diff --git a/.gitignore b/.gitignore
index a5d233be..1a31535f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,34 +1,27 @@
-
*~
-*.dll
*.*~
*.mdb
*.pdb
*.pidb
-*.vcproj
*.user
*.ncb
*.aps
*.suo
-*.sln
*.userprefs
*.usertasks
*.orig
*.cache
*.ReSharper
-*/bin/*
-*/obj/*
-*/test-results/*
-/test-results/
-
-/examples/*/bin/*
-/examples/*/test-results/*
-/examples/*/obj/*
+bin/
+obj/
+deploy/
+test-results/
+test-results/
+/Release/*
/_UpgradeReport_Files/*
/redist/*.zip
*_ReSharper.*/**
->>>>>>> dc06fc695339fb920a153bad7a131c47f57ac7d7:.gitignore
diff --git a/MongoDB.GridFS/AssemblyInfo.cs b/AssemblyInfoGlobal.cs
similarity index 50%
rename from MongoDB.GridFS/AssemblyInfo.cs
rename to AssemblyInfoGlobal.cs
index 65dd20a6..d595b24c 100644
--- a/MongoDB.GridFS/AssemblyInfo.cs
+++ b/AssemblyInfoGlobal.cs
@@ -1,26 +1,16 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
+using System.Reflection;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
-[assembly: AssemblyTitle("MongoDB.GridFS")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("")]
-[assembly: AssemblyCopyright("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("MongoDB-CSharp")]
+[assembly: AssemblyCopyright("MongoDB-CSharp")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
-
-[assembly: AssemblyVersion("1.0.*")]
-
-// The following attributes are used to specify the signing key for the assembly,
-// if desired. See the Mono documentation for more information about signing.
-
-[assembly: AssemblyDelaySign(false)]
-[assembly: AssemblyKeyFile("")]
+
+[assembly: AssemblyVersion("0.90.0.1")]
diff --git a/Deploy.proj b/Deploy.proj
new file mode 100644
index 00000000..133683f8
--- /dev/null
+++ b/Deploy.proj
@@ -0,0 +1,61 @@
+
+
+
+
+
+ $(MSBuildProjectDirectory)\tools\MSBuild.Community.Tasks
+ $(MSBuildProjectDirectory)\tools\MSBuild.ExtensionPack
+ $(MSBuildProjectDirectory)\redist
+ $(DeployPath)\tmp
+ $(MSBuildProjectDirectory)\MongoDB-CSharp.sln
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ $(DeployPath)\MongoDB-CSharp.zip
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/MongoDB-CSharp-2010.sln b/MongoDB-CSharp-2010.sln
new file mode 100644
index 00000000..5b360815
--- /dev/null
+++ b/MongoDB-CSharp-2010.sln
@@ -0,0 +1,116 @@
+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{4345382B-FAA2-46E2-99CF-C90ACA2DD574}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{AEFFB75E-9365-4BC6-87E9-148CEECA0C0C}"
+EndProject
+Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "SimpleVB", "examples\SimpleVB\SimpleVB.vbproj", "{1BAAE3D8-7720-4AA5-9335-E59824E7B667}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Simple", "examples\Simple\Simple.csproj", "{131BDB5F-5C6F-4AC7-B03E-394B1B75E120}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB", "source\MongoDB\MongoDB.csproj", "{B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.GridFS", "source\MongoDB.GridFS\MongoDB.GridFS.csproj", "{B42DBBF9-0A1F-4749-9787-013BF8D8F435}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.GridFS.Tests", "source\MongoDB.GridFS.Tests\MongoDB.GridFS.Tests.csproj", "{0C293FE9-F670-4FEF-A60F-20F8C978B1CD}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Tests", "source\MongoDB.Tests\MongoDB.Tests.csproj", "{C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Benchmark", "tools\Benchmark\Benchmark.csproj", "{5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {1BAAE3D8-7720-4AA5-9335-E59824E7B667}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {1BAAE3D8-7720-4AA5-9335-E59824E7B667}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {1BAAE3D8-7720-4AA5-9335-E59824E7B667}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {1BAAE3D8-7720-4AA5-9335-E59824E7B667}.Release|Any CPU.Build.0 = Release|Any CPU
+ {131BDB5F-5C6F-4AC7-B03E-394B1B75E120}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {131BDB5F-5C6F-4AC7-B03E-394B1B75E120}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {131BDB5F-5C6F-4AC7-B03E-394B1B75E120}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {131BDB5F-5C6F-4AC7-B03E-394B1B75E120}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B42DBBF9-0A1F-4749-9787-013BF8D8F435}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B42DBBF9-0A1F-4749-9787-013BF8D8F435}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B42DBBF9-0A1F-4749-9787-013BF8D8F435}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B42DBBF9-0A1F-4749-9787-013BF8D8F435}.Release|Any CPU.Build.0 = Release|Any CPU
+ {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Release|Any CPU.Build.0 = Release|Any CPU
+ {C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}.Release|Any CPU.Build.0 = Release|Any CPU
+ {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {1BAAE3D8-7720-4AA5-9335-E59824E7B667} = {4345382B-FAA2-46E2-99CF-C90ACA2DD574}
+ {131BDB5F-5C6F-4AC7-B03E-394B1B75E120} = {4345382B-FAA2-46E2-99CF-C90ACA2DD574}
+ {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B} = {AEFFB75E-9365-4BC6-87E9-148CEECA0C0C}
+ EndGlobalSection
+ GlobalSection(MonoDevelopProperties) = preSolution
+ StartupItem = MongoDBDriver\MongoDB.Driver.csproj
+ Policies = $0
+ $0.DotNetNamingPolicy = $1
+ $1.DirectoryNamespaceAssociation = None
+ $1.ResourceNamePolicy = FileFormatDefault
+ $0.TextStylePolicy = $2
+ $2.FileWidth = 120
+ $2.TabWidth = 4
+ $2.inheritsSet = Mono
+ $2.inheritsScope = text/plain
+ $2.scope = text/plain
+ $0.TextStylePolicy = $3
+ $3.FileWidth = 120
+ $3.NoTabsAfterNonTabs = True
+ $3.inheritsSet = VisualStudio
+ $3.inheritsScope = text/plain
+ $3.scope = text/x-csharp
+ $0.CSharpFormattingPolicy = $4
+ $4.IndentSwitchBody = True
+ $4.MethodBraceStyle = EndOfLineWithoutSpace
+ $4.BeforeMethodCallParentheses = False
+ $4.BeforeMethodDeclarationParentheses = False
+ $4.BeforeConstructorDeclarationParentheses = False
+ $4.BeforeDelegateDeclarationParentheses = False
+ $4.NewParentheses = False
+ $4.MethodBraceStyle = EndOfLine
+ $4.ConstructorBraceStyle = EndOfLine
+ $4.DestructorBraceStyle = EndOfLine
+ $4.BeforeMethodCallParentheses = False
+ $4.BeforeMethodDeclarationParentheses = False
+ $4.BeforeConstructorDeclarationParentheses = False
+ $4.NewParentheses = False
+ $4.IfParentheses = False
+ $4.WhileParentheses = False
+ $4.ForParentheses = False
+ $4.ForeachParentheses = False
+ $4.CatchParentheses = False
+ $4.SwitchParentheses = False
+ $4.LockParentheses = False
+ $4.UsingParentheses = False
+ $4.inheritsSet = Mono
+ $4.inheritsScope = text/x-csharp
+ $4.scope = text/x-csharp
+ $0.TextStylePolicy = $5
+ $5.FileWidth = 120
+ $5.EolMarker = Windows
+ $5.inheritsSet = VisualStudio
+ $5.inheritsScope = text/plain
+ $5.scope = text/x-vb
+ EndGlobalSection
+EndGlobal
diff --git a/MongoDBDriver.sln b/MongoDB-CSharp.sln
similarity index 65%
rename from MongoDBDriver.sln
rename to MongoDB-CSharp.sln
index fc6814ab..007cc71d 100644
--- a/MongoDBDriver.sln
+++ b/MongoDB-CSharp.sln
@@ -1,30 +1,23 @@
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
-# SharpDevelop 3.1.0.4890
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Driver", "MongoDBDriver\MongoDB.Driver.csproj", "{B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}"
-EndProject
-Project("{9344bdbb-3e7f-41fc-a0dd-8665d75ee146}") = "Packages", "Packages.mdproj", "{502F3381-58AA-461B-B9D8-12578A588C61}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Driver.Tests", "MongoDB.Net-Tests\MongoDB.Driver.Tests.csproj", "{C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}"
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{4345382B-FAA2-46E2-99CF-C90ACA2DD574}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Linq", "MongoDB.Linq\MongoDB.Linq.csproj", "{2E48891E-72F9-445D-9A5A-DBA787BFFE9E}"
+Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "SimpleVB", "examples\SimpleVB\SimpleVB.vbproj", "{1BAAE3D8-7720-4AA5-9335-E59824E7B667}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Linq.Tests", "MongoDB.Linq.Tests\MongoDB.Linq.Tests.csproj", "{870FE8E1-3461-4C79-BF25-9C35E41BF582}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Simple", "examples\Simple\Simple.csproj", "{131BDB5F-5C6F-4AC7-B03E-394B1B75E120}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Driver.Benchmark", "MongoDB.Driver.Benchmark\MongoDB.Driver.Benchmark.csproj", "{5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB", "source\MongoDB\MongoDB.csproj", "{B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.GridFS", "MongoDB.GridFS\MongoDB.GridFS.csproj", "{B42DBBF9-0A1F-4749-9787-013BF8D8F435}"
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{AEFFB75E-9365-4BC6-87E9-148CEECA0C0C}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.GridFS.Tests", "MongoDB.GridFS.Tests\MongoDB.GridFS.Tests.csproj", "{0C293FE9-F670-4FEF-A60F-20F8C978B1CD}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.GridFS", "source\MongoDB.GridFS\MongoDB.GridFS.csproj", "{B42DBBF9-0A1F-4749-9787-013BF8D8F435}"
EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{4345382B-FAA2-46E2-99CF-C90ACA2DD574}"
- ProjectSection(SolutionItems) = postProject
- EndProjectSection
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.GridFS.Tests", "source\MongoDB.GridFS.Tests\MongoDB.GridFS.Tests.csproj", "{0C293FE9-F670-4FEF-A60F-20F8C978B1CD}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Simple", "examples\Simple\Simple.csproj", "{131BDB5F-5C6F-4AC7-B03E-394B1B75E120}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Tests", "source\MongoDB.Tests\MongoDB.Tests.csproj", "{C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}"
EndProject
-Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "SimpleVB", "examples\SimpleVB\SimpleVB.vbproj", "{1BAAE3D8-7720-4AA5-9335-E59824E7B667}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Benchmark", "tools\Benchmark\Benchmark.csproj", "{5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -32,32 +25,14 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Release|Any CPU.Build.0 = Release|Any CPU
- {131BDB5F-5C6F-4AC7-B03E-394B1B75E120}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {131BDB5F-5C6F-4AC7-B03E-394B1B75E120}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {131BDB5F-5C6F-4AC7-B03E-394B1B75E120}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {131BDB5F-5C6F-4AC7-B03E-394B1B75E120}.Release|Any CPU.Build.0 = Release|Any CPU
{1BAAE3D8-7720-4AA5-9335-E59824E7B667}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BAAE3D8-7720-4AA5-9335-E59824E7B667}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BAAE3D8-7720-4AA5-9335-E59824E7B667}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BAAE3D8-7720-4AA5-9335-E59824E7B667}.Release|Any CPU.Build.0 = Release|Any CPU
- {2E48891E-72F9-445D-9A5A-DBA787BFFE9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {2E48891E-72F9-445D-9A5A-DBA787BFFE9E}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {2E48891E-72F9-445D-9A5A-DBA787BFFE9E}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {2E48891E-72F9-445D-9A5A-DBA787BFFE9E}.Release|Any CPU.Build.0 = Release|Any CPU
- {502F3381-58AA-461B-B9D8-12578A588C61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {502F3381-58AA-461B-B9D8-12578A588C61}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Release|Any CPU.Build.0 = Release|Any CPU
- {870FE8E1-3461-4C79-BF25-9C35E41BF582}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {870FE8E1-3461-4C79-BF25-9C35E41BF582}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {870FE8E1-3461-4C79-BF25-9C35E41BF582}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {870FE8E1-3461-4C79-BF25-9C35E41BF582}.Release|Any CPU.Build.0 = Release|Any CPU
+ {131BDB5F-5C6F-4AC7-B03E-394B1B75E120}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {131BDB5F-5C6F-4AC7-B03E-394B1B75E120}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {131BDB5F-5C6F-4AC7-B03E-394B1B75E120}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {131BDB5F-5C6F-4AC7-B03E-394B1B75E120}.Release|Any CPU.Build.0 = Release|Any CPU
{B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -66,12 +41,26 @@ Global
{B42DBBF9-0A1F-4749-9787-013BF8D8F435}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B42DBBF9-0A1F-4749-9787-013BF8D8F435}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B42DBBF9-0A1F-4749-9787-013BF8D8F435}.Release|Any CPU.Build.0 = Release|Any CPU
+ {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Release|Any CPU.Build.0 = Release|Any CPU
{C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}.Release|Any CPU.Build.0 = Release|Any CPU
- {502F3381-58AA-461B-B9D8-12578A588C61}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {502F3381-58AA-461B-B9D8-12578A588C61}.Release|Any CPU.Build.0 = Release|Any CPU
+ {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {1BAAE3D8-7720-4AA5-9335-E59824E7B667} = {4345382B-FAA2-46E2-99CF-C90ACA2DD574}
+ {131BDB5F-5C6F-4AC7-B03E-394B1B75E120} = {4345382B-FAA2-46E2-99CF-C90ACA2DD574}
+ {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B} = {AEFFB75E-9365-4BC6-87E9-148CEECA0C0C}
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
StartupItem = MongoDBDriver\MongoDB.Driver.csproj
@@ -92,6 +81,28 @@ Global
$3.inheritsScope = text/plain
$3.scope = text/x-csharp
$0.CSharpFormattingPolicy = $4
+ $4.IndentSwitchBody = True
+ $4.MethodBraceStyle = EndOfLineWithoutSpace
+ $4.BeforeMethodCallParentheses = False
+ $4.BeforeMethodDeclarationParentheses = False
+ $4.BeforeConstructorDeclarationParentheses = False
+ $4.BeforeDelegateDeclarationParentheses = False
+ $4.NewParentheses = False
+ $4.MethodBraceStyle = EndOfLine
+ $4.ConstructorBraceStyle = EndOfLine
+ $4.DestructorBraceStyle = EndOfLine
+ $4.BeforeMethodCallParentheses = False
+ $4.BeforeMethodDeclarationParentheses = False
+ $4.BeforeConstructorDeclarationParentheses = False
+ $4.NewParentheses = False
+ $4.IfParentheses = False
+ $4.WhileParentheses = False
+ $4.ForParentheses = False
+ $4.ForeachParentheses = False
+ $4.CatchParentheses = False
+ $4.SwitchParentheses = False
+ $4.LockParentheses = False
+ $4.UsingParentheses = False
$4.inheritsSet = Mono
$4.inheritsScope = text/x-csharp
$4.scope = text/x-csharp
@@ -102,11 +113,4 @@ Global
$5.inheritsScope = text/plain
$5.scope = text/x-vb
EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(NestedProjects) = preSolution
- {1BAAE3D8-7720-4AA5-9335-E59824E7B667} = {4345382B-FAA2-46E2-99CF-C90ACA2DD574}
- {131BDB5F-5C6F-4AC7-B03E-394B1B75E120} = {4345382B-FAA2-46E2-99CF-C90ACA2DD574}
- EndGlobalSection
EndGlobal
diff --git a/MongoDB.Driver.Benchmark/Main.cs b/MongoDB.Driver.Benchmark/Main.cs
deleted file mode 100644
index 18e513a3..00000000
--- a/MongoDB.Driver.Benchmark/Main.cs
+++ /dev/null
@@ -1,265 +0,0 @@
-using System;
-using System.IO;
-using System.Threading;
-
-using MongoDB.Driver;
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver.Benchmark
-{
- ///
- /// This is the standard 10gen benchmark program.
- ///
- class MainClass
- {
- static Document small = new Document();
- static Document medium = new Document();
- static Document large = new Document();
-
- static int trials = 1;
- static int perTrial = 5000;
- static int batchSize = 100;
-
- public static void Main (string[] args)
- {
- SetupDocuments();
-
- Mongo m = new Mongo();
- m.Connect();
- Database db = m["benchmark"];
-
- db.MetaData.DropDatabase();
- Console.WriteLine("Starting Tests");
-
- RunEncodeTest("encode (small)",small);
- RunEncodeTest("encode (medium)", medium);
- RunEncodeTest("encode (large)", large);
-
- RunDecodeTest("decode (small)",small);
- RunDecodeTest("decode (medium)", medium);
- RunDecodeTest("decode (large)", large);
-
- db.MetaData.DropDatabase();
- RunInsertTest("insert (small, no index)", db, "small_none",small,false,false);
- RunInsertTest("insert (medium, no index)", db, "medium_none",medium,false,false);
- RunInsertTest("insert (large, no index)", db, "large_none",large,false,false);
-
- RunInsertTest("insert (small, indexed)", db, "small_index",small,true,false);
- RunInsertTest("insert (medium, indexed)", db, "medium_index",medium,true,false);
- RunInsertTest("insert (large, indexed)", db, "large_index",large,true,false);
-
- RunInsertTest("batch insert (small, no index)", db, "small_bulk",small,false,true);
- RunInsertTest("batch insert (medium, no index)", db, "medium_bulk",medium,false,true);
- RunInsertTest("batch insert (large, no index)", db, "large_bulk",large,false,true);
-
- Document fonespec = new Document().Append("x",perTrial/2);
- RunFindTest("find_one (small, no index)", db, "small_none",fonespec,false);
- RunFindTest("find_one (medium, no index)", db, "medium_none",fonespec,false);
- RunFindTest("find_one (large, no index)", db, "large_none",fonespec,false);
-
- RunFindTest("find_one (small, indexed)", db, "small_index",fonespec,false);
- RunFindTest("find_one (medium, indexed)", db, "medium_index",fonespec,false);
- RunFindTest("find_one (large, indexed)", db, "large_index",fonespec,false);
-
- RunFindTest("find (small, no index)", db, "small_none",fonespec,true);
- RunFindTest("find (medium, no index)", db, "medium_none",fonespec,true);
- RunFindTest("find (large, no index)", db, "large_none",fonespec,true);
-
- RunFindTest("find (small, indexed)", db, "small_index",fonespec,true);
- RunFindTest("find (medium, indexed)", db, "medium_index",fonespec,true);
- RunFindTest("find (large, indexed)", db, "large_index",fonespec,true);
-
- Document findRange = new Document().Append("x",new Document().Append("$gt",perTrial/2).Append("$lt", perTrial/2 + batchSize));
- RunFindTest("find range (small, indexed)", db, "small_index",findRange,true);
- RunFindTest("find range (medium, indexed)", db, "medium_index",findRange,true);
- RunFindTest("find range (large, indexed)", db, "large_index",findRange,true);
-
- System.Console.WriteLine("Press any key to continue...");
- System.Console.ReadKey();
- }
-
- static void SetupDocuments(){
- medium.Append("integer", (int) 5);
- medium.Append("number", 5.05);
- medium.Append("boolean", false);
- medium.Append("array", new String[]{"test","benchmark"});
-
- large.Append("base_url", "http://www.example.com/test-me");
- large.Append("total_word_count", (int)6743);
- large.Append("access_time", DateTime.UtcNow);
- large.Append("meta_tags", new Document()
- .Append("description", "i am a long description string")
- .Append("author", "Holly Man")
- .Append("dynamically_created_meta_tag", "who know\n what"));
- large.Append("page_structure", new Document().Append("counted_tags", 3450)
- .Append("no_of_js_attached", (int)10)
- .Append("no_of_images", (int)6));
- string[] words = new string[]{"10gen","web","open","source","application","paas",
- "platform-as-a-service","technology","helps",
- "developers","focus","building","mongodb","mongo"};
- string[] harvestedWords = new string[words.Length * 20];
- for(int i = 0; i < words.Length * 20; i++){
- harvestedWords[i] = words[i % words.Length];
- }
- large.Append("harvested_words", harvestedWords);
- }
-#region Insert Tests
- static void RunInsertTest(string name, Database db, string col, Document doc, bool index, bool bulk){
- TimeSpan lowest = TimeSpan.MaxValue;
- for(int i = 0; i < trials; i++){
- SetupInsert(db,"col",index);
- TimeSpan ret = TimeInsert(db, col,doc, bulk);
- if(ret < lowest) lowest = ret;
- }
- int opsSec = (int)(perTrial/lowest.TotalSeconds);
- Console.Out.WriteLine(String.Format("{0}{1} {2}", name + new string('.', 55 - name.Length), opsSec, lowest));
- }
-
- static void SetupInsert(Database db, string col, bool index){
- try{
- db.MetaData.DropCollection(col);
- if(index){
- Document idx = new Document().Append("x", IndexOrder.Ascending);
- db[col].MetaData.CreateIndex(idx,false);
- }
- }catch(MongoCommandException){
- //swallow for now.
- }
- }
-
- static TimeSpan TimeInsert(Database db, string col, Document doc, bool bulk){
- DateTime start = DateTime.Now;
- if(bulk){
- DoBulkInsert(db,col,doc, batchSize);
- }else{
- DoInsert(db,col,doc);
- }
- DateTime stop = DateTime.Now;
- TimeSpan t = stop - start;
- return t;
- }
-
- static void DoInsert(Database db, string col, Document doc){
- for(int i = 0; i < perTrial; i++){
- Document ins = new Document();
- doc.CopyTo(ins);
- ins.Append("x", i);
- db[col].Insert(ins);
- }
- }
-
- static void DoBulkInsert(Database db, string col, Document doc, int size){
- for(int i = 0; i < perTrial / size; i++){
- Document[] docs = new Document[size];
- for(int f = 0; f < docs.Length; f++){
- Document ins = new Document();
- doc.CopyTo(ins);
- docs[f] = ins;
- }
- db[col].Insert(docs);
- }
- }
-#endregion
-
-#region Encode Tests
- static void RunEncodeTest(string name, Document doc){
- TimeSpan lowest = TimeSpan.MaxValue;
- for(int i = 0; i < trials; i++){
- TimeSpan ret = TimeEncode(doc);
- if(ret < lowest) lowest = ret;
- }
- int opsSec = (int)(perTrial/lowest.TotalSeconds);
- Console.Out.WriteLine(String.Format("{0}{1} {2}", name + new string('.', 55 - name.Length), opsSec, lowest));
- }
-
- static TimeSpan TimeEncode(Document doc){
- DateTime start = DateTime.Now;
- DoEncode(doc);
- DateTime stop = DateTime.Now;
- TimeSpan t = stop - start;
- return t;
- }
-
- static void DoEncode(Document doc){
- MemoryStream ms = new MemoryStream();
- for(int i = 0; i < perTrial; i++){
- BsonWriter writer = new BsonWriter(ms);
- writer.Write(doc);
- ms.Seek(0,SeekOrigin.Begin);
- }
- }
-#endregion
-
- static void RunDecodeTest(string name, Document doc){
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
- writer.Write(doc);
-
- byte[] buff = ms.ToArray();
-
- TimeSpan lowest = TimeSpan.MaxValue;
- for(int i = 0; i < trials; i++){
- TimeSpan ret = TimeDecode(buff);
- if(ret < lowest) lowest = ret;
- }
- int opsSec = (int)(perTrial/lowest.TotalSeconds);
- Console.Out.WriteLine(String.Format("{0}{1} {2}", name + new string('.', 55 - name.Length), opsSec, lowest));
- }
-
- static TimeSpan TimeDecode(byte[] doc){
- DateTime start = DateTime.Now;
- DoDecode(doc);
- DateTime stop = DateTime.Now;
- TimeSpan t = stop - start;
- return t;
- }
-
- static void DoDecode(byte[] buff){
- MemoryStream ms = new MemoryStream(buff);
- for(int i = 0; i < perTrial; i++){
- BsonReader reader = new BsonReader(ms);
- reader.Read();
- ms.Seek(0,SeekOrigin.Begin);
- }
- }
-
- #region Find Tests
- static void RunFindTest(string name, Database db, string col, Document spec, bool range){
- TimeSpan lowest = TimeSpan.MaxValue;
- for(int i = 0; i < trials; i++){
- TimeSpan ret = TimeFind(db, col, spec, range);
- if(ret < lowest) lowest = ret;
- }
- int opsSec = (int)(perTrial/lowest.TotalSeconds);
- Console.Out.WriteLine(String.Format("{0}{1} {2}", name + new string('.', 55 - name.Length), opsSec, lowest));
- }
-
- static TimeSpan TimeFind(Database db, string col,Document psec, bool range){
- DateTime start = DateTime.Now;
- if(range){
- DoFindOne(db,col,psec);
- }else{
- DoFind(db,col,psec);
- }
- DateTime stop = DateTime.Now;
- TimeSpan t = stop - start;
- return t;
- }
-
- static void DoFindOne(Database db, string col, Document spec){
- for(int i = 0; i < perTrial; i++){
- db[col].FindOne(spec);
- }
- }
-
- static void DoFind(Database db, string col, Document spec){
- for(int i = 0; i < perTrial; i++){
- ICursor cur = db[col].Find(spec);
- foreach(Document d in cur.Documents){
- }
- }
- }
- #endregion
-
- }
-}
\ No newline at end of file
diff --git a/MongoDB.Driver.Benchmark/MongoDB.Driver.Benchmark.csproj b/MongoDB.Driver.Benchmark/MongoDB.Driver.Benchmark.csproj
deleted file mode 100644
index d1f6247d..00000000
--- a/MongoDB.Driver.Benchmark/MongoDB.Driver.Benchmark.csproj
+++ /dev/null
@@ -1,44 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.21022
- 2.0
- {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}
- Exe
- MongoDB.Driver.Benchmark
- MongoDB.Driver.Benchmark
- v3.5
-
-
- true
- full
- false
- bin\Debug
- DEBUG
- prompt
- 4
-
-
- none
- false
- bin\Release
- prompt
- 4
-
-
-
-
-
-
-
-
-
-
- {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}
- MongoDB.Driver
-
-
-
-
\ No newline at end of file
diff --git a/MongoDB.GridFS.Tests/AssemblyInfo.cs b/MongoDB.GridFS.Tests/AssemblyInfo.cs
deleted file mode 100644
index a393bb35..00000000
--- a/MongoDB.GridFS.Tests/AssemblyInfo.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
-
-// Information about this assembly is defined by the following attributes.
-// Change them to the values specific to your project.
-
-[assembly: AssemblyTitle("MongoDB.GridFS.Tests")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("")]
-[assembly: AssemblyCopyright("")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
-// The form "{Major}.{Minor}.*" will automatically update the build and revision,
-// and "{Major}.{Minor}.{Build}.*" will update just the revision.
-
-[assembly: AssemblyVersion("1.0.*")]
-
-// The following attributes are used to specify the signing key for the assembly,
-// if desired. See the Mono documentation for more information about signing.
-
-[assembly: AssemblyDelaySign(false)]
-[assembly: AssemblyKeyFile("")]
diff --git a/MongoDB.GridFS.Tests/MongoDB.GridFS.Tests.csproj b/MongoDB.GridFS.Tests/MongoDB.GridFS.Tests.csproj
deleted file mode 100644
index b8d868c9..00000000
--- a/MongoDB.GridFS.Tests/MongoDB.GridFS.Tests.csproj
+++ /dev/null
@@ -1,62 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.21022
- 2.0
- {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}
- Library
- MongoDB.GridFS.Tests
- v3.5
- MongoDB.GridFS.Tests
-
-
- true
- full
- false
- bin\Debug
- DEBUG
- prompt
- 4
- false
-
-
- none
- false
- bin\Release
- prompt
- 4
- false
-
-
-
-
- False
- ..\redist\nunit.framework.dll
-
-
-
-
-
-
-
-
-
-
-
-
- {C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}
- MongoDB.Driver.Tests
-
-
- {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}
- MongoDB.Driver
-
-
- {B42DBBF9-0A1F-4749-9787-013BF8D8F435}
- MongoDB.GridFS
-
-
-
-
\ No newline at end of file
diff --git a/MongoDB.GridFS.Tests/MongoDB.GridFS.Tests.dll.config b/MongoDB.GridFS.Tests/MongoDB.GridFS.Tests.dll.config
deleted file mode 100644
index a24d6958..00000000
--- a/MongoDB.GridFS.Tests/MongoDB.GridFS.Tests.dll.config
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/MongoDB.GridFS.Tests/Properties/AssemblyInfo.cs b/MongoDB.GridFS.Tests/Properties/AssemblyInfo.cs
deleted file mode 100644
index 24d8cdcc..00000000
--- a/MongoDB.GridFS.Tests/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("MongoDB.Driver.GridFS.Tests")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("MongoDB.Driver.GridFS.Tests")]
-[assembly: AssemblyCopyright("Copyright © Microsoft 2009")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("94ed0246-0a62-4e43-94fb-bd52a9efc901")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/MongoDB.GridFS/GridChunk.cs b/MongoDB.GridFS/GridChunk.cs
deleted file mode 100644
index b4397a6d..00000000
--- a/MongoDB.GridFS/GridChunk.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using MongoDB.Driver;
-
-namespace MongoDB.Driver.GridFS
-{
- public class GridChunk : IComparable //TODO Change back to a struct
- {
- public GridChunk(object filesId, int n, byte[] data){
-// OidGenerator oidGenerator = new OidGenerator();
-// this.id = oidGenerator.Generate();
- this.filesId = filesId;
- this.n = n;
- this.data = new Binary(data);
- }
-
- public GridChunk(Document doc)
- {
- this.id = (Oid)doc["_id"];
- this.filesId = (Object)doc["files_id"];
- this.n = Convert.ToInt32(doc["n"]);
- this.data = (Binary)doc["data"];
- }
-
- // object id of the chunk in the _chunks collection
- private Object id;
- public Object Id{
- get { return this.id; }
- set { this.id = value; }
- }
- // id value of the owning {{files}} collection entry
- private Object filesId;
- public Object FilesId{
- get { return this.filesId; }
- set { this.filesId = value; }
- }
-
- //Chunk number
- private int n;
- public int N{
- get { return this.n; }
- set { this.n = value; }
- }
-
- private Binary data;
- public Binary Data{
- get { return this.data; }
- }
-
- //Allow sorting by chunk number
- public int CompareTo(Object obj){
- GridChunk chunk = (GridChunk)obj;
- return this.n.CompareTo(chunk.N);
- }
-
- public Document ToDocument()
- {
- Document doc = new Document();
- if(this.id != null) doc["_id"] = this.id;
- doc["files_id"] = this.filesId;
- doc["n"] = this.n;
- doc["data"] = this.data;
- return doc;
- }
-
- }
-}
diff --git a/MongoDB.GridFS/GridException.cs b/MongoDB.GridFS/GridException.cs
deleted file mode 100644
index 64d89e14..00000000
--- a/MongoDB.GridFS/GridException.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-using System;
-
-namespace MongoDB.GridFS
-{
- public class MongoGridFSException : Exception
- {
- private string filename;
- public string Filename
- {
- get { return filename; }
- }
-
- public MongoGridFSException(string message, string filename, Exception inner)
- : base(message, inner)
- {
- this.filename = filename;
- }
- }
-}
diff --git a/MongoDB.GridFS/GridFileStream.cs b/MongoDB.GridFS/GridFileStream.cs
deleted file mode 100644
index 2fe398df..00000000
--- a/MongoDB.GridFS/GridFileStream.cs
+++ /dev/null
@@ -1,389 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.IO;
-
-using MongoDB.Driver;
-
-namespace MongoDB.GridFS
-{
- ///
- /// Stream for reading and writing to a file in GridFS.
- ///
- ///
- /// When using the stream for random io it is possible to produce chunks in the begining and middle of the
- /// file that are not full size followed by other chunks that are full size. This only affects the md5 sum
- /// that is calculated on the file on close. Because of this do not rely on the md5 sum of a file when doing
- /// random io. Writing to the stream sequentially works fine and will produce a consistent md5.
- ///
- public class GridFileStream : Stream
- {
-
- private IMongoCollection files;
- private IMongoCollection chunks;
- private Document chunk;
- private bool chunkDirty;
- private long chunkLower = -1;
- private long chunkUpper = -1;
-
- private byte[] buffer;
- private byte[] blankBuffer;
- private int buffPosition;
- private int highestBuffPosition;
- private long highestPosWritten;
-
-
- #region Properties
- private GridFileInfo gridFileInfo;
- public GridFileInfo GridFileInfo {
- get { return gridFileInfo; }
- set { gridFileInfo = value; }
- }
-
- private bool canRead;
- public override bool CanRead {
- get { return canRead; }
- }
-
- private bool canWrite;
- public override bool CanWrite {
- get { return canRead; }
- }
-
- public override bool CanSeek {
- get { return true; }
- }
-
- public override long Length {
- get {
- return gridFileInfo.Length;
- }
- }
-
- private long position;
- public override long Position {
- get {
- return position;
- }
- set {
- this.Seek(value, SeekOrigin.Begin);
- }
- }
- #endregion
-
- public GridFileStream(GridFileInfo gridfileinfo,IMongoCollection files, IMongoCollection chunks, FileAccess access){
- switch (access){
- case FileAccess.Read:
- canRead = true;
- break;
- case FileAccess.ReadWrite:
- canRead = true;
- canWrite = true;
- break;
- case FileAccess.Write:
- canWrite = true;
- break;
- }
- this.gridFileInfo = gridfileinfo;
- this.files = files;
- this.chunks = chunks;
- this.buffer = new byte[gridFileInfo.ChunkSize];
- this.blankBuffer = new byte[gridFileInfo.ChunkSize];
- this.highestPosWritten = this.gridFileInfo.Length;
- this.MoveTo(0);
- }
-
- ///
- /// Reads data from the stream into the specified array. It will fill the array in starting at offset and
- /// adding count bytes returning the number of bytes read from the stream.
- ///
- public override int Read(byte[] array, int offset, int count){
- int bytesLeftToRead = count;
- int bytesRead = 0;
- while(bytesLeftToRead > 0 && this.position < this.Length){
- int buffAvailable = buffer.Length - buffPosition;
- int readCount = 0;
- if(buffAvailable > bytesLeftToRead){
- readCount = bytesLeftToRead;
- }else{
- readCount = buffAvailable;
- }
- if(readCount + position > highestPosWritten){
- //adjust readcount so that we don't read past the end of file.
- readCount = readCount - (int)(readCount + position - highestPosWritten);
- }
- Array.Copy(buffer,buffPosition,array,offset,readCount);
- buffPosition += readCount;
- bytesLeftToRead -= readCount;
- bytesRead += readCount;
- offset += readCount;
- MoveTo(position + readCount);
- }
- return bytesRead;
- }
-
- private void ValidateReadState(byte[] array, int offset, int count){
- if (array == null){
- throw new ArgumentNullException("array", new Exception("array is null"));
- }
- else if (offset < 0){
- throw new ArgumentOutOfRangeException("offset", new Exception("offset is negative"));
- }
- else if (count < 0){
- throw new ArgumentOutOfRangeException("count", new Exception("count is negative"));
- }
- else if ((array.Length - offset) < count){
- throw new MongoGridFSException("Invalid count argument", gridFileInfo.FileName, null);
- }
- else if (!canRead){
- throw new MongoGridFSException("Reading this file is not supported", gridFileInfo.FileName, null);
- }
- }
-
- ///
- /// Copies from the source array into the grid file.
- ///
- ///
- /// A The source array to copy from.
- ///
- ///
- /// A The offset within the source array.
- ///
- ///
- /// A The number of bytes from within the source array to copy.
- ///
- public override void Write(byte[] array, int offset, int count){
- ValidateWriteState(array,offset,count);
-
- int bytesLeftToWrite = count;
- while(bytesLeftToWrite > 0){
- int buffAvailable = buffer.Length - buffPosition;
- int writeCount = 0;
- if(buffAvailable > bytesLeftToWrite){
- writeCount = bytesLeftToWrite;
- }else{
- writeCount = buffAvailable;
- }
- Array.Copy(array,offset,buffer,buffPosition,writeCount);
- chunkDirty = true;
- buffPosition += writeCount;
- offset += writeCount;
- bytesLeftToWrite -= writeCount;
- MoveTo(position + writeCount);
- highestPosWritten = Math.Max(highestPosWritten, position);
- }
- }
-
- private void ValidateWriteState(byte[] array, int offset, int count){
- if (array == null){
- throw new ArgumentNullException("array", new Exception("array is null"));
- }else if (offset < 0){
- throw new ArgumentOutOfRangeException("offset", new Exception("offset is negative"));
- }else if (count < 0){
- throw new ArgumentOutOfRangeException("count",new Exception("count is negative"));
- }else if ((array.Length - offset) < count){
- throw new MongoGridFSException("Invalid count argument", gridFileInfo.FileName, null);
- }else if (!canWrite){
- throw new System.NotSupportedException("Stream does not support writing.");
- }
- }
-
-
- ///
- /// Flushes any changes to current chunk to the database. It can be called in client code at any time or it
- /// will automatically be called on Close() and when the stream position moves off the bounds of the current
- /// chunk.
- ///
- public override void Flush(){
- if(chunkDirty == false) return;
- //avoid a copy if possible.
- if(highestBuffPosition == buffer.Length){
- chunk["data"] = new Binary(buffer);
- }else{
- byte[] data = new byte[highestBuffPosition];
- Array.Copy(buffer,data,highestBuffPosition);
- chunk["data"] = new Binary(data);
- }
-
-
- if(chunk.Contains("_id")){
- chunks.Update(chunk);
- }else{
- chunks.Insert(chunk);
- }
- this.gridFileInfo.Length = highestPosWritten;
- }
-
- ///
- /// Seek to any location in the stream. Seeking past the end of the file is allowed. Any writes to that
- /// location will cause the file to grow to that size. Any holes that may be created from the seek will
- /// be zero filled on close.
- ///
- public override long Seek(long offset, SeekOrigin origin){
- if ((origin < SeekOrigin.Begin) || (origin > SeekOrigin.End)){
- throw new ArgumentException("Invalid Seek Origin");
- }
-
- switch (origin){
- case SeekOrigin.Begin:
- if (offset < 0){
- throw new ArgumentException("Attempted seeking before the begining of the stream");
- }else{
- MoveTo(offset);
- }
- break;
- case SeekOrigin.Current:
- MoveTo(position + offset);
- break;
- case SeekOrigin.End:
- if (offset <= 0){
- throw new ArgumentException("Attempted seeking after the end of the stream");
- }
- MoveTo(this.Length - offset);
- break;
- }
- return position;
- }
-
- ///
- /// Sets the length of this stream to the given value.
- ///
- ///
- /// A
- ///
- public override void SetLength(long value){
- if(value < 0) throw new ArgumentOutOfRangeException("length");
- if(this.CanSeek == false || this.CanWrite == false) {
- throw new NotSupportedException("The stream does not support both writing and seeking.");
- }
-
- if(value < highestPosWritten) {
- TruncateAfter(value);
- }else{
- this.Seek(value, SeekOrigin.Begin);
- }
- chunkDirty = true;
- this.gridFileInfo.Length = value;
- highestPosWritten = value;
-
- }
-
- ///
- /// Close the stream and flush any changes to the database.
- ///
- public override void Close(){
- this.Flush();
- this.gridFileInfo.Length = highestPosWritten;
- EnsureNoHoles();
- string md5 = gridFileInfo.CalcMD5();
- gridFileInfo.Md5 = md5;
- this.files.Update(gridFileInfo.ToDocument());
- base.Close();
- }
-
- ///
- /// Moves the current position to the new position. If this causes a new chunk to need to be loaded it will take
- /// care of flushing the buffer and loading a new chunk.
- ///
- ///
- /// A designating where to go to.
- ///
- private void MoveTo(long position){
- this.position = position;
- int chunkSize = this.gridFileInfo.ChunkSize;
- bool chunkInRange = (chunk != null && position >= chunkLower && position < chunkUpper);
- if(chunkInRange == false){
- if(chunk != null && chunkDirty){
- highestBuffPosition = Math.Max(highestBuffPosition, buffPosition);
- this.Flush();
- }
- int chunknum = (int)Math.Floor((double)(position / chunkSize));
- Array.Copy(blankBuffer,buffer,buffer.Length);
- LoadOrCreateChunk(chunknum);
- chunkDirty = false;
- chunkLower = chunknum * chunkSize;
- chunkUpper = chunkLower + chunkSize;
- }
- buffPosition = (int)(position % chunkSize);
- highestBuffPosition = Math.Max(highestBuffPosition, buffPosition);
-
- }
-
- ///
- /// Loads a chunk from the chunks collection if it exists. Otherwise it creates a blank chunk Document.
- ///
- ///
- private void LoadOrCreateChunk(int num){
- Object fid = this.GridFileInfo.Id;
- Document spec = new Document().Append("files_id", fid).Append("n",num);
- chunk = this.chunks.FindOne(spec);
- if(chunk == null) {
- chunk = spec;
- highestBuffPosition = 0;
- }else{
- Binary b = (Binary)chunk["data"];
- highestBuffPosition = b.Bytes.Length;
- Array.Copy(b.Bytes,buffer, highestBuffPosition);
- }
- }
-
-
- ///
- /// Deletes all chunks after the specified position and clears out any extra bytes if the position doesn't fall on
- /// a chunk boundry.
- ///
- private void TruncateAfter(long value){
- int chunknum = CalcChunkNum(value);
- Document spec = new Document().Append("files_id", this.gridFileInfo.Id)
- .Append("n",new Document().Append("$gt",chunknum));
- this.chunks.Delete(spec);
- this.MoveTo(value );
- Array.Copy(blankBuffer,0,buffer,buffPosition, buffer.Length - buffPosition);
- highestBuffPosition = buffPosition;
- }
-
- private int CalcChunkNum(long position){
- int chunkSize = this.gridFileInfo.ChunkSize;
- return (int)Math.Floor((double)(position / chunkSize));
- }
-
- ///
- /// Makes sure that at least a skelton chunk exists for all numbers. If not the MD5 calculation will fail on a sparse file.
- ///
- private void EnsureNoHoles(){
- int highChunk = CalcChunkNum(this.GridFileInfo.Length);
- Document query = new Document().Append("files_id", this.GridFileInfo.Id)
- .Append("n", new Document()
- .Append("$lte",highChunk));
- Document sort = new Document().Append("n",1);
- Document fields = new Document().Append("_id", 1).Append("n",1);
-
- Binary data = new Binary(this.blankBuffer);
- int i = 0;
- using (ICursor cur = chunks.Find(new Document().Append("query",query).Append("sort",sort),0,0,fields)){
- foreach(Document doc in cur.Documents){
- int n = Convert.ToInt32(doc["n"]);
- if(i < n){
- while(i < n){
- chunks.Insert(new Document().Append("files_id", this.gridFileInfo.Id)
- .Append("n", i)
- .Append("data", data)
- );
- i++;
- }
- }else{
- i++;
- }
- }
- }
-
- }
-
- protected override void Dispose(bool disposing){
- this.canRead = false;
- this.canWrite = false;
-
- base.Dispose(disposing);
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDB.GridFS/MongoDB.GridFS.csproj b/MongoDB.GridFS/MongoDB.GridFS.csproj
deleted file mode 100644
index 83089bea..00000000
--- a/MongoDB.GridFS/MongoDB.GridFS.csproj
+++ /dev/null
@@ -1,49 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.21022
- 2.0
- {B42DBBF9-0A1F-4749-9787-013BF8D8F435}
- Library
- MongoDB.GridFS
- v2.0
- MongoDB.GridFS
-
-
- true
- full
- false
- bin\Debug
- DEBUG
- prompt
- 4
- false
-
-
- none
- false
- bin\Release
- prompt
- 4
- false
-
-
-
-
-
-
-
-
-
-
-
-
-
- {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}
- MongoDB.Driver
-
-
-
-
\ No newline at end of file
diff --git a/MongoDB.GridFS/Properties/AssemblyInfo.cs b/MongoDB.GridFS/Properties/AssemblyInfo.cs
deleted file mode 100644
index 7e1330f5..00000000
--- a/MongoDB.GridFS/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("MongoDB.Driver.GridFS")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("MongoDB.Driver.GridFS")]
-[assembly: AssemblyCopyright("Copyright © Microsoft 2009")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("05f4c345-88fc-4e22-87c8-4e1292da6faf")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/MongoDB.Linq.Tests/App.config b/MongoDB.Linq.Tests/App.config
deleted file mode 100644
index 1680d110..00000000
--- a/MongoDB.Linq.Tests/App.config
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/MongoDB.Linq.Tests/AppSettingsFactory.cs b/MongoDB.Linq.Tests/AppSettingsFactory.cs
deleted file mode 100644
index 932c0fe3..00000000
--- a/MongoDB.Linq.Tests/AppSettingsFactory.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using System.Configuration;
-using MongoDB.Driver;
-using MongoDB.Driver.Connections;
-
-namespace MongoDB.Linq.Tests {
- public static class AppSettingsFactory {
-
- public static string Host { get { return ConfigurationManager.AppSettings["mongo.host"]; } }
- public static int Port { get { return int.Parse(ConfigurationManager.AppSettings["mongo.port"]); } }
-
- public static Mongo CreateMongo() {
- var builder = new MongoConnectionStringBuilder();
- builder.AddServer(Host,Port);
- return new Mongo(builder.ToString());
- }
-
- public static Connection CreateConnection() {
- var builder = new MongoConnectionStringBuilder();
- builder.AddServer(Host, Port);
- return ConnectionFactory.GetConnection(builder.ToString());
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDB.Linq.Tests/MongoDB.Linq.Tests.csproj b/MongoDB.Linq.Tests/MongoDB.Linq.Tests.csproj
deleted file mode 100644
index a3f878d7..00000000
--- a/MongoDB.Linq.Tests/MongoDB.Linq.Tests.csproj
+++ /dev/null
@@ -1,85 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {870FE8E1-3461-4C79-BF25-9C35E41BF582}
- Library
- Properties
- MongoDB.Linq.Tests
- MongoDB.Linq.Tests
- v3.5
- 512
-
-
- true
- full
- false
- bin\Debug\
- DEBUG;TRACE
- prompt
- 4
-
-
- pdbonly
- true
- bin\Release\
- TRACE
- prompt
- 4
-
-
-
- False
- ..\redist\Moq.dll
-
-
- False
- ..\redist\nunit.framework.dll
-
-
-
-
- 3.5
-
-
- 3.5
-
-
- 3.5
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {2E48891E-72F9-445D-9A5A-DBA787BFFE9E}
- MongoDB.Linq
-
-
- {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}
- MongoDB.Driver
-
-
-
-
-
\ No newline at end of file
diff --git a/MongoDB.Linq.Tests/Properties/AssemblyInfo.cs b/MongoDB.Linq.Tests/Properties/AssemblyInfo.cs
deleted file mode 100644
index f4d382f8..00000000
--- a/MongoDB.Linq.Tests/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("MongoDB.Linq.Tests")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("MongoDB.Linq.Tests")]
-[assembly: AssemblyCopyright("Copyright © 2009")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("c3a2a135-887c-47db-a891-18924f9cf068")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
\ No newline at end of file
diff --git a/MongoDB.Linq.Tests/TestExpressions.cs b/MongoDB.Linq.Tests/TestExpressions.cs
deleted file mode 100644
index 2cedd7e5..00000000
--- a/MongoDB.Linq.Tests/TestExpressions.cs
+++ /dev/null
@@ -1,64 +0,0 @@
-using System;
-using System.Linq.Expressions;
-using System.Reflection;
-using NUnit.Framework;
-
-namespace MongoDB.Linq.Tests {
- // ReSharper disable InconsistentNaming
- [TestFixture]
- public class TestExpressions {
- [Test]
- public void Getting_at_member_expression_values() {
- var foo = new { Bar = "abc" };
- Expression> expression = () => foo.Bar;
- var memberExpression = expression.Body as MemberExpression;
- switch (memberExpression.Member.MemberType) {
- case MemberTypes.Property:
- var propertyInfo = (PropertyInfo)memberExpression.Member;
- var innerMember = (MemberExpression)memberExpression.Expression;
- var fieldInfo = (FieldInfo)innerMember.Member;
- var obj = fieldInfo.GetValue(((ConstantExpression)innerMember.Expression).Value);
- Assert.AreEqual("abc", propertyInfo.GetValue(obj, null));
- break;
- default:
- Assert.Fail();
- break;
- }
- }
-
- [Test]
- public void Getting_field_from_closure() {
- string key = "xyz";
- Expression> expression = () => key;
- var memberExpression = expression.Body as MemberExpression;
- switch (memberExpression.Member.MemberType) {
- case MemberTypes.Field:
- var fieldInfo = (FieldInfo)memberExpression.Member;
- Assert.AreEqual("xyz", fieldInfo.GetValue(((ConstantExpression)memberExpression.Expression).Value));
- break;
- default:
- Assert.Fail();
- break;
- }
- }
-
- [Test]
- public void Evaluating_a_MethodCallExpression_with_known_return_type() {
- Expression> expression = () => DateTime.Parse("2009/10/10");
- var methodCallExpression = expression.Body as MethodCallExpression;
- Expression> lambda = Expression.Lambda>(methodCallExpression);
- var value = lambda.Compile()();
- Assert.AreEqual(DateTime.Parse("2009/10/10"), value);
- }
-
- [Test]
- public void Evaluating_a_MethodCallExpression_with_unknown_return_type() {
- Expression> expression = () => DateTime.Parse("2009/10/10");
- var methodCallExpression = expression.Body as MethodCallExpression;
- var lambda = Expression.Lambda(methodCallExpression);
- var value = lambda.Compile().DynamicInvoke();
- Assert.AreEqual(DateTime.Parse("2009/10/10"), value);
- }
- }
- // ReSharper restore InconsistentNaming
-}
diff --git a/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs b/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs
deleted file mode 100644
index 4d953a8d..00000000
--- a/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs
+++ /dev/null
@@ -1,318 +0,0 @@
-using System;
-using System.Diagnostics;
-using System.Linq;
-using MongoDB.Driver;
-using Moq;
-using NUnit.Framework;
-
-namespace MongoDB.Linq.Tests {
- // ReSharper disable InconsistentNaming
- [TestFixture]
- public class TestMongoDocumentQuerySyntax {
-
- private IMongoQuery queryable;
- private Mock collectionMock;
- private Mock cursorMock;
-
- [SetUp]
- public void Setup() {
- Debug.WriteLine("initializing queryable");
- collectionMock = new Mock();
- cursorMock = new Mock();
- collectionMock.Setup(c => c.Find(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(cursorMock.Object);
- queryable = new MongoQuery(new MongoQueryProvider(collectionMock.Object));
- }
-
- [Test]
- public void Can_use_in_query() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo").In("bar", "baz") select d);
- Assert.AreEqual(
- new Document().Append("foo", new Document().Append("$in", new[]{ "bar", "baz" })),
- q.Query);
- }
-
- [Test]
- public void Can_use_in_query_with_array_ref() {
- var a = new[] { "bar", "baz" };
- var q = (IMongoQuery)(from d in queryable where d.Key("foo").In(a) select d);
- Assert.AreEqual(
- new Document().Append("foo", new Document().Append("$in", new[] { "bar", "baz" })),
- q.Query);
- }
-
- [Test]
- public void Can_use_not_in_query() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo").NotIn("bar", "baz") select d);
- Assert.AreEqual(
- new Document().Append("foo", new Document().Append("$nin", new[] { "bar", "baz" })),
- q.Query);
- }
-
- [Test]
- public void Can_use_Equals() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo").Equals("bar") select d);
- Assert.AreEqual(new Document().Append("foo", "bar").ToString(), q.Query.ToString());
- }
-
- #region string operator overloads
- [Test]
- public void Can_use_equality_op_on_string() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") == "bar" select d);
- Assert.AreEqual(new Document().Append("foo", "bar").ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_inequality_op_on_string() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") != "bar" select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$ne","bar")).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_equality_op_on_string_reversed() {
- var q = (IMongoQuery)(from d in queryable where "bar" == d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", "bar").ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_inequality_op_on_string_reversed() {
- var q = (IMongoQuery)(from d in queryable where "bar" != d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$ne","bar")).ToString(), q.Query.ToString());
- }
- #endregion
-
- #region int operator overloads
- [Test]
- public void Can_use_equality_op_on_int() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") == 10 select d);
- Assert.AreEqual(new Document().Append("foo", 10).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_inequality_op_on_int() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") != 10 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$ne", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_op_on_int() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") > 10 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gt", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_or_equal_op_on_int() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") >= 10 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gte", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_op_on_int() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") < 10 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lt", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_or_equal_op_on_int() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") <= 10 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lte", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_equality_op_on_int_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10 == d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", 10).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_inequality_op_on_int_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10 != d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$ne", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_op_on_int_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10 > d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lt", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_or_equal_op_on_int_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10 >= d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lte", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_op_on_int_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10 < d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gt", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_or_equal_op_on_int_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10 <= d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gte", 10)).ToString(), q.Query.ToString());
- }
- #endregion
-
- #region double operator overloads
- [Test]
- public void Can_use_equality_op_on_double() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") == 10.1 select d);
- Assert.AreEqual(new Document().Append("foo", 10.1).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_inequality_op_on_double() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") != 10.1 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$ne", 10.1)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_op_on_double() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") > 10.1 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gt", 10.1)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_or_equal_op_on_double() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") >= 10.1 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gte", 10.1)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_op_on_double() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") < 10.1 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lt", 10.1)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_or_equal_op_on_double() {
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") <= 10.1 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lte", 10.1)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_equality_op_on_double_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10.1 == d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", 10.1).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_inequality_op_on_double_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10.1 != d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$ne", 10.1)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_op_on_double_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10.1 > d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lt", 10.1)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_or_equal_op_on_double_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10.1 >= d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lte", 10.1)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_op_on_double_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10.1 < d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gt", 10.1)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_or_equal_op_on_double_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10.1 <= d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gte", 10.1)).ToString(), q.Query.ToString());
- }
- #endregion
-
- #region double operator overloads
- [Test]
- public void Can_use_equality_op_on_DateTime() {
- var dt = DateTime.Parse("2009-10-10T07:00:00.0000000Z");
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") == dt select d);
- Assert.AreEqual(new Document().Append("foo",dt).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_inequality_op_on_DateTime() {
- var dt = DateTime.Parse("2009-10-10T07:00:00.0000000Z");
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") != dt select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$ne", dt)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_op_on_DateTime() {
- var dt = DateTime.Parse("2009-10-10T07:00:00.0000000Z");
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") > dt select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gt", dt)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_or_equal_op_on_DateTime() {
- var dt = DateTime.Parse("2009-10-10T07:00:00.0000000Z");
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") >= dt select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gte", dt)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_op_on_DateTime() {
- var dt = DateTime.Parse("2009-10-10T07:00:00.0000000Z");
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") < dt select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lt", dt)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_or_equal_op_on_DateTime() {
- var dt = DateTime.Parse("2009-10-10T07:00:00.0000000Z");
- var q = (IMongoQuery)(from d in queryable where d.Key("foo") <= dt select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lte", dt)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_equality_op_on_DateTime_reversed() {
- var dt = DateTime.Parse("2009-10-10T07:00:00.0000000Z");
- var q = (IMongoQuery)(from d in queryable where dt == d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", dt).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_inequality_op_on_DateTime_reversed() {
- var dt = DateTime.Parse("2009-10-10T07:00:00.0000000Z");
- var q = (IMongoQuery)(from d in queryable where dt != d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$ne", dt)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_op_on_DateTime_reversed() {
- var dt = DateTime.Parse("2009-10-10T07:00:00.0000000Z");
- var q = (IMongoQuery)(from d in queryable where dt > d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lt", dt)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_or_equal_op_on_DateTime_reversed() {
- var dt = DateTime.Parse("2009-10-10T07:00:00.0000000Z");
- var q = (IMongoQuery)(from d in queryable where dt >= d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lte", dt)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_op_on_DateTime_reversed() {
- var dt = DateTime.Parse("2009-10-10T07:00:00.0000000Z");
- var q = (IMongoQuery)(from d in queryable where dt < d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gt", dt)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_or_equal_op_on_DateTime_reversed() {
- var dt = DateTime.Parse("2009-10-10T07:00:00.0000000Z");
- var q = (IMongoQuery)(from d in queryable where dt <= d.Key("foo") select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gte", dt)).ToString(), q.Query.ToString());
- }
- #endregion
- }
- // ReSharper restore InconsistentNaming
-}
diff --git a/MongoDB.Linq.Tests/TestQueryExecution.cs b/MongoDB.Linq.Tests/TestQueryExecution.cs
deleted file mode 100644
index e2bcf7f8..00000000
--- a/MongoDB.Linq.Tests/TestQueryExecution.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using System.Diagnostics;
-using System.Linq;
-using MongoDB.Driver;
-using NUnit.Framework;
-
-namespace MongoDB.Linq.Tests {
- // ReSharper disable InconsistentNaming
- [TestFixture]
- public class TestQueryExecution {
- private Mongo mongo;
-
- [TestFixtureSetUp]
- public void GlobalSetup() {
- Debug.WriteLine("initiallizing connection");
- mongo = AppSettingsFactory.CreateMongo();
- mongo.Connect();
- }
-
- [TestFixtureTearDown]
- public void GlobalTeardown() {
- mongo.Disconnect();
- }
-
- [Test]
- public void Can_build_simple_query() {
- var c = mongo["foo"]["bar"];
- var q = from d in c.AsQueryable() where (string)d["name"] == "bob" select d;
- var l = q.ToList();
- }
- }
- // ReSharper restore InconsistentNaming
-}
diff --git a/MongoDB.Linq.Tests/TestQueryParsing.cs b/MongoDB.Linq.Tests/TestQueryParsing.cs
deleted file mode 100644
index 13fcf74a..00000000
--- a/MongoDB.Linq.Tests/TestQueryParsing.cs
+++ /dev/null
@@ -1,225 +0,0 @@
-using System;
-using System.Diagnostics;
-using System.Linq;
-using MongoDB.Driver;
-using Moq;
-using NUnit.Framework;
-
-namespace MongoDB.Linq.Tests {
- // ReSharper disable InconsistentNaming
- [TestFixture]
- public class TestQueryParsing {
-
- private IMongoQuery queryable;
- private Mock collectionMock;
- private Mock cursorMock;
-
- [SetUp]
- public void Setup() {
- Debug.WriteLine("initializing queryable");
- collectionMock = new Mock();
- cursorMock = new Mock();
- collectionMock.Setup(c => c.Find(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(cursorMock.Object);
- queryable = new MongoQuery(new MongoQueryProvider(collectionMock.Object));
- }
-
- [Test]
- public void No_where_produces_empty_Query() {
- var q = (IMongoQuery)(from d in queryable select d);
- Assert.IsNull(q.Query);
- }
-
- [Test]
- public void Can_call_ToList_on_query() {
- (from d in queryable select d).ToList();
- collectionMock.Verify(c => c.Find(null, 0, 0, null));
- }
-
- [Test]
- public void Can_call_AsEnumerable_on_query() {
- var q = (from d in queryable select d).AsEnumerable();
- var enumerator = q.GetEnumerator();
- var first = enumerator.Current;
- collectionMock.Verify(c => c.Find(null, 0, 0, null));
- }
-
- [Test]
- public void No_skip_produces_zero_skip() {
- var q = (IMongoQuery)(from d in queryable select d);
- Assert.AreEqual(0, q.Skip);
- }
-
- [Test]
- public void Skip_5_produces_skip_5() {
- var q = (IMongoQuery)(from d in queryable select d).Skip(5);
- Assert.AreEqual(5, q.Skip);
- }
-
- [Test]
- public void No_take_produces_zero_limit() {
- var q = (IMongoQuery)(from d in queryable select d);
- Assert.AreEqual(0, q.Limit);
- }
-
- [Test]
- public void Take_5_produces_limit_5() {
- var q = (IMongoQuery)(from d in queryable select d).Take(5);
- Assert.AreEqual(5, q.Limit);
- }
-
- [Test]
- public void Can_chain_Take_and_Skip() {
- var q = (IMongoQuery)(from d in queryable select d).Take(5).Skip(10);
- Assert.AreEqual(5, q.Limit);
- Assert.AreEqual(10, q.Skip);
- }
-
- [Test]
- public void FirstOrDefault_produces_limit_1() {
- (from d in queryable select d).FirstOrDefault();
- collectionMock.Verify(c => c.Find(null, 1, 0, null));
- }
-
- [Test]
- public void First_on_empty_sequence_throws() {
- try {
- (from d in queryable select d).First();
- Assert.Fail("First didn't throw");
- } catch (InvalidOperationException e) {
- Assert.AreEqual("Sequence contains no elements", e.Message);
- }
- collectionMock.Verify(c => c.Find(null, 1, 0, null));
- }
-
- [Test]
- public void Can_use_equality_where_clause_with_equals() {
- var q = (IMongoQuery)(from d in queryable where Equals(d["foo"], "bar") select d);
- Assert.AreEqual(new Document().Append("foo","bar").ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_equality_where_clause_with_equals_method_on_Document_indexer() {
- var q = (IMongoQuery)(from d in queryable where d["foo"].Equals("bar") select d);
- Assert.AreEqual(new Document().Append("foo", "bar").ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_equality_where_clause_with_equals_method_on_value() {
- var q = (IMongoQuery)(from d in queryable where "bar".Equals(d["foo"]) select d);
- Assert.AreEqual(new Document().Append("foo", "bar").ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_equality_where_clause_with_left_cast_to_string() {
- var q = (IMongoQuery)(from d in queryable where (string)d["foo"] == "bar" select d);
- Assert.AreEqual(new Document().Append("foo", "bar").ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_equality_where_clause_with_right_cast_to_object() {
- var q = (IMongoQuery)(from d in queryable where (string)d["foo"] == "bar" select d);
- Assert.AreEqual(new Document().Append("foo", "bar").ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_equality_where_clause_with_left_and_right_reversed() {
- var q = (IMongoQuery)(from d in queryable where "bar" == (string)d["foo"] select d);
- Assert.AreEqual(new Document().Append("foo", "bar").ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_equality_where_clause_with_key_as_variable() {
- string key = "foo";
- var q = (IMongoQuery)(from d in queryable where (string)d[key] == "bar" select d);
- Assert.AreEqual(new Document().Append("foo", "bar").ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_equality_where_clause_with_value_as_variable() {
- string value = "bar";
- var q = (IMongoQuery)(from d in queryable where (string)d["foo"] == value select d);
- Assert.AreEqual(new Document().Append("foo","bar").ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_inequality() {
- var q = (IMongoQuery)(from d in queryable where (string)d["foo"] != "bar" select d);
- Assert.AreEqual(new Document().Append("foo",new Document().Append("$ne","bar")).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_inequality_reversed() {
- var q = (IMongoQuery)(from d in queryable where "bar" != (string)d["foo"] select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$ne", "bar")).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than() {
- var q = (IMongoQuery)(from d in queryable where (int)d["foo"] > 10 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gt", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_reversed() {
- var q = (IMongoQuery)(from d in queryable where 10 > (int)d["foo"] select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lt", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_greater_than_or_equal() {
- var q = (IMongoQuery)(from d in queryable where (int)d["foo"] >= 10 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$gte", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than() {
- var q = (IMongoQuery)(from d in queryable where (int)d["foo"] < 10 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lt", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_use_less_than_or_equal() {
- var q = (IMongoQuery)(from d in queryable where (int)d["foo"] <= 10 select d);
- Assert.AreEqual(new Document().Append("foo", new Document().Append("$lte", 10)).ToString(), q.Query.ToString());
- }
-
- [Test]
- public void Can_do_and_queries() {
- var q = (IMongoQuery)(from d in queryable where (int)d["foo"] <= 10 && (string)d["bar"] == "zoop" select d);
- Assert.AreEqual(
- new Document()
- .Append("foo", new Document().Append("$lte", 10))
- .Append("bar","zoop"),
- q.Query);
- }
-
- [Test]
- public void Can_do_and_queries_on_same_key(){
- var q = (IMongoQuery)(from d in queryable where (int)d["foo"] < 10 && (int)d["foo"] > 5 select d);
- Assert.AreEqual(
- new Document().Append("foo", new Document().Append("$lt", 10).Append("$gt",5)),
- q.Query);
- }
-
- [Test]
- public void Can_compose_queries() {
- // Note (sdether): this passes without explicit AND support, which is a bit scary
- var q1 = from d in queryable where (int)d["foo"] <= 10 select d;
- var q2 = (IMongoQuery)(from d in q1 where (string)d["bar"] == "zoop" select d);
- Assert.AreEqual(
- new Document()
- .Append("foo", new Document().Append("$lte", 10))
- .Append("bar", "zoop"),
- q2.Query);
- }
-
- [Test]
- public void Can_use_dot_notation_for_queries() {
- // Note (sdether): dot.notation in document is a bit of a perversion, since it's not legal
- // in a document to be saved. So this syntax may break, if Document becomes more strict
- var q = (IMongoQuery)(from d in queryable where (int)d["foo.bar"] == 10 select d);
- Assert.AreEqual(new Document().Append("foo.bar",10).ToString(), q.Query.ToString());
- }
- }
- // ReSharper restore InconsistentNaming
-}
diff --git a/MongoDB.Linq.Tests/test-results/MongoDB.Linq.Tests.csproj-Debug-2009-10-12.xml b/MongoDB.Linq.Tests/test-results/MongoDB.Linq.Tests.csproj-Debug-2009-10-12.xml
deleted file mode 100644
index b17da309..00000000
--- a/MongoDB.Linq.Tests/test-results/MongoDB.Linq.Tests.csproj-Debug-2009-10-12.xml
+++ /dev/null
@@ -1,2301 +0,0 @@
-
-
-
-
- 2009-10-12T22:40:45
- Success Failure
- 75
- 2
- 0
-
- Child test failed
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Success Failure
- 75
- 2
- 0
-
- Child test failed
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Success Failure
- 75
- 2
- 0
-
- Child test failed
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Success Failure
- 75
- 2
- 0
-
- Child test failed
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Success Failure
- 2
- 2
- 0
-
- Child test failed
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Success
- 0
- 1
- 0
-
- Test successful
-
-Execution time: 0.11ms
-
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Success
- 0
- 1
- 0
-
- Test successful
-
-Execution time: 0.01ms
-
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.InvalidCastException : Cannot cast from source type to destination type.
- at MongoDB.Linq.Tests.TestExpressions.Getting_at_member_expression_values () [0x0007c] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestExpressions.cs:18
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
-
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.NullReferenceException : Object reference not set to an instance of an object
- at MongoDB.Linq.Tests.TestExpressions.Getting_field_from_closure () [0x00034] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestExpressions.cs:34
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
-
-
-
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 44
- 0
- 0
-
- Child test failed
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.ArgumentNullException : Argument cannot be null.
-Parameter name: s
- at System.Int32.Parse (System.String s) [0x00000]
- at MongoDB.Linq.Tests.AppSettingsFactory.get_Port () [0x00000] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/AppSettingsFactory.cs:11
- at MongoDB.Linq.Tests.AppSettingsFactory.CreateMongo () [0x00000] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/AppSettingsFactory.cs:14
- at MongoDB.Linq.Tests.TestQueryExecution.GlobalSetup () [0x0000a] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestQueryExecution.cs:15
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- TestFixtureSetUp failed in TestQueryExecution
-
-
-
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 28
- 0
- 0
-
- Child test failed
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
- 2009-10-12T22:40:45
- Failure
- 1
- 0
- 0
-
- System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Mock`1
- ----> System.TypeInitializationException : An exception was thrown by the type initializer for Moq.Proxy.CastleProxyFactory
- ----> System.TypeLoadException : A type load exception has occurred.
- at MongoDB.Linq.Tests.TestMongoDocumentQuerySyntax.Setup () [0x0001f] in /home/samus/Documents/Projects/mongodb-csharp/MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs:20
- at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000]
---TypeInitializationException
- at Moq.Mock`1[MongoDB.Driver.IMongoCollection]..cctor () [0x00000]
---TypeLoadException
- at Castle.DynamicProxy.ModuleScope..ctor (Boolean savePhysicalAssembly) [0x00000]
- at Castle.DynamicProxy.ModuleScope..ctor () [0x00000]
- at Castle.DynamicProxy.DefaultProxyBuilder..ctor () [0x00000]
- at Castle.DynamicProxy.ProxyGenerator..ctor () [0x00000]
- at Moq.Proxy.CastleProxyFactory..cctor () [0x00000]
-
- initializing queryable
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/MongoDB.Linq/IMongoQuery.cs b/MongoDB.Linq/IMongoQuery.cs
deleted file mode 100644
index 3d2b5387..00000000
--- a/MongoDB.Linq/IMongoQuery.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System.Linq;
-using MongoDB.Driver;
-
-namespace MongoDB.Linq {
- public interface IMongoQuery : IQueryable {
- Document Query { get; }
- int Limit { get; }
- int Skip { get; }
- Document Fields { get; }
- }
-}
diff --git a/MongoDB.Linq/IMongoQueryProvider.cs b/MongoDB.Linq/IMongoQueryProvider.cs
deleted file mode 100644
index 2ee68dc9..00000000
--- a/MongoDB.Linq/IMongoQueryProvider.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-using System.Linq;
-using System.Linq.Expressions;
-
-namespace MongoDB.Linq {
- public interface IMongoQueryProvider : IQueryProvider {
- MongoQuerySpec GetQuerySpec(Expression expression);
- }
-
-}
diff --git a/MongoDB.Linq/MongoDB.Linq.csproj b/MongoDB.Linq/MongoDB.Linq.csproj
deleted file mode 100644
index 024a200a..00000000
--- a/MongoDB.Linq/MongoDB.Linq.csproj
+++ /dev/null
@@ -1,72 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {2E48891E-72F9-445D-9A5A-DBA787BFFE9E}
- Library
- Properties
- MongoDB.Linq
- MongoDB.Linq
- v3.5
- 512
-
-
- true
- full
- false
- bin\Debug\
- DEBUG;TRACE
- prompt
- 4
-
-
- pdbonly
- true
- bin\Release\
- TRACE
- prompt
- 4
-
-
-
-
- 3.5
-
-
- 3.5
-
-
- 3.5
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}
- MongoDB.Driver
-
-
-
-
-
\ No newline at end of file
diff --git a/MongoDB.Linq/MongoDocumentQuery.cs b/MongoDB.Linq/MongoDocumentQuery.cs
deleted file mode 100644
index e50d14ee..00000000
--- a/MongoDB.Linq/MongoDocumentQuery.cs
+++ /dev/null
@@ -1,96 +0,0 @@
-using System;
-using MongoDB.Driver;
-
-namespace MongoDB.Linq {
-
- ///
- /// This class is a construct for writing strongly typed query expressions for Document fields.
- /// It is not meant to be used outside of expressions, since most functions and operators return
- /// fake data and are only used to extract parameter information from expressions.
- ///
- public class MongoDocumentQuery {
- private readonly string key;
-
- public MongoDocumentQuery(Document document, string key) {
- this.key = key;
- }
-
- public string Key { get { return key; } }
-
- public bool In(params T[] values) {
- return false;
- }
- public bool NotIn(params T[] values) {
- return false;
- }
-
- public static bool operator ==(MongoDocumentQuery a, string b) { return false; }
- public static bool operator !=(MongoDocumentQuery a, string b) { return false; }
- public static bool operator ==(string a, MongoDocumentQuery b) { return false; }
- public static bool operator !=(string a, MongoDocumentQuery b) { return false; }
-
- public static bool operator >(MongoDocumentQuery a, int b) { return false; }
- public static bool operator >=(MongoDocumentQuery a, int b) { return false; }
- public static bool operator <(MongoDocumentQuery a, int b) { return false; }
- public static bool operator <=(MongoDocumentQuery a, int b) { return false; }
- public static bool operator ==(MongoDocumentQuery a, int b) { return false; }
- public static bool operator !=(MongoDocumentQuery a, int b) { return false; }
- public static bool operator >(int a, MongoDocumentQuery b) { return false; }
- public static bool operator >=(int a, MongoDocumentQuery b) { return false; }
- public static bool operator <(int a, MongoDocumentQuery b) { return false; }
- public static bool operator <=(int a, MongoDocumentQuery b) { return false; }
- public static bool operator ==(int a, MongoDocumentQuery b) { return false; }
- public static bool operator !=(int a, MongoDocumentQuery b) { return false; }
-
- public static bool operator >(MongoDocumentQuery a, double b) { return false; }
- public static bool operator >=(MongoDocumentQuery a, double b) { return false; }
- public static bool operator <(MongoDocumentQuery a, double b) { return false; }
- public static bool operator <=(MongoDocumentQuery a, double b) { return false; }
- public static bool operator ==(MongoDocumentQuery a, double b) { return false; }
- public static bool operator !=(MongoDocumentQuery a, double b) { return false; }
- public static bool operator >(double a, MongoDocumentQuery b) { return false; }
- public static bool operator >=(double a, MongoDocumentQuery b) { return false; }
- public static bool operator <(double a, MongoDocumentQuery b) { return false; }
- public static bool operator <=(double a, MongoDocumentQuery b) { return false; }
- public static bool operator ==(double a, MongoDocumentQuery b) { return false; }
- public static bool operator !=(double a, MongoDocumentQuery b) { return false; }
-
- public static bool operator >(MongoDocumentQuery a, DateTime b) { return false; }
- public static bool operator >=(MongoDocumentQuery a, DateTime b) { return false; }
- public static bool operator <(MongoDocumentQuery a, DateTime b) { return false; }
- public static bool operator <=(MongoDocumentQuery a, DateTime b) { return false; }
- public static bool operator ==(MongoDocumentQuery a, DateTime b) { return false; }
- public static bool operator !=(MongoDocumentQuery a, DateTime b) { return false; }
- public static bool operator >(DateTime a, MongoDocumentQuery b) { return false; }
- public static bool operator >=(DateTime a, MongoDocumentQuery b) { return false; }
- public static bool operator <(DateTime a, MongoDocumentQuery b) { return false; }
- public static bool operator <=(DateTime a, MongoDocumentQuery b) { return false; }
- public static bool operator ==(DateTime a, MongoDocumentQuery b) { return false; }
- public static bool operator !=(DateTime a, MongoDocumentQuery b) { return false; }
-
- public bool Equals(MongoDocumentQuery other)
- {
- if(ReferenceEquals(null, other))
- return false;
- if(ReferenceEquals(this, other))
- return true;
- return Equals(other.key, key);
- }
-
- public override bool Equals(object obj)
- {
- if(ReferenceEquals(null, obj))
- return false;
- if(ReferenceEquals(this, obj))
- return true;
- if(obj.GetType() != typeof(MongoDocumentQuery))
- return false;
- return Equals((MongoDocumentQuery)obj);
- }
-
- public override int GetHashCode()
- {
- return (key != null ? key.GetHashCode() : 0);
- }
- }
-}
diff --git a/MongoDB.Linq/MongoLinqEx.cs b/MongoDB.Linq/MongoLinqEx.cs
deleted file mode 100644
index c98b2e67..00000000
--- a/MongoDB.Linq/MongoLinqEx.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using System;
-using MongoDB.Driver;
-
-namespace MongoDB.Linq
-{
- public static class MongoLinqEx
- {
- public static IMongoQuery AsQueryable(this T collection) where T : IMongoCollection
- {
- return new MongoQuery(new MongoQueryProvider(collection));
- }
-
- public static MongoDocumentQuery Key(this T document,string key) where T: Document{
- return new MongoDocumentQuery(document,key);
- }
- }
-}
diff --git a/MongoDB.Linq/MongoQuery.cs b/MongoDB.Linq/MongoQuery.cs
deleted file mode 100644
index 67095db1..00000000
--- a/MongoDB.Linq/MongoQuery.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Linq;
-using System.Linq.Expressions;
-using MongoDB.Driver;
-
-namespace MongoDB.Linq
-{
- public class MongoQuery : IMongoQuery
- {
- private readonly IMongoQueryProvider queryProvider;
- private readonly Expression expression;
- private MongoQuerySpec querySpec;
-
- public MongoQuery(IMongoQueryProvider queryProvider)
- {
- this.queryProvider = queryProvider;
- expression = Expression.Constant(this);
- }
-
- public MongoQuery(IMongoQueryProvider queryProvider, Expression expression)
- {
- this.queryProvider = queryProvider;
- this.expression = expression;
- }
-
- public IEnumerator GetEnumerator()
- {
- return ((IEnumerable)queryProvider.Execute(expression)).GetEnumerator();
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return ((IEnumerable)queryProvider.Execute(expression)).GetEnumerator();
- }
-
- public Expression Expression
- {
- get { return expression; }
- }
-
- public Type ElementType
- {
- get { return typeof(Document); }
- }
-
- public IQueryProvider Provider
- {
- get { return queryProvider; }
- }
-
- private MongoQuerySpec QuerySpec
- {
- get
- {
- if (querySpec == null)
- {
- querySpec = queryProvider.GetQuerySpec(expression);
- }
- return querySpec;
- }
- }
- public Document Query { get { return QuerySpec.Query; } }
- public int Limit { get { return QuerySpec.Limit; } }
- public int Skip { get { return QuerySpec.Skip; } }
- public Document Fields { get { return QuerySpec.Fields; } }
- }
-}
diff --git a/MongoDB.Linq/MongoQueryProvider.cs b/MongoDB.Linq/MongoQueryProvider.cs
deleted file mode 100644
index a22ee016..00000000
--- a/MongoDB.Linq/MongoQueryProvider.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Text;
-using MongoDB.Driver;
-
-namespace MongoDB.Linq {
- public class MongoQueryProvider : IMongoQueryProvider {
-
- private struct Result {
- public IEnumerable Documents;
- public bool IsFirstCall;
- }
-
- private readonly IMongoCollection collection;
-
- public MongoQueryProvider(IMongoCollection collection) {
- this.collection = collection;
- }
-
- public IQueryable CreateQuery(Expression expression) {
- return new MongoQuery(this, expression);
- }
-
- public IQueryable CreateQuery(Expression expression) {
- return (IQueryable)new MongoQuery(this, expression);
- }
-
- public object Execute(Expression expression) {
- return ExecuteInternal(expression).Documents;
- }
-
- private Result ExecuteInternal(Expression expression) {
- var spec = new MongoQueryTranslator().Translate(expression);
- var cur = collection.Find(spec.Query, spec.Limit, spec.Skip, spec.Fields);
- return new Result {
- Documents = cur.Documents,
- IsFirstCall = spec.IsFirstCall
- };
- }
-
- public TResult Execute(Expression expression) {
- var result = ExecuteInternal(expression);
- if (typeof(TResult).IsAssignableFrom(typeof(Document))) {
- return (TResult)(object)((result.IsFirstCall) ? result.Documents.First() : result.Documents.FirstOrDefault());
- }
- return (TResult)result.Documents;
- }
-
- public MongoQuerySpec GetQuerySpec(Expression expression) {
- return new MongoQueryTranslator().Translate(expression);
- }
- }
-}
diff --git a/MongoDB.Linq/MongoQueryTranslator.cs b/MongoDB.Linq/MongoQueryTranslator.cs
deleted file mode 100644
index f6765005..00000000
--- a/MongoDB.Linq/MongoQueryTranslator.cs
+++ /dev/null
@@ -1,309 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using System.Reflection;
-using System.Linq.Expressions;
-using MongoDB.Driver;
-
-namespace MongoDB.Linq {
- public class MongoQuerySpec {
- public readonly Document Query;
- public readonly int Limit;
- public readonly int Skip;
- public readonly Document Fields;
- public readonly Document SortOrder;
- public readonly bool IsFirstCall;
-
- public MongoQuerySpec(Document query, int limit, int skip, Document fields, Document sortOrder, bool isFirstCall) {
- Query = query;
- Limit = limit;
- Skip = skip;
- Fields = fields;
- SortOrder = sortOrder;
- IsFirstCall = isFirstCall;
- }
- }
-
- public class MongoQueryTranslator : ExpressionVisitor {
-
- private Document query;
- private int limit;
- private int skip;
- private Document fields;
- private Document sortOrder;
- private bool isFirstCall = false;
- private bool inConditional = false;
- private bool foundKey = false;
- private readonly Stack valueStack = new Stack();
- private readonly Stack keyStack = new Stack();
-
- protected Document Query {
- get {
- if (query == null) {
- query = new Document();
- }
- return query;
- }
- }
-
- protected Document Fields {
- get {
- if (fields == null) {
- fields = new Document();
- }
- return fields;
- }
- }
-
- protected Document SortOrder {
- get {
- if (sortOrder == null) {
- sortOrder = new Document();
- }
- return sortOrder;
- }
- }
-
- public MongoQuerySpec Translate(Expression expression) {
- Visit(expression);
- return new MongoQuerySpec(query, limit, skip, fields, sortOrder, isFirstCall);
- }
-
- private static Expression StripQuotes(Expression e) {
- while (e.NodeType == ExpressionType.Quote) {
- e = ((UnaryExpression)e).Operand;
- }
- return e;
- }
-
- protected override Expression VisitMethodCall(MethodCallExpression m) {
- Debug.WriteLine(string.Format("Method call: {0}", m.Method.Name));
- if (m.Method.DeclaringType == typeof(Queryable)) {
- switch (m.Method.Name) {
- case "Where":
- Visit(m.Arguments[0]);
- var lambda = (LambdaExpression)StripQuotes(m.Arguments[1]);
- Visit(lambda.Body);
- break;
- case "Skip":
- Visit(m.Arguments[0]);
- Visit(m.Arguments[1]);
- skip = (int)valueStack.Pop();
- break;
- case "Take":
- Visit(m.Arguments[0]);
- Visit(m.Arguments[1]);
- limit = (int)valueStack.Pop();
- break;
- case "First":
- isFirstCall = true;
- limit = 1;
- Visit(m.Arguments[0]);
- break;
- case "FirstOrDefault":
- limit = 1;
- Visit(m.Arguments[0]);
- break;
- case "Select":
- break;
- default:
- throw new NotSupportedException(string.Format("The method '{0}' on queryable type is not supported", m.Method.Name));
- }
-
- return m;
- }
- if (m.Object == null && m.Method.Name == "Key") {
- Visit(m.Arguments[1]);
- keyStack.Push((string)valueStack.Pop());
- foundKey = true;
- return m;
- }
- if (m.Object != null && typeof(MongoDocumentQuery).IsAssignableFrom(m.Object.Type)) {
- Debug.WriteLine("call on MongoDocumentQuery");
- Visit(((MethodCallExpression)m.Object).Arguments[1]);
- keyStack.Push((string)valueStack.Pop());
- foundKey = true;
- switch (m.Method.Name) {
- case "In":
- case "NotIn":
- var argsLambda = Expression.Lambda(m.Arguments[0]);
- var argsValue = argsLambda.Compile().DynamicInvoke();
- Query.Add(keyStack.Pop(), new Document().Append((m.Method.Name == "In") ? "$in" : "$nin", argsValue));
- break;
- case "Equals":
- Visit(m.Arguments[0]);
- AddEqualityQuery();
- break;
- }
- return m;
- }
- if (m.Method.Name == "Equals") {
- if (m.Object == null) {
- Visit(m.Arguments[0]);
- Visit(m.Arguments[1]);
- } else {
- Visit(m.Object);
- Visit(m.Arguments[0]);
- }
- AddEqualityQuery();
- return m;
- }
- if (m.Object != null && typeof(Document).IsAssignableFrom(m.Object.Type) && m.Method.Name == "get_Item") {
- Debug.WriteLine("Document indexer access, divining query key");
- Visit(m.Arguments[0]);
- keyStack.Push((string)valueStack.Pop());
- foundKey = true;
- return m;
- }
-
- Debug.WriteLine("unrecognized method call, trying to convert to constant value");
- try {
- var methodCallLambda = Expression.Lambda(m);
- var methodConstValue = methodCallLambda.Compile().DynamicInvoke();
- valueStack.Push(methodConstValue);
- } catch (Exception e) {
- throw new NotSupportedException(string.Format("The method '{0}' could not be converted into a constant", m.Method.Name), e);
- }
- return m;
- }
-
- private void AddEqualityQuery() {
- var key = keyStack.Pop();
- var value = valueStack.Pop();
- Query.Append(key, value);
- }
-
- protected override Expression VisitUnary(UnaryExpression u) {
- Debug.WriteLine(string.Format("Unary type: {0}", u.NodeType));
- switch (u.NodeType) {
- case ExpressionType.Not:
- break;
- case ExpressionType.Convert:
- Visit(StripConvert(u));
- break;
- default:
- throw new NotSupportedException(string.Format("The unary operator '{0}' is not supported", u.NodeType));
- } return u;
- }
-
- private Expression StripConvert(Expression expression) {
- while (expression.NodeType == ExpressionType.Convert) {
- expression = ((UnaryExpression)expression).Operand;
- }
- return expression;
- }
-
- protected override Expression VisitBinary(BinaryExpression b) {
- Debug.WriteLine(string.Format("Binary type: {0}", b.NodeType));
- string key;
- object value;
- switch (b.NodeType) {
- case ExpressionType.Equal:
- Visit(b.Left);
- Visit(b.Right);
- AddEqualityQuery();
- break;
- case ExpressionType.NotEqual:
- case ExpressionType.LessThan:
- case ExpressionType.LessThanOrEqual:
- case ExpressionType.GreaterThan:
- case ExpressionType.GreaterThanOrEqual:
- if (inConditional) {
- throw new NotSupportedException("cannot handle nested conditionals");
- }
- // Note (sdether): because of conditional ordering, left and right visits have to happen inside the
- // inConditional = true block, which is why the visits cannot be moved to the top of the switch
- inConditional = true;
- Visit(b.Left);
- bool reverseConditional = false;
- if (!foundKey) {
- reverseConditional = true;
- }
- Visit(b.Right);
- key = keyStack.Pop();
- value = valueStack.Pop();
- var conditional = "$ne";
- switch (b.NodeType) {
- case ExpressionType.LessThan: conditional = reverseConditional ? "$gt" : "$lt"; break;
- case ExpressionType.LessThanOrEqual: conditional = reverseConditional ? "$gte" : "$lte"; break;
- case ExpressionType.GreaterThan: conditional = reverseConditional ? "$lt" : "$gt"; break;
- case ExpressionType.GreaterThanOrEqual: conditional = reverseConditional ? "$lte" : "$gte"; break;
- }
- if(Query.Contains(key)){
- ((Document)Query[key]).Append(conditional,value);
- }else{
- Query.Append(key, new Document().Append(conditional, value));
- }
- inConditional = false;
- foundKey = false;
- break;
- case ExpressionType.AndAlso:
- Visit(b.Left);
- Visit(b.Right);
- break;
- default:
- throw new NotSupportedException(string.Format("The binary operator '{0}' is not supported", b.NodeType));
- }
-
- return b;
- }
-
- protected override Expression VisitConstant(ConstantExpression c) {
- Debug.WriteLine(string.Format("constant: ({0}){1}", c.Type, c.Value));
- if (c.Value is MongoQuery) {
- Debug.WriteLine("constant of type MongoQuery is our terminal, ignore");
- } else {
- switch (Type.GetTypeCode(c.Value.GetType())) {
- case TypeCode.Boolean:
- case TypeCode.DateTime:
- case TypeCode.Decimal:
- case TypeCode.Double:
- case TypeCode.Int16:
- case TypeCode.Int32:
- case TypeCode.Int64:
- case TypeCode.Single:
- case TypeCode.String:
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- valueStack.Push(c.Value);
- break;
- default:
- throw new NotSupportedException(string.Format("The constant for '{0}' is not supported", c.Value));
- }
- }
- return c;
- }
-
- protected override Expression VisitMemberAccess(MemberExpression m) {
- Debug.WriteLine(string.Format("Member Access: {0}", m.Member.Name));
- if (m.Expression != null) {
- if (m.Expression.NodeType == ExpressionType.Parameter) {
- return m;
- }
- if (m.Expression != null && m.Expression.NodeType == ExpressionType.Constant) {
- switch (m.Member.MemberType) {
- case MemberTypes.Property:
- var propertyInfo = (PropertyInfo)m.Member;
- var innerMember = (MemberExpression)m.Expression;
- var closureFieldInfo = (FieldInfo)innerMember.Member;
- var obj = closureFieldInfo.GetValue(((ConstantExpression)innerMember.Expression).Value);
- valueStack.Push(propertyInfo.GetValue(obj, null));
- break;
- case MemberTypes.Field:
- var fieldInfo = (FieldInfo)m.Member;
- valueStack.Push(fieldInfo.GetValue(((ConstantExpression)m.Expression).Value));
- break;
- default:
- Visit(m.Expression);
- break;
- }
- return m;
- }
- }
- throw new NotSupportedException(string.Format("The member '{0}' is not supported", m.Member.Name));
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDB.Linq/Properties/AssemblyInfo.cs b/MongoDB.Linq/Properties/AssemblyInfo.cs
deleted file mode 100644
index 836f0c87..00000000
--- a/MongoDB.Linq/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("MongoDB.Linq")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("MongoDB.Linq")]
-[assembly: AssemblyCopyright("Copyright © 2009")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("443b51f7-36c7-434b-9d50-2a22a2d9be44")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/MongoDB.Net-Tests/.gitignore b/MongoDB.Net-Tests/.gitignore
deleted file mode 100644
index d09da2cd..00000000
--- a/MongoDB.Net-Tests/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-*.dll
-*.pdb
-*.xml
-obj/*
-PartCover/*
diff --git a/MongoDB.Net-Tests/Bson/TestBsonBinary.cs b/MongoDB.Net-Tests/Bson/TestBsonBinary.cs
deleted file mode 100755
index 99db4af2..00000000
--- a/MongoDB.Net-Tests/Bson/TestBsonBinary.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-using System;
-using System.IO;
-using NUnit.Framework;
-
-using MongoDB.Driver;
-
-namespace MongoDB.Driver.Bson
-{
- [TestFixture]
- public class TestBsonBinary
- {
- [Test]
- public void TestRoundTrip ()
- {
- Document idoc = new Document ();
- idoc.Add ("b", new Binary (new byte[] { (byte)1, (byte)2 }));
-
- MemoryStream stream = new MemoryStream ();
- BsonWriter writer = new BsonWriter (stream);
- writer.Write (idoc);
-
- stream.Seek (0, SeekOrigin.Begin);
- BsonReader reader = new BsonReader (stream);
- Document odoc = reader.Read ();
-
- Assert.AreEqual (idoc.ToString (), odoc.ToString ());
- }
-
- [Test]
- public void TestBinaryRead ()
- {
- string hex = "28000000075f6964004b1971811d8b0f00c0000000056461746100070000000203000000e188b400";
-
- byte[] data = DecodeHex (hex);
- MemoryStream inmem = new MemoryStream (data);
- BsonReader inreader = new BsonReader (inmem);
- Document indoc = new Document ();
- indoc = inreader.Read ();
-
- MemoryStream outmem = new MemoryStream ();
- BsonWriter outwriter = new BsonWriter (outmem);
- outwriter.Write (indoc);
- byte[] outdata = outmem.ToArray ();
- String outhex = BitConverter.ToString (outdata);
- outhex = outhex.Replace ("-", "");
-
- Assert.AreEqual (hex, outhex.ToLower ());
-
- }
-
- protected static byte[] DecodeHex (string val)
- {
- int numberChars = val.Length;
-
- byte[] bytes = new byte[numberChars / 2];
- for (int i = 0; i < numberChars; i += 2) {
- try {
- bytes[i / 2] = Convert.ToByte (val.Substring (i, 2), 16);
- } catch {
- //failed to convert these 2 chars, they may contain illegal charracters
- bytes[i / 2] = 0;
- }
- }
- return bytes;
- }
-
- }
-}
diff --git a/MongoDB.Net-Tests/Bson/TestBsonReader.cs b/MongoDB.Net-Tests/Bson/TestBsonReader.cs
deleted file mode 100644
index 8f711be8..00000000
--- a/MongoDB.Net-Tests/Bson/TestBsonReader.cs
+++ /dev/null
@@ -1,287 +0,0 @@
-using System;
-using System.IO;
-using System.Text;
-
-using NUnit.Framework;
-
-namespace MongoDB.Driver.Bson
-{
- [TestFixture]
- public class TestBsonReader
- {
- char pound = '\u00a3';
- char euro = '\u20ac';
-
- [Test]
- public void TestReadString(){
- byte[] buf = HexToBytes("7465737400");
- MemoryStream ms = new MemoryStream(buf);
- BsonReader reader = new BsonReader(ms);
-
- String s = reader.ReadString();
- Assert.AreEqual("test",s);
- Assert.AreEqual(4,Encoding.UTF8.GetByteCount(s));
- }
-
- [Test]
- public void TestReadStringLong(){
- StringBuilder sb = new StringBuilder();
- sb.Append('t',256);
- string expected = sb.ToString();
- Assert.AreEqual(expected, WriteAndReadString(expected));
- }
-
- [Test]
- public void TestReadStringWithUKPound(){
- string expected = "1234£56";
- Assert.AreEqual(expected, WriteAndReadString(expected));
- }
-
- [Test]
- public void TestReadStringBreakDblByteCharOverBuffer(){
- StringBuilder sb = new StringBuilder();
- sb.Append('1',127);
- sb.Append(pound); //will break the pound symbol over the buffer boundry.
- //sb.Append("1");
-
- string expected = sb.ToString();
- Assert.AreEqual(expected, WriteAndReadString(expected));
- }
-
- [Test]
- public void TestReadStringDblByteCharOnEndOfBufferBoundry(){
- StringBuilder sb = new StringBuilder();
- sb.Append(pound, 66); //puts a pound symbol at the end of the buffer boundry but not broken.
-
- string expected = sb.ToString();
- Assert.AreEqual(expected, WriteAndReadString(expected));
- }
-
- [Test]
- public void TestReadStringTripleByteCharBufferBoundry(){
- StringBuilder sb = new StringBuilder();
- sb.Append("12");
- sb.Append(euro, 66); //will break the euro symbol over the buffer boundry.
-
- string expected = sb.ToString();
-
- Assert.AreEqual(expected, WriteAndReadString(expected));
- }
-
- private string WriteAndReadString(string val){
- byte[] buf = Encoding.UTF8.GetBytes(val + '\0');
-
- MemoryStream ms = new MemoryStream(buf);
- BsonReader reader = new BsonReader(ms);
- return reader.ReadString();
- }
-
- [Test]
- public void TestReadLenStringValue(){
- string expected = "test";
-
- Assert.AreEqual(expected, WriteAndReadLenString(expected));
- }
-
- [Test]
- public void TestReadLenStringShortTripleByte(){
- StringBuilder sb = new StringBuilder();
- //sb.Append('1',127); //first char of euro at the end of the boundry.
- //sb.Append(euro, 5);
- //sb.Append('1',128);
- sb.Append(euro);
-
- string expected = sb.ToString();
- Assert.AreEqual(expected, WriteAndReadLenString(expected));
- }
-
- [Test]
- public void TestReadLenStringTripleByteCharBufferBoundry0(){
- StringBuilder sb = new StringBuilder();
- sb.Append('1',127); //first char of euro at the end of the boundry.
- sb.Append(euro, 5);
- sb.Append('1',128);
- sb.Append(euro);
-
- string expected = sb.ToString();
- Assert.AreEqual(expected, WriteAndReadLenString(expected));
- }
-
- [Test]
- public void TestReadLenStringTripleByteCharBufferBoundry1(){
- StringBuilder sb = new StringBuilder();
- sb.Append('1',126);
- sb.Append(euro, 5); //middle char of euro at the end of the boundry.
- sb.Append('1',128);
- sb.Append(euro);
-
- string expected = sb.ToString();
- Assert.AreEqual(expected, WriteAndReadLenString(expected));
- }
-
- [Test]
- public void TestReadLenStringTripleByteCharOne(){
- StringBuilder sb = new StringBuilder();
- sb.Append(euro, 1); //Just one triple byte char in the string.
-
- string expected = sb.ToString();
- Assert.AreEqual(expected, WriteAndReadLenString(expected));
- }
-
- [Test]
- public void TestReadLenStringTripleByteCharBufferBoundry2(){
- StringBuilder sb = new StringBuilder();
- sb.Append('1', 125);
- sb.Append(euro, 5); //last char of the eruo at the end of the boundry.
- sb.Append('1',128);
- sb.Append(euro);
-
- string expected = sb.ToString();
- Assert.AreEqual(expected, WriteAndReadLenString(expected));
- }
-
- [Test]
- public void TestReadLenString(){
- string expected = "test";
- Assert.AreEqual(expected, WriteAndReadLenString(expected));
- }
-
- [Test]
- public void TestReadLenStringLong(){
- StringBuilder sb = new StringBuilder();
- sb.Append('t',150);
- string expected = sb.ToString();
- Assert.AreEqual(expected, WriteAndReadLenString(expected));
- }
-
- private string WriteAndReadLenString(string val){
- MemoryStream ms = new MemoryStream();
- BsonWriter bs = new BsonWriter(ms);
- BinaryWriter w = new BinaryWriter(ms);
- int byteCount = bs.CalculateSize(val,false);
- w.Write(byteCount);
- bs.WriteString(val);
- ms.Seek(0,SeekOrigin.Begin);
- BsonReader reader = new BsonReader(ms);
- return reader.ReadLenString();
- }
-
-
- [Test]
- public void TestReadEmptyDocument(){
- byte[] buf = HexToBytes("0500000000");
- MemoryStream ms = new MemoryStream(buf);
- BsonReader reader = new BsonReader(ms);
-
- Document doc = reader.ReadDocument();
-
- Assert.IsNotNull(doc);
- }
-
- [Test]
- public void TestReadSimpleDocument(){
- byte[] buf = HexToBytes("1400000002746573740005000000746573740000");
- MemoryStream ms = new MemoryStream(buf);
- BsonReader reader = new BsonReader(ms);
-
- Document doc = reader.Read();
-
- Assert.IsNotNull(doc, "Document was null");
- Assert.IsTrue(doc.Contains("test"));
- Assert.AreEqual("test", (String)doc["test"]);
- }
-
- [Test]
- public void TestReadMultiElementDocument(){
- byte[] buf = HexToBytes("2D000000075F6964004A753AD8FAC16EA58B290351016100000000000000F03F02620005000000746573740000");
- MemoryStream ms = new MemoryStream(buf);
- BsonReader reader = new BsonReader(ms);
-
- Document doc = reader.ReadDocument();
-
- Assert.IsNotNull(doc, "Document was null");
- Assert.IsTrue(doc.Contains("_id"));
- Assert.IsTrue(doc.Contains("a"));
- Assert.IsTrue(doc.Contains("b"));
- Assert.AreEqual("\"4a753ad8fac16ea58b290351\"", ((Oid)doc["_id"]).ToString());
- Assert.AreEqual(1, Convert.ToInt32(doc["a"]));
- Assert.AreEqual("test", (String)doc["b"]);
- }
-
- [Test]
- public void TestReadDocWithDocs(){
-// Document doc = new Document().Append("a", new Document().Append("b", new Document().Append("c",new Document())));
-// Console.WriteLine(ConvertDocToHex(doc));
- byte[] buf = HexToBytes("1D000000036100150000000362000D0000000363000500000000000000");
- MemoryStream ms = new MemoryStream(buf);
- BsonReader reader = new BsonReader(ms);
-
- Document doc = reader.ReadDocument();
- Assert.IsNotNull(doc, "Document was null");
- Assert.AreEqual(buf.Length, reader.Position);
- Assert.IsTrue(doc.Contains("a"));
-
- }
-
- [Test]
- public void TestReadBigDocument(){
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
-
- Document expected = new Document();
- expected.Append("str", "test")
- .Append("int", 45)
- .Append("long", (long)46)
- .Append("num", 4.5)
- .Append("date",DateTime.Today)
- .Append("_id", new OidGenerator().Generate())
- .Append("code", new Code("return 1;"))
- .Append("subdoc", new Document().Append("a",1).Append("b",2))
- .Append("array", new String[]{"a","b","c","d"})
- .Append("codewscope", new CodeWScope("return 2;", new Document().Append("c",1)))
- .Append("binary", new Binary(new byte[]{0,1,2,3}))
- .Append("regex", new MongoRegex("[A-Z]"))
- .Append("minkey", MongoMinKey.Value)
- .Append("maxkey", MongoMaxKey.Value)
- ;
- writer.Write(expected);
- writer.Flush();
- ms.Seek(0,SeekOrigin.Begin);
-
- BsonReader reader = new BsonReader(ms);
- Document doc = reader.Read();
-
- Assert.IsNotNull(doc);
- }
-
- private String ConvertDocToHex(Document doc){
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
-
- writer.Write(doc);
- return BitConverter.ToString(ms.ToArray()).Replace("-","");
-
- }
-
- private byte[] HexToBytes(string hex){
- //TODO externalize somewhere.
- if(hex.Length % 2 == 1){
- System.Console.WriteLine("uneven number of hex pairs.");
- hex = "0" + hex;
- }
- int numberChars = hex.Length;
- byte[] bytes = new byte[numberChars / 2];
- for (int i = 0; i < numberChars; i += 2){
- try{
- bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
- }
- catch{
- //failed to convert these 2 chars, they may contain illegal charracters
- bytes[i / 2] = 0;
- }
- }
- return bytes;
- }
-
- }
-}
diff --git a/MongoDB.Net-Tests/Bson/TestBsonWriter.cs b/MongoDB.Net-Tests/Bson/TestBsonWriter.cs
deleted file mode 100644
index aff7daac..00000000
--- a/MongoDB.Net-Tests/Bson/TestBsonWriter.cs
+++ /dev/null
@@ -1,151 +0,0 @@
-using System;
-using System.IO;
-using System.Text;
-
-using NUnit.Framework;
-
-using MongoDB.Driver;
-
-namespace MongoDB.Driver.Bson
-{
- [TestFixture]
- public class TestBsonWriter
- {
- char euro = '\u20ac';
- [Test]
- public void TestCalculateSizeOfEmptyDoc(){
- Document doc = new Document();
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
-
- Assert.AreEqual(5,writer.CalculateSize(doc));
- }
-
- [Test]
- public void TestCalculateSizeOfSimpleDoc(){
- Document doc = new Document();
- doc.Append("a","a");
- doc.Append("b",1);
-
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
- //BsonDocument bdoc = BsonConvert.From(doc);
-
- Assert.AreEqual(21,writer.CalculateSize(doc));
- }
-
- [Test]
- public void TestCalculateSizeOfComplexDoc(){
- Document doc = new Document();
- doc.Append("a","a");
- doc.Append("b",1);
- Document sub = new Document().Append("c_1",1).Append("c_2",DateTime.Now);
- doc.Append("c",sub);
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
-
- Assert.AreEqual(51,writer.CalculateSize(doc));
- }
-
- [Test]
- public void TestWriteString(){
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
- string expected = "54-65-73-74-73-2E-69-6E-73-65-72-74-73-00";
- writer.WriteString("Tests.inserts");
-
- string hexdump = BitConverter.ToString(ms.ToArray());
-
- Assert.AreEqual(expected, hexdump);
- }
-
- [Test]
- public void TestWriteMultibyteString(){
-
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
-
- string val = new StringBuilder().Append(euro,3).ToString();
- string expected = BitConverter.ToString(Encoding.UTF8.GetBytes(val + '\0'));
- Assert.AreEqual(expected,WriteStringAndGetHex(val));
- }
-
- [Test]
- public void TestWriteMultibyteStringLong(){
-
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
-
- string val = new StringBuilder().Append("ww").Append(euro,180).ToString();
- string expected = BitConverter.ToString(Encoding.UTF8.GetBytes(val + '\0'));
- Assert.AreEqual(expected,WriteStringAndGetHex(val));
- }
-
- private string WriteStringAndGetHex(string val){
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
- writer.WriteString(val);
- return BitConverter.ToString(ms.ToArray());
- }
-
- [Test]
- public void TestWriteDocument(){
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
- string expected = "1400000002746573740005000000746573740000";
- Document doc = new Document().Append("test", "test");
-
- writer.Write(doc);
-
- string hexdump = BitConverter.ToString(ms.ToArray());
- hexdump = hexdump.Replace("-","");
-
- Assert.AreEqual(expected, hexdump);
- }
-
- [Test]
- public void TestWriteArrayDoc(){
- String expected = "2000000002300002000000610002310002000000620002320002000000630000";
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
-
- String[] str = new String[]{"a","b","c"};
- writer.WriteValue(BsonDataType.Array,str);
-
- string hexdump = BitConverter.ToString(ms.ToArray());
- hexdump = hexdump.Replace("-","");
- Assert.AreEqual(expected, hexdump);
- }
-
- [Test]
- public void TestNullsDontThrowExceptions(){
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
- Document doc = new Document().Append("n", null);
- try{
- writer.Write(doc);
- }catch(NullReferenceException){
- Assert.Fail("Null Reference Exception was thrown on trying to serialize a null value");
- }
- }
-
- [Test]
- public void TestWritingTooLargeDocument(){
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
- Binary b = new Binary(new byte[BsonInfo.MaxDocumentSize]);
- Document big = new Document().Append("x", b);
- bool thrown = false;
- try{
- writer.Write(big);
- }catch(ArgumentException){
- thrown = true;
- }catch(Exception e){
- Assert.Fail("Wrong Exception thrown " + e.GetType().Name);
- }
-
- Assert.IsTrue(thrown, "Shouldn't be able to write large document");
- }
-
- }
-}
diff --git a/MongoDB.Net-Tests/Configuration/TestConfigurationSection.cs b/MongoDB.Net-Tests/Configuration/TestConfigurationSection.cs
deleted file mode 100644
index 39ed3834..00000000
--- a/MongoDB.Net-Tests/Configuration/TestConfigurationSection.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using System;
-using System.Configuration;
-
-using NUnit.Framework;
-
-using MongoDB.Driver;
-
-namespace MongoDB.Driver.Configuration
-{
- [TestFixture]
- public class TestConfigurationSection
- {
- [Test]
- public void TestReadNamed(){
- MongoConfiguration config = (MongoConfiguration)ConfigurationManager.GetSection("Mongo");
- Assert.AreEqual("Server=localhost:27018", config.Connections["local21018"].ConnectionString);
- }
-
- [Test]
- public void TestReadDefaults(){
- MongoConfiguration config = (MongoConfiguration)ConfigurationManager.GetSection("Mongo");
- Assert.AreEqual("Server=localhost:27017", config.Connections["defaults"].ConnectionString);
- }
- }
-}
diff --git a/MongoDB.Net-Tests/Connections/TestConnection.cs b/MongoDB.Net-Tests/Connections/TestConnection.cs
deleted file mode 100644
index b61c03fa..00000000
--- a/MongoDB.Net-Tests/Connections/TestConnection.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-using System;
-using System.IO;
-using MongoDB.Driver.Protocol;
-using NUnit.Framework;
-using MongoDB.Driver.IO;
-
-namespace MongoDB.Driver.Connections
-{
- [TestFixture()]
- public class TestConnection
- {
- [Test]
- public void TestSendQueryMessage(){
- //Connection conn = new Connection("10.141.153.2");
- Connections.Connection conn = ConnectionFactory.GetConnection(string.Empty);
- conn.Open();
-
- QueryMessage qmsg = generateQueryMessage();
- conn.SendTwoWayMessage(qmsg);
-
- conn.Close();
- }
-
- [Test]
- public void TestReconnectOnce(){
- Connections.Connection conn = ConnectionFactory.GetConnection(string.Empty);
- conn.Open();
-
- WriteBadMessage(conn);
- try{
- QueryMessage qmsg = generateQueryMessage();
- conn.SendTwoWayMessage(qmsg);
-
- }catch(IOException){
- //Should be able to resend.
- Assert.IsTrue(conn.State == ConnectionState.Opened);
- QueryMessage qmsg = generateQueryMessage();
- ReplyMessage rmsg = conn.SendTwoWayMessage(qmsg);
- Assert.IsNotNull(rmsg);
-
- }
- }
-
- protected void WriteBadMessage(Connections.Connection conn){
- //Write a bad message to the socket to force mongo to shut down our connection.
- BinaryWriter writer = new BinaryWriter(conn.GetStream());
- System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
- Byte[] msg = encoding.GetBytes("Goodbye MongoDB!");
- writer.Write(16 + msg.Length + 1);
- writer.Write(1);
- writer.Write(1);
- writer.Write(1001);
- writer.Write(msg);
- writer.Write((byte)0);
- }
-
- protected QueryMessage generateQueryMessage(){
- Document qdoc = new Document();
- qdoc.Add("listDatabases", 1.0);
- //QueryMessage qmsg = new QueryMessage(qdoc,"system.namespaces");
- QueryMessage qmsg = new QueryMessage(qdoc,"admin.$cmd");
- qmsg.NumberToReturn = -1;
-
- return qmsg;
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/Connections/TestConnectionFactory.cs b/MongoDB.Net-Tests/Connections/TestConnectionFactory.cs
deleted file mode 100644
index ed581018..00000000
--- a/MongoDB.Net-Tests/Connections/TestConnectionFactory.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-using System;
-
-using NUnit.Framework;
-
-namespace MongoDB.Driver.Connections
-{
- [TestFixture]
- public class TestConnectionFactory
- {
- [TearDown]
- public void TearDown (){
- ConnectionFactory.Shutdown ();
- }
-
- [Test]
- public void TestGetConnection (){
- var connection1 = ConnectionFactory.GetConnection (string.Empty);
- var connection2 = ConnectionFactory.GetConnection (string.Empty);
- Assert.IsNotNull (connection1);
- Assert.IsNotNull (connection2);
- Assert.AreEqual (1, ConnectionFactory.PoolCount);
- }
-
- [Test]
- public void TestCreatePoolForEachUniqeConnectionString (){
- ConnectionFactory.GetConnection (string.Empty);
- ConnectionFactory.GetConnection (string.Empty);
- ConnectionFactory.GetConnection ("Username=test");
- ConnectionFactory.GetConnection ("Username=test");
- ConnectionFactory.GetConnection ("Server=localhost");
- Assert.AreEqual (3, ConnectionFactory.PoolCount);
- }
-
- [Test]
- public void TestExceptionWhenMinimumPoolSizeIsGreaterThenMaximumPoolSize (){
- try{
- ConnectionFactory.GetConnection("MinimumPoolSize=50; MaximumPoolSize=10");
- }catch(ArgumentException){
- }catch(Exception){
- Assert.Fail("Wrong exception thrown");
- }
- }
- }
-}
diff --git a/MongoDB.Net-Tests/IO/TestQueryMessage.cs b/MongoDB.Net-Tests/IO/TestQueryMessage.cs
deleted file mode 100755
index 48c26123..00000000
--- a/MongoDB.Net-Tests/IO/TestQueryMessage.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-using System;
-using System.IO;
-using MongoDB.Driver.Protocol;
-using NUnit.Framework;
-
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver.IO
-{
- [TestFixture]
- public class TestQueryMessage
- {
- [Test]
- public void TestAllBytesWritten()
- {
- Document query = new Document();
- query.Add("col1", 1);
-
- QueryMessage msg = new QueryMessage(query,"TestDB.TestCol");
- MemoryStream buffer = new MemoryStream();
- msg.Write(buffer);
-
- Byte[] output = buffer.ToArray();
- String hexdump = BitConverter.ToString(output);
- //Console.WriteLine("Dump: " + hexdump);
-
- Assert.IsTrue(output.Length > 0);
- Assert.AreEqual("3A-00-00-00-00-00-00-00-00-00-00-00-D4-07-00-00-00-00-00-00-54-65-73-74-44-42-2E-54-65-73-74-43-6F-6C-00-00-00-00-00-00-00-00-00-0F-00-00-00-10-63-6F-6C-31-00-01-00-00-00-00", hexdump);
-
- }
-
- [Test]
- public void TestWriteMessageTwice(){
- string expectedHex = "3A-00-00-00-00-00-00-00-00-00-00-00-D4-07-00-00-00-00-00-00-54-65-73-74-44-42-2E-54-65-73-74-43-6F-6C-00-00-00-00-00-00-00-00-00-0F-00-00-00-10-63-6F-6C-31-00-01-00-00-00-00";
- Document query = new Document();
- query.Add("col1", 1);
-
- QueryMessage msg = new QueryMessage(query,"TestDB.TestCol");
- MemoryStream buffer = new MemoryStream();
- msg.Write(buffer);
-
- Byte[] output = buffer.ToArray();
- String hexdump = BitConverter.ToString(output);
-
- MemoryStream buffer2 = new MemoryStream();
- msg.Write(buffer2);
-
- Byte[] output2 = buffer.ToArray();
- String hexdump2 = BitConverter.ToString(output2);
-
- Assert.AreEqual(expectedHex,hexdump);
- Assert.AreEqual(hexdump,hexdump2);
-
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/MongoDB.Driver.Tests.csproj b/MongoDB.Net-Tests/MongoDB.Driver.Tests.csproj
deleted file mode 100644
index 57e60b3d..00000000
--- a/MongoDB.Net-Tests/MongoDB.Driver.Tests.csproj
+++ /dev/null
@@ -1,150 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}
- Library
- MongoDB.Driver.Tests
-
-
- 2.0
-
-
- publish\
- true
- Disk
- false
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- false
- false
- true
- v3.5
- MongoDB.Driver.Tests
- C:\Documents and Settings\scorder\Application Data\ICSharpCode/SharpDevelop3.0\Settings.SourceAnalysis
- False
- False
- false
-
-
- true
- full
- false
- bin\Debug
- DEBUG
- prompt
- 4
-
-
- none
- false
- bin\Release
- prompt
- 4
-
-
- False
-
-
- False
- Auto
- 4194304
- AnyCPU
- 4096
-
-
-
-
-
- 3.5
-
-
-
-
- False
- ..\redist\nunit.framework.dll
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Always
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- False
-
-
- False
-
-
- False
-
-
- False
-
-
- False
-
-
-
-
- {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}
- MongoDB.Driver
-
-
-
-
-
- Always
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/MongoDB.Driver.Tests.dll.config b/MongoDB.Net-Tests/MongoDB.Driver.Tests.dll.config
deleted file mode 100644
index 26ef9e06..00000000
--- a/MongoDB.Net-Tests/MongoDB.Driver.Tests.dll.config
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/TestAuthentication.cs b/MongoDB.Net-Tests/TestAuthentication.cs
deleted file mode 100644
index b9c56880..00000000
--- a/MongoDB.Net-Tests/TestAuthentication.cs
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * User: Sedward
- */
-using System;
-using MongoDB.Driver.Connections;
-using NUnit.Framework;
-
-namespace MongoDB.Driver
-{
- [TestFixture(Description = "Requires start server with --auth")]
- public class TestAuthentication
- {
- private const int AuthServerPort = MongoServerEndPoint.DefaultPort + 3;
- const String testDatabaseName = "testAuth";
- const String testuser = "testuser";
- const String testpass = "test1234";
-
- const String adminuser = "adminuser";
- const String adminpass = "admin1234";
-
- [TestFixtureSetUp]
- public void SetUp()
- {
- using(var mongo = new Mongo(CreateConnectionStringBuilder().ToString()))
- {
- mongo.Connect();
-
- var testDatabase = mongo[testDatabaseName];
- if(testDatabase.MetaData.FindUser(testuser) == null)
- testDatabase.MetaData.AddUser(testuser, testpass);
-
- var adminDatabase = mongo["admin"];
- if(adminDatabase.MetaData.FindUser(adminuser) == null)
- adminDatabase.MetaData.AddUser(adminuser, adminpass);
- }
- }
-
- [Test]
- public void TestLoginGoodPassword()
- {
- using(var mongo = ConnectAndAuthenticatedMongo(testuser, testpass))
- TryInsertData(mongo);
- }
-
- [Test]
- [ExpectedException(typeof(MongoException))]
- public void TestLoginBadPassword()
- {
- using(var mongo = ConnectAndAuthenticatedMongo(testuser, "badpassword"))
- TryInsertData(mongo);
- }
-
- [Test]
- public void TestAuthenticatedInsert(){
- using(var mongo = ConnectAndAuthenticatedMongo(testuser, testpass))
- TryInsertData(mongo);
- }
-
- [Test]
- [ExpectedException(typeof(MongoOperationException))]
- public void TestUnauthenticatedInsert(){
- using(var mongo = new Mongo(CreateConnectionStringBuilder().ToString()))
- {
- mongo.Connect();
-
- TryInsertData(mongo);
- }
- }
-
- private static Mongo ConnectAndAuthenticatedMongo(string username,string password)
- {
- var builder = CreateConnectionStringBuilder();
- builder.Username = username;
- builder.Password = password;
- var mongo = new Mongo(builder.ToString());
- mongo.Connect();
- return mongo;
- }
-
- private static MongoConnectionStringBuilder CreateConnectionStringBuilder()
- {
- var builder = new MongoConnectionStringBuilder();
- builder.AddServer("localhost", AuthServerPort);
- return builder;
- }
-
- private static void TryInsertData(Mongo mongo)
- {
- var collection = mongo[testDatabaseName]["testCollection"];
- collection.Delete(new Document(),true);
- collection.Insert(new Document().Append("value", 84),true);
-
- var value = collection.FindOne(new Document().Append("value", 84));
-
- Assert.AreEqual(84, value["value"]);
- }
-
- [TestFixtureTearDown]
- public void TestTearDown(){
- /*
- * In case clean up fails open a Mongo shell and execute the following commands
- * use admin
- * db.auth("adminuser", "admin1234");
- * db.system.users.find(); //should see adminuser
- * db.system.users.remove({user:"adminuser"});
- * db.system.users.find(); //should not see adminuser or any other.
- * Tests should now run.
- */
- using(var mongo = ConnectAndAuthenticatedMongo(adminuser, adminuser))
- {
- mongo[testDatabaseName].MetaData.RemoveUser(testuser);
- mongo["admin"].MetaData.RemoveUser(adminuser);
- }
-
- // clean connections
- ConnectionFactory.Shutdown();
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/TestB.cs b/MongoDB.Net-Tests/TestB.cs
deleted file mode 100644
index 49354316..00000000
--- a/MongoDB.Net-Tests/TestB.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-
-using System;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-
-
-using NUnit.Framework;
-
-namespace MongoDB.Driver
-{
-
-
- [TestFixture()]
- public class TestB
- {
-
- [Test()]
- public void TestCase(){
- TcpClient client = new TcpClient();
- client.Connect("localhost", 27017);
- BufferedStream buff = new BufferedStream(client.GetStream());
- BinaryWriter writer = new BinaryWriter(buff);
-
- System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
- Byte[] msg = encoding.GetBytes("Hello MongoDB!");
-
-
- writer.Write(16 + msg.Length + 1);
- writer.Write(1);
- writer.Write(1);
- writer.Write(1000);
- writer.Write(msg);
- writer.Write((byte)0);
-
- writer.Flush();
- writer.Close();
- client.Close();
-
- }
- }
-}
diff --git a/MongoDB.Net-Tests/TestBinary.cs b/MongoDB.Net-Tests/TestBinary.cs
deleted file mode 100644
index dd94a4fc..00000000
--- a/MongoDB.Net-Tests/TestBinary.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-
-using System;
-using NUnit.Framework;
-
-namespace MongoDB.Driver
-{
- [TestFixture()]
- public class TestBinary
- {
-
- [Test]
- public void TestToString(){
- Binary b = new Binary();
- }
- }
-}
diff --git a/MongoDB.Net-Tests/TestCollection.cs b/MongoDB.Net-Tests/TestCollection.cs
deleted file mode 100755
index 2cf8849b..00000000
--- a/MongoDB.Net-Tests/TestCollection.cs
+++ /dev/null
@@ -1,398 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-using NUnit.Framework;
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver
-{
- [TestFixture]
- public class TestCollection : MongoTestBase
- {
- private string pound = "\u00a3";
-
- public override string TestCollections {
- get {
- return "inserts,updates,counts,counts_spec,finds,charreads";
- }
- }
-
- public override void OnInit (){
- IMongoCollection finds = DB["finds"];
- for(int j = 1; j < 100; j++){
- finds.Insert(new Document(){{"x", 4},{"h", "hi"},{"j", j}});
- }
- for(int j = 100; j < 105; j++){
- finds.Insert(new Document(){{"x", 4},{"n", 1},{"j", j}});
- }
- IMongoCollection charreads = DB["charreads"];
- charreads.Insert(new Document(){{"test", "1234" + pound + "56"}});
-
- }
-
-
- [Test]
- public void TestFindOne(){
- Document query = new Document();
- query["j"] = 10;
- Document result = DB["finds"].FindOne(query);
- Assert.IsNotNull(result);
- Assert.AreEqual(4, result["x"]);
- Assert.AreEqual(10, result["j"]);
-
- }
-
- [Test]
- public void TestFindOneNotThere(){
- Document query = new Document();
- query["not_there"] = 10;
- Document result = DB["finds"].FindOne(query);
- Assert.IsNull(result);
- }
-
- [Test]
- public void TestFindNulls(){
- Document query = new Document().Append("n",DBNull.Value);
- long numnulls = DB["finds"].Count(query);
- Assert.AreEqual(99,numnulls);
- }
-
- [Test]
- public void TestFindAttributeLimit(){
- Document query = new Document();
- query["j"] = 10;
- Document fields = new Document();
- fields["x"] = 1;
-
- ICursor c = DB["finds"].Find(query,-1,0,fields);
- foreach(Document result in c.Documents){
- Assert.IsNotNull(result);
- Assert.AreEqual(4, result["x"]);
- Assert.IsNull(result["j"]);
- }
- }
-
- [Test]
- public void TestFindGTRange(){
- Document query = new Document();
- query["j"] = new Document().Append("$gt",20);
-
- ICursor c = DB["finds"].Find(query);
- foreach(Document result in c.Documents){
- Assert.IsNotNull(result);
- Object j = result["j"];
- Assert.IsTrue(Convert.ToDouble(j) > 20);
- }
- }
-
- [Test]
- public void TestManualWhere(){
- Document query = new Document().Append("$where", new Code("this.j % 2 == 0"));
- ICursor c = DB["finds"].Find(query);
- foreach(Document result in c.Documents){
- Assert.IsNotNull(result);
- Object j = result["j"];
- Assert.IsTrue(Convert.ToInt32(j) % 2 == 0);
- }
- }
- [Test]
- public void TestFindWhereEquivalency(){
- IMongoCollection col = DB["finds"];
- Document lt = new Document().Append("j", new Document().Append("$lt", 5));
- string where = "this.j < 5";
- Document explicitWhere = new Document().Append("$where", new Code(where));
- CodeWScope func = new CodeWScope("function() { return this.j < 5; }", new Document());
- Document funcDoc = new Document().Append("$where", func);
-
- Assert.AreEqual(4, CountDocs(col.Find(lt)), "Basic find didn't return 4 docs");
- Assert.AreEqual(4, CountDocs(col.Find(where)), "String where didn't return 4 docs");
- Assert.AreEqual(4, CountDocs(col.Find(explicitWhere)), "Explicit where didn't return 4 docs");
- Assert.AreEqual(4, CountDocs(col.Find(funcDoc)), "Function where didn't return 4 docs");
- }
-
- private int CountDocs(ICursor cur){
- int cnt = 0;
- foreach(Document doc in cur.Documents){
- cnt++;
- }
- return cnt;
- }
- [Test]
- public void TestWhere(){
- ICursor c = DB["finds"].Find("this.j % 2 == 0");
- foreach(Document result in c.Documents){
- Assert.IsNotNull(result);
- Object j = result["j"];
- Assert.IsTrue(Convert.ToInt32(j) % 2 == 0);
- }
- }
-
- [Test]
- public void TestFindOneObjectContainingUKPound(){
- Document query = new Document();
- Document result = DB["charreads"].FindOne(query);
- Assert.IsNotNull(result);
- Assert.IsTrue(result.Contains("test"));
- Assert.AreEqual("1234£56",result["test"]);
- }
-
- [Test]
- public void TestSimpleInsert(){
- IMongoCollection inserts = DB["inserts"];
- Document indoc = new Document();
- indoc["song"] = "Palmdale";
- indoc["artist"] = "Afroman";
- indoc["year"] = 1999;
-
- inserts.Insert(indoc);
-
- Document result = inserts.FindOne(new Document().Append("song","Palmdale"));
- Assert.IsNotNull(result);
- Assert.AreEqual(1999,result["year"]);
- }
-
- [Test]
- public void TestReallySimpleInsert(){
- IMongoCollection inserts = DB["inserts"];
- Document indoc = new Document();
- indoc["y"] = 1;
- indoc["x"] = 2;
- inserts.Insert(indoc);
-
- Document result = inserts.FindOne(new Document().Append("x",2));
- Assert.IsNotNull(result);
- Assert.AreEqual(1,result["y"]);
- }
-
- [Test]
- public void TestPoundSymbolInsert(){
- IMongoCollection inserts = DB["inserts"];
- Document indoc = new Document().Append("x","1234" + pound + "56").Append("y",1);;
- inserts.Insert(indoc);
-
- Document result = inserts.FindOne(new Document().Append("x","1234" + pound + "56"));
- Assert.IsNotNull(result);
- Assert.AreEqual(1,result["y"]);
- }
-
- [Test]
- public void TestArrayInsert(){
- IMongoCollection inserts = DB["inserts"];
- Document indoc1 = new Document();
- indoc1["song"] = "The Axe";
- indoc1["artist"] = "Tinsley Ellis";
- indoc1["year"] = 2006;
-
- Document indoc2 = new Document();
- indoc2["song"] = "The Axe2";
- indoc2["artist"] = "Tinsley Ellis2";
- indoc2["year"] = 2008;
-
- inserts.Insert(new Document[]{indoc1,indoc2});
-
- Document result = inserts.FindOne(new Document().Append("song","The Axe"));
- Assert.IsNotNull(result);
- Assert.AreEqual(2006,result["year"]);
-
- result = inserts.FindOne(new Document().Append("song","The Axe2"));
- Assert.IsNotNull(result);
- Assert.AreEqual(2008,result["year"]);
- }
-
- [Test]
- public void TestInsertOfArray(){
- OidGenerator ogen = new OidGenerator();
- IMongoCollection inserts = DB["inserts"];
- Document album = new Document();
- album["_id"] = ogen.Generate();
- album["artist"] = "Popa Chubby";
- album["title"] = "Deliveries After Dark";
- album["songs"] = new[] {
- new Document().Append("title", "Let The Music Set You Free").Append("length", "5:15").Append("_id", ogen.Generate()),
- new Document().Append("title", "Sally Likes to Run").Append("length", "4:06").Append("_id", ogen.Generate()),
- new Document().Append("title", "Deliveries After Dark").Append("length", "4:17").Append("_id", ogen.Generate()),
- new Document().Append("title", "Theme From The Godfather").Append("length", "3:06").Append("_id", ogen.Generate()),
- new Document().Append("title", "Grown Man Crying Blues").Append("length", "8:09").Append("_id", ogen.Generate()),
- };
- inserts.Insert(album);
-
- Document result = inserts.FindOne(new Document().Append("songs.title","Deliveries After Dark"));
- Assert.IsNotNull(result);
-
- Assert.AreEqual(album.ToString(), result.ToString());
- }
-
- [Test]
- public void TestInsertLargerThan4MBDocument(){
- Binary b = new Binary(new byte[1024 * 1024]);
- Document big = new Document(){{"name", "Big Document"}, {"b1", b}, {"b2", b}, {"b3", b}, {"b4", b}};
- IMongoCollection inserts = DB["inserts"];
- bool thrown = false;
- try{
- inserts.Insert(big);
- }catch(MongoException){
- thrown = true;
- }catch(Exception e){
- Assert.Fail("Wrong Exception thrown " + e.GetType().Name);
- }
- Assert.IsTrue(thrown, "Shouldn't be able to insert large document");
- }
-
- [Test]
- public void TestInsertBulkLargerThan4MBOfDocuments(){
- Binary b = new Binary(new byte[1024 * 1024 * 2]);
- IMongoCollection inserts = DB["inserts"];
- try{
- Document[] docs = new Document[10];
- //6MB+ of documents
- for(int x = 0; x < docs.Length; x++){
- docs[x] = new Document(){{"name", "bulk"}, {"b", b}, {"x", x}};
- }
- inserts.Insert(docs,true);
- long count = inserts.Count(new Document(){{"name", "bulk"}});
- Assert.AreEqual(docs.Length, count, "Wrong number of documents inserted");
- }catch(MongoException){
- Assert.Fail("MongoException should not have been thrown.");
- }
- }
-
- [Test]
- public void TestDelete(){
- IMongoCollection deletes = DB["deletes"];
- Document doc = new Document();
- doc["y"] = 1;
- doc["x"] = 2;
- deletes.Insert(doc);
-
- Document selector = new Document().Append("x",2);
-
- Document result = deletes.FindOne(selector);
- Assert.IsNotNull(result);
- Assert.AreEqual(1,result["y"]);
-
- deletes.Delete(selector);
- result = deletes.FindOne(selector);
- Assert.IsNull(result,"Shouldn't have been able to find a document that was deleted");
-
- }
-
- [Test]
- public void TestUpdateUpsertNotExisting(){
- IMongoCollection updates = DB["updates"];
- Document doc = new Document();
- doc["First"] = "Sam";
- doc["Last"] = "CorderNE";
-
- updates.Update(doc);
- Document selector = new Document().Append("Last", "CorderNE");
- Document result = updates.FindOne(selector);
- Assert.IsNotNull(result);
- Assert.AreEqual("Sam", result["First"]);
- }
-
- [Test]
- public void TestUpdateUpsertExisting(){
- IMongoCollection updates = DB["updates"];
- Document doc = new Document();
- doc["First"] = "Mtt";
- doc["Last"] = "Brewer";
-
- updates.Insert(doc);
-
- Document selector = new Document().Append("Last", "Brewer");
- doc = updates.FindOne(selector);
- Assert.IsNotNull(doc);
- Assert.AreEqual("Mtt", doc["First"]);
- Assert.IsNotNull(doc["_id"]);
-
- doc["First"] = "Matt";
- updates.Update(doc);
-
- Document result = updates.FindOne(selector);
- Assert.IsNotNull(result);
- Assert.AreEqual("Matt", result["First"]);
-
- }
-
- [Test]
- public void TestUpdateMany(){
- IMongoCollection updates = DB["updates"];
-
- updates.Insert(new Document().Append("Last", "Cordr").Append("First","Sam"));
- updates.Insert(new Document().Append("Last", "Cordr").Append("First","Sam2"));
- updates.Insert(new Document().Append("Last", "Cordr").Append("First","Sam3"));
-
- Document selector = new Document().Append("Last", "Cordr");
- ICursor results = updates.Find(selector);
- bool found = false;
- foreach(Document doc in results.Documents){
- Assert.AreEqual("Cordr", doc["Last"]);
- found = true;
- }
- Assert.IsTrue(found,"Should have found docs inserted for TestUpdateMany");
- Assert.AreEqual(3, updates.Count(selector), "Didn't find all Documents inserted for TestUpdateMany with Selector");
-
- //Document updateData = new Document().Append("$set", new Document().Append("Last", "Corder2"));
- Document updateData = new Document().Append("Last", "Corder2");
- updates.UpdateAll(updateData, selector);
-
- selector["Last"] = "Corder2";
- Assert.AreEqual(3, updates.Count(selector), "Not all Cordr documents were updated");
-
- results = updates.Find(selector);
- found = false;
- foreach(Document doc in results.Documents){
- Assert.AreEqual("Corder2", doc["Last"]);
- Assert.IsNotNull(doc["First"],"First name should not disappear");
- found = true;
- }
- Assert.IsTrue(found,"Should have found docs updated for TestMany");
- }
-
- [Test]
- public void TestUpdatePartial(){
- IMongoCollection updates = DB["updates"];
- int coolness = 5;
- Document einstein = new Document(){{"Last", "Einstien"},{"First", "Albert"},{"Coolness",coolness++}};
- updates.Insert(einstein);
- Document selector = new Document(){{"_id", einstein["_id"]}};
-
- updates.Update(new Document(){{"$inc", new Document(){{"Coolness", 1}}}}, selector);
- Assert.AreEqual(coolness++, Convert.ToInt32(updates.FindOne(selector)["Coolness"]), "Coolness field not incremented", true);
-
- updates.Update(new Document(){{"$set",new Document(){{"Last", "Einstein"}}},
- {"$inc",new Document(){{"Coolness",1}}}},selector,true);
- Assert.AreEqual(coolness++, Convert.ToInt32(updates.FindOne(selector)["Coolness"]), "Coolness field not incremented");
- }
-
- [Test]
- public void TestCount(){
- IMongoCollection counts = DB["counts"];
- int top = 100;
- for(int i = 0; i < top; i++){
- counts.Insert(new Document().Append("Last", "Cordr").Append("First","Sam").Append("cnt", i));
- }
- long cnt = counts.Count();
- Assert.AreEqual(top,cnt, "Count not the same as number of inserted records");
- }
-
- [Test]
- public void TestCountWithSpec(){
- IMongoCollection counts = DB["counts_spec"];
- counts.Insert(new Document().Append("Last", "Cordr").Append("First","Sam").Append("cnt", 1));
- counts.Insert(new Document().Append("Last", "Cordr").Append("First","Sam").Append("cnt", 2));
- counts.Insert(new Document().Append("Last", "Corder").Append("First","Sam").Append("cnt", 3));
-
- Assert.AreEqual(2, counts.Count(new Document().Append("Last", "Cordr")));
- Assert.AreEqual(1, counts.Count(new Document().Append("Last", "Corder")));
- Assert.AreEqual(0, counts.Count(new Document().Append("Last", "Brown")));
-
- }
-
- [Test]
- public void TestCountInvalidCollection(){
- IMongoCollection counts = DB["counts_wtf"];
- Assert.AreEqual(0, counts.Count());
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/TestConnectionStringBuilder.cs b/MongoDB.Net-Tests/TestConnectionStringBuilder.cs
deleted file mode 100644
index 44acdda7..00000000
--- a/MongoDB.Net-Tests/TestConnectionStringBuilder.cs
+++ /dev/null
@@ -1,85 +0,0 @@
-using System;
-using System.Collections.Generic;
-using NUnit.Framework;
-
-namespace MongoDB.Driver
-{
- [TestFixture]
- public class TestConnectionStringBuilder
- {
- [Test]
- public void TestCreateEmptyInstance (){
- new MongoConnectionStringBuilder ();
- }
-
- [Test]
- public void TestDefaults (){
- var builder = new MongoConnectionStringBuilder ();
- Assert.IsNull (builder.Username);
- Assert.IsNull (builder.Password);
- Assert.AreEqual (builder.MaximumPoolSize, MongoConnectionStringBuilder.DefaultMaximumPoolSize);
- Assert.AreEqual (builder.MinimumPoolSize, MongoConnectionStringBuilder.DefaultMinimumPoolSize);
- Assert.AreEqual (builder.ConnectionLifetime, MongoConnectionStringBuilder.DefaultConnectionLifeTime);
- Assert.AreEqual (builder.ConnectionTimeout, MongoConnectionStringBuilder.DefaultConnectionTimeout);
- Assert.AreEqual (builder.Pooled, MongoConnectionStringBuilder.DefaultPooled);
-
- var servers = new List (builder.Servers);
- Assert.AreEqual (1, servers.Count);
- Assert.AreEqual (MongoServerEndPoint.DefaultPort, servers[0].Port);
- Assert.AreEqual (MongoServerEndPoint.DefaultHost, servers[0].Host);
- }
-
- [Test]
- public void TestConnectionStringParsing (){
- var builder = new MongoConnectionStringBuilder ("Username=testuser;Password=testpassword;Server=testserver:555;ConnectionLifetime=50;MaximumPoolSize=101;MinimumPoolSize=202;Pooled=false");
- Assert.AreEqual ("testuser", builder.Username);
- Assert.AreEqual ("testpassword", builder.Password);
- Assert.AreEqual (101, builder.MaximumPoolSize);
- Assert.AreEqual (202, builder.MinimumPoolSize);
- Assert.AreEqual (TimeSpan.FromSeconds (50), builder.ConnectionLifetime);
- Assert.AreEqual (false, builder.Pooled);
-
- var servers = new List(builder.Servers);
- Assert.AreEqual (1, servers.Count);
- Assert.AreEqual ("testserver", servers[0].Host);
- Assert.AreEqual (555, servers[0].Port);
- }
-
- [Test]
- public void TestConnectionStringParsingServerWithoutPort (){
- var builder = new MongoConnectionStringBuilder ("Username=testuser;Password=testpassword;Server=testserver");
- Assert.AreEqual ("testuser", builder.Username);
- Assert.AreEqual ("testpassword", builder.Password);
-
- var servers = new List (builder.Servers);
- Assert.AreEqual (1, servers.Count);
- Assert.AreEqual ("testserver", servers[0].Host);
- Assert.AreEqual (MongoServerEndPoint.DefaultPort, servers[0].Port);
- }
-
- [Test]
- public void TestToStringOutput (){
- var builder = new MongoConnectionStringBuilder { Password = "testpassword", Username = "testusername", ConnectionLifetime = TimeSpan.FromSeconds (50), MaximumPoolSize = 101, MinimumPoolSize = 202, ConnectionTimeout = TimeSpan.FromSeconds(60)};
- builder.AddServer ("testserver1", 555);
- builder.AddServer ("testserver2");
-
- Assert.AreEqual ("Username=testusername;Password=testpassword;Server=testserver1:555,testserver2;MaximumPoolSize=101;MinimumPoolSize=202;ConnectionTimeout=60;ConnectionLifetime=50", builder.ToString ());
- }
-
- [Test]
- public void TestToStringOutputWithoutUsernameAndPassword (){
- var builder = new MongoConnectionStringBuilder ();
- builder.AddServer ("testserver", 555);
-
- Assert.AreEqual ("Server=testserver:555", builder.ToString ());
- }
-
- [Test]
- public void TestToStringOutputWithDefaultServerPort (){
- var builder = new MongoConnectionStringBuilder ();
- builder.AddServer ("testserver");
- Assert.AreEqual ("Server=testserver", builder.ToString ());
- }
-
- }
-}
diff --git a/MongoDB.Net-Tests/TestCursor.cs b/MongoDB.Net-Tests/TestCursor.cs
deleted file mode 100644
index 16de1f19..00000000
--- a/MongoDB.Net-Tests/TestCursor.cs
+++ /dev/null
@@ -1,142 +0,0 @@
-using System;
-using NUnit.Framework;
-
-using MongoDB.Driver;
-using MongoDB.Driver.IO;
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver
-{
- [TestFixture]
- public class TestCursor : MongoTestBase
- {
- public override string TestCollections {
- get {
- return "sorts,hintindex,smallreads,reads";
- }
- }
-
- public override void OnInit (){
- //smallreads
- IMongoCollection smallreads = DB["smallreads"];
- for(int j = 1; j < 5; j++){
- smallreads.Insert(new Document(){{"x", 4},{"j", j}});
- }
- smallreads.Insert(new Document(){{"x", 4}, {"j", 5}, {"n", 1}});
-
- IMongoCollection reads = DB["reads"];
- for(int j = 1; j < 10000; j++){
- reads.Insert(new Document(){{"x", 4},{"h", "hi"},{"j", j}});
- }
- }
-
-
- [Test]
- public void TestCanReadSmall()
- {
- ICursor c = DB["smallreads"].FindAll();
-
- Assert.IsNotNull(c,"Cursor shouldn't be null");
- int reads = 0;
- foreach(Document doc in c.Documents){
- reads++;
- }
- Assert.IsTrue(reads > 0, "No documents were returned.");
- Assert.AreEqual(5, reads, "More than 5 documents in the small reads dataset");
- }
-
- [Test]
- public void TestCanReadMore(){
- ICursor c = DB["reads"].FindAll();
-
- Assert.IsNotNull(c,"Cursor shouldn't be null");
- int reads = 0;
- int idchanges = 0;
- long id = 0;
- foreach(Document doc in c.Documents){
- reads++;
- if(c.Id != id){
- idchanges++;
- id = c.Id;
- }
- }
- Assert.IsTrue(reads > 0, "No documents were returned.");
- Assert.IsTrue(idchanges > 0,String.Format("ReadMore message never sent. {0} changes seen", idchanges));
- Assert.AreEqual(9999,reads, "Not all documents returned.");
- System.Console.Out.Write(String.Format("{0} records read", reads));
-
-
- }
- [Test]
- public void TestCanReadAndKillCursor()
- {
- ICursor c = DB["reads"].FindAll();
-
- Assert.IsNotNull(c,"Cursor shouldn't be null");
- foreach(Document doc in c.Documents){
- break;
- }
- c.Dispose();
- Assert.AreEqual(0,c.Id);
- }
-
- [Test]
- public void TestCanLimit(){
- ICursor c = DB["reads"].FindAll().Limit(5);
-
- Assert.IsNotNull(c,"Cursor shouldn't be null");
- int reads = 0;
- foreach(Document doc in c.Documents){
- reads++;
- }
- Assert.IsTrue(reads > 0, "No documents were returned.");
- Assert.AreEqual(5, reads);
- }
-
- [Test]
- public void TestSort(){
- IMongoCollection sorts = DB["sorts"];
- int[] randoms = new int[]{4,6,8,9,1,3,2,5,7,0};
- foreach(int x in randoms){
- sorts.Insert(new Document().Append("x", randoms[x]));
- }
- Assert.AreEqual(randoms.Length, sorts.Count());
-
- int exp = 0;
- foreach(Document doc in sorts.FindAll().Sort("x", IndexOrder.Ascending).Documents){
- Assert.AreEqual(exp, Convert.ToInt32(doc["x"]));
- exp++;
- }
-
- exp = 9;
- foreach(Document doc in sorts.FindAll().Sort("x", IndexOrder.Descending).Documents){
- Assert.AreEqual(exp, Convert.ToInt32(doc["x"]));
- exp--;
- }
- }
-
- [Test]
- public void TestExplain(){
- Document exp = DB["reads"].FindAll().Limit(5).Skip(5).Sort("x").Explain();
- Assert.IsTrue(exp.Contains("cursor"));
- Assert.IsTrue(exp.Contains("n"));
- Assert.IsTrue(exp.Contains("nscanned"));
- }
-
- [Test]
- public void TestHint(){
- IMongoCollection reads = DB["reads"];
- Document hint = new Document().Append("x",IndexOrder.Ascending);
-
- Document exp = reads.FindAll().Hint(hint).Explain();
- Assert.IsTrue(exp.Contains("$err"), "No error found");
-
- reads.MetaData.CreateIndex("hintindex",hint,false);
- exp = reads.FindAll().Hint(hint).Explain();
-
- Assert.IsTrue(exp.Contains("cursor"));
- Assert.IsTrue(exp.Contains("n"));
- Assert.IsTrue(exp.Contains("nscanned"));
- }
- }
-}
diff --git a/MongoDB.Net-Tests/TestDBRef.cs b/MongoDB.Net-Tests/TestDBRef.cs
deleted file mode 100644
index 478657b0..00000000
--- a/MongoDB.Net-Tests/TestDBRef.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-
-
-using System;
-using NUnit.Framework;
-
-namespace MongoDB.Driver
-{
- [TestFixture]
- public class TestDBRef
- {
- [Test]
- public void TestEqualsAreSameObject (){
- DBRef r = new DBRef ("tests", "2312314");
- Assert.AreEqual (r, r);
- }
-
- [Test]
- public void TestEqualsUsingSameValues (){
- String colname = "tests";
- String id = "32312312";
- DBRef r = new DBRef (colname, id);
- DBRef r2 = new DBRef (colname, id);
-
- Assert.AreEqual (r, r2);
- }
-
- [Test]
- public void TestFromDocument (){
- String colname = "tests";
- String id = "32312312";
- Document doc = new Document ().Append (DBRef.RefName, colname).Append (DBRef.IdName, id);
-
- DBRef expected = new DBRef (colname, id);
- Assert.AreEqual (expected, DBRef.FromDocument (doc));
- }
-
- [Test]
- public void TestFromIncompleteDocumentThrowsArguementException (){
- bool thrown = false;
- try {
- DBRef.FromDocument (new Document ().Append (DBRef.RefName, "tests"));
- } catch (ArgumentException) {
- thrown = true;
- }
- Assert.IsTrue (thrown, "ArgumentException should have been thrown when trying to create convert from incomplete document");
-
- }
-
- [Test]
- public void TestIsDocumentDBRef (){
- Document doc = new Document ();
-
- Assert.IsFalse (DBRef.IsDocumentDBRef (null));
- Assert.IsFalse (DBRef.IsDocumentDBRef (doc));
-
- doc[DBRef.RefName] = "tests";
- Assert.IsFalse (DBRef.IsDocumentDBRef (doc));
-
- doc.Remove (DBRef.RefName);
- doc[DBRef.IdName] = "12312131";
- Assert.IsFalse (DBRef.IsDocumentDBRef (doc));
-
- doc[DBRef.RefName] = "tests";
- Assert.IsTrue (DBRef.IsDocumentDBRef (doc));
-
- doc[DBRef.MetaName] = new Document();
- Assert.IsTrue (DBRef.IsDocumentDBRef (doc));
- }
-
- [Test]
- public void TestCastsToDocument (){
- OidGenerator ogen = new OidGenerator ();
- DBRef dref = new DBRef ("tests.dbrefs", ogen.Generate ());
- Document doc = (Document)dref;
- Assert.AreEqual (dref.CollectionName, doc[DBRef.RefName]);
- }
- }
-}
diff --git a/MongoDB.Net-Tests/TestDatabase.cs b/MongoDB.Net-Tests/TestDatabase.cs
deleted file mode 100644
index dc0cbb04..00000000
--- a/MongoDB.Net-Tests/TestDatabase.cs
+++ /dev/null
@@ -1,137 +0,0 @@
-using System;
-using System.Collections.Generic;
-using NUnit.Framework;
-
-namespace MongoDB.Driver
-{
- [TestFixture]
- public class TestDatabase : MongoTestBase
- {
- public override string TestCollections {
- get {
- return "refs,noerror,errcol,preverror";
- }
- }
-
- public override void OnInit ()
- {
- base.OnInit();
- }
-
- [Test]
- public void TestFollowReference(){
- IMongoCollection refs = DB["refs"];
- Oid id = new Oid("4a7067c30a57000000008ecb");
- string msg = "this has an oid key";
- Document doc = new Document(){{"_id", id},{"msg", msg}};
- refs.Insert(doc);
-
- DBRef rf = new DBRef("refs", id);
-
- Document target = DB.FollowReference(rf);
- Assert.IsNotNull(target, "FollowReference returned null");
- Assert.IsTrue(target.Contains("msg"));
- Assert.AreEqual(msg, target["msg"]);
- }
-
- [Test]
- public void TestFollowNonReference(){
- Oid id = new Oid("BAD067c30a57000000008ecb");
- DBRef rf = new DBRef("refs", id);
-
- Document target = DB.FollowReference(rf);
- Assert.IsNull(target, "FollowReference returned wasn't null");
- }
-
- [Test]
- public void TestReferenceNonOid(){
- IMongoCollection refs = DB["refs"];
-
- Document doc = new Document().Append("_id",123).Append("msg", "this has a non oid key");
- refs.Insert(doc);
-
- DBRef rf = new DBRef("refs",123);
-
- Document recv = DB.FollowReference(rf);
-
- Assert.IsNotNull(recv);
- Assert.IsTrue(recv.Contains("msg"));
- Assert.AreEqual(recv["_id"], (long)123);
- }
-
- [Test]
- public void TestGetCollectionNames(){
- List names = DB.GetCollectionNames();
- Assert.IsNotNull(names,"No collection names returned");
- Assert.IsTrue(names.Count > 0);
- Assert.IsTrue(names.Contains("tests.inserts"));
- }
-
- [Test]
- public void TestEvalNoScope(){
- Document result = DB.Eval("function(){return 3;}");
- Assert.AreEqual(3, result["retval"]);
- }
-
- [Test]
- public void TestEvalWithScope(){
- int val = 3;
- Document scope = new Document().Append("x",val);
- Document result = DB.Eval("function(){return x;}", scope);
- Assert.AreEqual(val, result["retval"]);
- }
-
- [Test]
- public void TestEvalWithScopeAsFunctionParameters(){
- int x = 3;
- int y = 4;
- string func = "adder = function(a, b){return a + b;}; return adder(x,y)";
- Document scope = new Document().Append("x",x).Append("y", y);
- Document result = DB.Eval(func, scope);
- Console.Out.WriteLine(result.ToString());
- Assert.AreEqual(x + y, result["retval"]);
- }
-
- [Test]
- public void TestGetLastErrorNoError(){
- DB["noerror"].Insert(new Document(){{"a",1},{"b",2}});
- Document error = DB.GetLastError();
- Assert.AreEqual(DBNull.Value, error["err"]);
- }
-
- [Test]
- public void TestGetLastError(){
- IMongoCollection errcol = DB["errcol"];
- errcol.MetaData.CreateIndex(new Document(){{"x", IndexOrder.Ascending}}, true);
- Document dup = new Document(){{"x",1},{"y",2}};
- errcol.Insert(dup);
- Document error = DB.GetLastError();
- Assert.AreEqual(DBNull.Value, error["err"]);
-
- errcol.Insert(dup);
- error = DB.GetLastError();
-
- Assert.IsFalse(DBNull.Value == error["err"]);
-
- }
-
- [Test]
- public void TestGetPrevError(){
- IMongoCollection col = DB["preverror"];
- col.MetaData.CreateIndex(new Document(){{"x", IndexOrder.Ascending}},true);
- List docs = new List();
- for(int x = 0; x < 10; x++){
- docs.Add(new Document(){{"x",x},{"y",2}});
- }
- docs.Add(new Document(){{"x",1},{"y",4}}); //the dupe
- DB.ResetError();
- Assert.AreEqual(DBNull.Value, DB.GetLastError()["err"]);
-
- col.Insert(docs);
- Document error = DB.GetLastError();
-
- Assert.IsFalse(DBNull.Value == error["err"]);
-
- }
- }
-}
diff --git a/MongoDB.Net-Tests/TestDatabaseJS.cs b/MongoDB.Net-Tests/TestDatabaseJS.cs
deleted file mode 100644
index 5ec7eb92..00000000
--- a/MongoDB.Net-Tests/TestDatabaseJS.cs
+++ /dev/null
@@ -1,197 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-using NUnit.Framework;
-
-namespace MongoDB.Driver{
-
-
- [TestFixture()]
- public class TestDatabaseJS : MongoTestBase
- {
- DatabaseJS js;
- public override string TestCollections {
- get {
- return "jsreads";
- }
- }
-
- public override void OnInit (){
- DB["system.js"].Delete(new Document());
- js = DB.JS;
-
- IMongoCollection jsreads = DB["jsreads"];
- for(int j = 1; j < 10; j++){
- jsreads.Insert(new Document(){{"j", j}});
- }
- }
-
- [Test()]
- public void TestCanGetDatabaseJSObject(){
- Assert.IsNotNull(DB.JS);
- }
-
- [Test()]
- public void TestCanGetAFunction(){
- string name = "fget";
- AddFunction(name);
- Assert.IsNotNull(js[name]);
- Assert.IsNotNull(js.GetFunction(name));
- }
-
- [Test()]
- public void TestCanListFunctions(){
- string name = "flist";
- AddFunction(name);
- List list = js.GetFunctionNames();
- Assert.IsTrue(list.Count > 0);
-
- bool found = false;
- foreach(string l in list){
- if(l == name) found = true;
- }
- Assert.IsTrue(found, "Didn't find the function that was inserted.");
- }
-
- [Test()]
- public void TestCanAddAFunctionStrStr(){
- string name = "faddss";
- string func = "function(x, y){return x + y;}";
- js.Add(name,func);
- Assert.IsNotNull(js[name]);
- }
-
- [Test()]
- public void TestCanAddAFunctionStrCode(){
- string name = "faddsc";
- Code func = new Code("function(x, y){return x + y;}");
- js.Add(name,func);
- Assert.IsNotNull(js[name]);
- }
-
- [Test()]
- public void TestCanAddAFunctionDoc(){
- string name = "fadddoc";
- Code func = new Code("function(x, y){return x + y;}");
- Document doc = new Document().Append("_id", name).Append("value", func);
- js.Add(doc);
- Assert.IsNotNull(js[name]);
- }
-
- [Test]
- public void TestCannotAddAFunctionTwice(){
- string name = "faddtwice";
- Code func = new Code("function(x,y){return x + y;}");
- js.Add(name, func);
- bool thrown = false;
- try{
- js.Add(name, func);
- }catch(ArgumentException){
- thrown = true;
- }
- Assert.IsTrue(thrown, "Shouldn't be able to add a function twice");
- }
-
- [Test]
- public void TestCanAddFunctionByAssignment(){
- string name = "fassignadd";
- Code func = new Code("function(x,y){return x + y;}");
- Document doc = new Document().Append("_id", name).Append("value", func);
- js[name] = doc;
- Assert.IsNotNull(js[name]);
- }
-
- [Test]
- public void TestContains(){
- string name = "fcontains";
- AddFunction(name);
- Assert.IsTrue(js.Contains(name));
- Assert.IsFalse(js.Contains("none"));
- Assert.IsTrue(js.Contains(new Document().Append("_id", name).Append("value", new Code("dfs"))));
- }
-
- [Test]
- public void TestCopyTo(){
- int cnt = 5;
- Document[] funcs = new Document[cnt];
- Code func = new Code("function(x,y){return x +y;}");
-
- for(int i = 0; i < cnt; i++){
- string name = "_" + i + "fcopyTo";
- Document doc = new Document().Append("_id", name).Append("value", func);
- js[name] = doc;
- }
-
- js.CopyTo(funcs, 1);
- Assert.IsNull(funcs[0]);
- Assert.IsNotNull(funcs[1]);
- Assert.IsNotNull(funcs[4]);
- Assert.IsTrue(((string)funcs[1]["_id"]).StartsWith("_1")); //as long as no other _ named functions get in.
- }
-
- [Test]
- public void TestRemoveByName(){
- String name = "fremoven";
- AddFunction(name);
- Assert.IsTrue(js.Contains(name));
- js.Remove(name);
- Assert.IsFalse(js.Contains(name));
- }
-
- [Test]
- public void TestRemoveByDoc(){
- String name = "fremoved";
- Document func = new Document().Append("_id", name);
- AddFunction(name);
- Assert.IsTrue(js.Contains(name));
- js.Remove(func);
- Assert.IsFalse(js.Contains(name));
- }
-
- [Test]
- public void TestForEach(){
- string name = "foreach";
- AddFunction(name);
- bool found = false;
- foreach(Document doc in js){
- if(name.Equals(doc["_id"]))found = true;
- }
- Assert.IsTrue(found, "Added function wasn't found during foreach");
- }
-
- [Test]
- public void TestClear(){
- AddFunction("clear");
- Assert.IsTrue(js.Count > 0);
- js.Clear();
- Assert.IsTrue(js.Count == 0);
- }
-
- [Test]
- public void TestExec(){
- js.Add("lt4", new Code("function(doc){return doc.j < 4;}"));
- int cnt = 0;
- foreach(Document doc in DB["reads"].Find("lt4(this)").Documents){
- cnt++;
- }
- Assert.AreEqual(3,cnt);
- }
-
- [Test]
- public void TestExecWithScope(){
- js.Add("lt", new Code("function(doc){ return doc.j < limit;}"));
- int cnt = 0;
- Document scope = new Document().Append("limit", 5);
- Document query = new Document().Append("$where", new CodeWScope("lt(this)",scope));
- foreach(Document doc in DB["jsreads"].Find(query).Documents){
- cnt++;
- }
- Assert.AreEqual(4,cnt);
- }
-
- protected void AddFunction(string name){
- Code func = new Code("function(x,y){return x + y;}");
- DB["system.js"].Insert(new Document().Append("_id", name).Append("value", func));
- }
- }
-}
diff --git a/MongoDB.Net-Tests/TestDocument.cs b/MongoDB.Net-Tests/TestDocument.cs
deleted file mode 100644
index 75a4ec00..00000000
--- a/MongoDB.Net-Tests/TestDocument.cs
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * User: scorder
- * Date: 7/8/2009
- */
-
-using System;
-using System.Collections;
-
-using NUnit.Framework;
-
-using MongoDB.Driver;
-
-namespace MongoDB.Driver
-{
- [TestFixture]
- public class TestDocument
- {
- [Test]
- public void TestValuesAdded()
- {
- Document d = new Document();
- d["test"] = 1;
- Assert.AreEqual(1, d["test"]);
- }
-
- [Test]
- public void TestKeyOrderIsPreserved(){
- Document d = new Document();
- d["one"] = 1;
- d.Add("two", 2);
- d["three"] = 3;
- int cnt = 1;
- foreach(String key in d.Keys){
- Assert.AreEqual(cnt, d[key]);
- cnt++;
- }
- }
- [Test]
- public void TestRemove(){
- Document d = new Document();
- d["one"] = 1;
- d.Remove("one");
- Assert.IsFalse(d.Contains("one"));
- }
-
- [Test]
- public void TestKeyOrderPreservedOnRemove(){
- Document d = new Document();
- d["one"] = 1;
- d["onepointfive"] = 1.5;
- d.Add("two", 2);
- d.Add("two.5", 2.5);
- d.Remove("two.5");
- d["three"] = 3;
- d.Remove("onepointfive");
- int cnt = 1;
- foreach(String key in d.Keys){
- Assert.AreEqual(cnt, d[key]);
- cnt++;
- }
- }
-
- [Test]
- public void TestValues(){
- Document d = new Document();
- d["one"] = 1;
- d.Add("two", 2);
- d["three"] = 3;
- ICollection vals = d.Values;
- Assert.AreEqual(3, vals.Count);
-
- }
-
- [Test]
- public void TestClearRemovesAll(){
- Document d = new Document();
- d["one"] = 1;
- d.Add("two", 2);
- d["three"] = 3;
- Assert.AreEqual(3,d.Count);
- d.Clear();
- Assert.AreEqual(0, d.Count);
- Assert.IsNull(d["one"]);
- Assert.IsFalse(d.Contains("one"));
- }
-
- [Test]
- public void TestCopyToCopiesAndPreservesKeyOrderToEmptyDoc(){
- Document d = new Document();
- Document dest = new Document();
- d["one"] = 1;
- d.Add("two", 2);
- d["three"] = 3;
- d.CopyTo(dest);
- int cnt = 1;
- foreach(String key in dest.Keys){
- Assert.AreEqual(cnt, d[key]);
- cnt++;
- }
- }
-
- [Test]
- public void TestCopyToCopiesAndOverwritesKeys(){
- Document d = new Document();
- Document dest = new Document();
- dest["two"] = 200;
- d["one"] = 1;
- d.Add("two", 2);
- d["three"] = 3;
- d.CopyTo(dest);
- Assert.AreEqual(2, dest["two"]);
- }
-
- [Test]
- public void TestTwoDocumentsWithSameContentInSameOrderAreEqual() {
- Document d1 = new Document().Append("k1", "v1").Append("k2", "v2");
- Document d2 = new Document().Append("k1", "v1").Append("k2", "v2");
- AreEqual(d1, d2);
- }
-
- [Test]
- public void TestTwoDocumentsWithSameContentInDifferentOrderAreNotEqual() {
- Document d1 = new Document().Append("k1", "v1").Append("k2", "v2");
- Document d2 = new Document().Append("k2", "v2").Append("k1", "v1");
- AreNotEqual(d1, d2);
- }
-
- [Test]
- public void TestTwoDocumentsWithSameArrayContentAreEqual() {
- Document d1 = new Document().Append("k1", new string[] { "v1", "v2" });
- Document d2 = new Document().Append("k1", new string[] { "v1", "v2" });
- AreEqual(d1, d2);
- }
-
- [Test]
- public void TestTwoDocumentsWithMisorderedArrayContentAreNotEqual() {
- Document d1 = new Document().Append("k1", new string[] { "v1", "v2" });
- Document d2 = new Document().Append("k1", new string[] { "v2", "v1" });
- AreNotEqual(d1, d2);
- }
-
- [Test]
- public void TestTwoDocumentsWithSameDocumentChildTreeAreEqual() {
- Document d1 = new Document().Append("k1", new Document().Append("k2",new Document().Append("k3","foo")));
- Document d2 = new Document().Append("k1", new Document().Append("k2", new Document().Append("k3", "foo")));
- AreEqual(d1, d2);
- }
-
- [Test]
- public void TestTwoDocumentsWithDifferentDocumentChildTreeAreNotEqual() {
- Document d1 = new Document().Append("k1", new Document().Append("k2", new Document().Append("k3", "foo")));
- Document d2 = new Document().Append("k1", new Document().Append("k2", new Document().Append("k3", "bar")));
- AreNotEqual(d1, d2);
- }
-
- private void AreEqual(Document d1, Document d2) {
- if (!d1.Equals(d2)) {
- Assert.Fail(string.Format("Documents don't match\r\nExpected: {0}\r\nActual: {1}", d1, d2));
- }
- }
-
- private void AreNotEqual(Document d1, Document d2) {
- if (d1.Equals(d2)) {
- Assert.Fail(string.Format("Documents match\r\nExpected: not {0}\r\nActual: {1}", d1, d2));
- }
- }
- }
-}
diff --git a/MongoDB.Net-Tests/TestMapReduce.cs b/MongoDB.Net-Tests/TestMapReduce.cs
deleted file mode 100644
index 0145fa03..00000000
--- a/MongoDB.Net-Tests/TestMapReduce.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-
-using System;
-using NUnit.Framework;
-
-namespace MongoDB.Driver
-{
- [TestFixture()]
- public class TestMapReduce : MongoTestBase
- {
- IMongoCollection mrcol;
- string mapfunction = "function(){\n" +
- " this.tags.forEach(\n" +
- " function(z){\n" +
- " emit( z , { count : 1 } );\n" +
- " });\n" +
- "};";
- string reducefunction = "function( key , values ){\n" +
- " var total = 0;\n" +
- " for ( var i=0; i lower);
- }
-
- [Test]
- public void TestOidFromBytes(){
- byte[] bytes = new byte[]{1,2,3,4,5,6,7,8,9,10,11,12};
- string hex = "0102030405060708090a0b0c";
-
- Oid bval = new Oid(bytes);
- Oid sval = new Oid(hex);
- Assert.AreEqual(bval, sval);
- }
-
- [Test]
- public void TestNullValue(){
- bool thrown = false;
- try{
- new Oid(String.Empty);
- }catch(Exception){
- thrown = true;
- }
- Assert.IsTrue(thrown,"Null value exception not thrown");
- }
-
- [Test]
- public void TestCtor(){
- bool thrown = false;
- try{
- new Oid("4a7067c30a57000000008ecb");
- }catch(ArgumentException){
- thrown = true;
- }
- Assert.IsFalse(thrown,"ID should be fine.");
- }
-
- [Test]
- public void TestDecode(){
- string hex = "4a7067c30a57000000008ecb";
- Oid oid = new Oid(hex);
-
- Assert.AreEqual("\"" + hex + "\"", oid.ToString());
- }
-
- [Test]
- public void TestEquals(){
- string hex = "4a7067c30a57000000008ecb";
- Assert.AreEqual(new Oid(hex), new Oid(hex));
-
- }
- [Test]
- public void TestNotEquals(){
- string hex = "4a7067c30a57000000008ecb";
- string hex2 = "4a7067c30a57000000008ecc";
- Assert.AreNotEqual(new Oid(hex), new Oid(hex2));
-
- }
-
- [Test]
- public void TestDate(){
- string hex = "4B458B95D114BE541B000000";
- Oid oid = new Oid(hex);
- //Expected: 2010-01-07 02:24:56.633
- DateTime expected = new DateTime(2010,1,7,7,21,57,DateTimeKind.Utc);
- Assert.AreEqual(expected,oid.Created);
- }
-
- [Test]
- public void TestToByteArray(){
- byte[] bytes = new byte[]{1,2,3,4,5,6,7,8,9,10,11,12};
- string hex = "0102030405060708090a0b0c";
-
- Oid bval = new Oid(bytes);
- byte[] bytes2 = bval.ToByteArray();
-
- Assert.IsNotNull(bytes2);
- Assert.AreEqual(12, bytes2.Length);
- Assert.AreEqual(bytes, bytes2);
- }
-
- [Test]
- public void TestNewOidFromToString(){
- var hex = "4B458B95D114BE541B000000";
- var firstOid = new Oid(hex);
- var secondOid = new Oid(firstOid.ToString());
-
- Assert.AreEqual(firstOid.ToString(), secondOid.ToString());
- }
- }
-}
diff --git a/MongoDBDriver/.gitignore b/MongoDBDriver/.gitignore
deleted file mode 100644
index 4d42fe72..00000000
--- a/MongoDBDriver/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-obj/*
-*.xml
-*.dll
-*.mdb
-*.pidb
-*.csproj
diff --git a/MongoDBDriver/Binary.cs b/MongoDBDriver/Binary.cs
deleted file mode 100644
index 927906f5..00000000
--- a/MongoDBDriver/Binary.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-using System;
-
-namespace MongoDB.Driver
-{
- public class Binary{
- public enum TypeCode:byte{
- Unknown = 0,
- General = 2,
- // Uuid is now replaced by Guid
- //Uuid = 3,
- Md5 = 5,
- UserDefined = 80
- }
-
- public byte[] Bytes{get;set;}
-
- public TypeCode Subtype{get;set;}
-
- public Binary() { }
-
- public Binary(byte[] value){
- Bytes = value;
- Subtype = TypeCode.General;
- }
-
- public override string ToString (){
- return String.Format(@"{{ ""$binary"": ""{0}"", ""$type"" : {1} }}",
- Convert.ToBase64String(Bytes), (int)Subtype);
- }
- }
-}
diff --git a/MongoDBDriver/Bson/BsonReader.cs b/MongoDBDriver/Bson/BsonReader.cs
deleted file mode 100644
index 0b09bb07..00000000
--- a/MongoDBDriver/Bson/BsonReader.cs
+++ /dev/null
@@ -1,330 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.IO;
-using System.Reflection;
-using System.Text;
-
-namespace MongoDB.Driver.Bson
-{
- ///
- /// Reads binary streams containing BSON data and converts them to native types.
- ///
- public class BsonReader
- {
- private Stream stream;
- private BinaryReader reader;
- private int position = 0;
-
- private byte[] _byteBuffer;
- private char[] _charBuffer;
-
- private const int MaxCharBytesSize = 128;
-
- private byte[] seqRange1 = new byte[]{0,127}; //Range of 1-byte sequence
- private byte[] seqRange2 = new byte[]{194,223};//Range of 2-byte sequence
- private byte[] seqRange3 = new byte[]{224,239};//Range of 3-byte sequence
- private byte[] seqRange4 = new byte[]{240,244};//Range of 4-byte sequence
-
- public BsonReader (Stream stream)
- {
- this.stream = stream;
- reader = new BinaryReader (this.stream);
- }
-
- public int Position {
- get { return position; }
- }
-
- public Document Read ()
- {
- position = 0;
- Document doc = ReadDocument();
- return doc;
- }
-
- public Document ReadDocument(){
- int startpos = position;
- Document doc = new Document ();
- int size = reader.ReadInt32 ();
- position += 4;
- while ((position - startpos) + 1 < size) {
- ReadElement (doc);
- }
- byte eoo = reader.ReadByte ();
- position++;
- if (eoo != 0)
- throw new InvalidDataException ("Document not null terminated");
- if (size != position - startpos) {
- throw new InvalidDataException (string.Format ("Should have read {0} bytes from stream but only read {1}", size, (position - startpos)));
- }
- return doc;
- }
-
- public void ReadElement (Document doc){
- sbyte typeNum = (sbyte)reader.ReadByte ();
- position++;
- String key = ReadString ();
- Object element = ReadElementType(typeNum);
- doc.Add (key, element);
- }
-
- public Object ReadElementType (sbyte typeNum){
- switch ((BsonDataType)typeNum) {
- case BsonDataType.Null:
- case BsonDataType.Undefined:
- return DBNull.Value;
- case BsonDataType.MinKey:
- return MongoMinKey.Value;
- case BsonDataType.MaxKey:
- return MongoMaxKey.Value;
- case BsonDataType.Boolean:
- position++;
- return reader.ReadBoolean ();
- case BsonDataType.Integer:
- position += 4;
- return reader.ReadInt32 ();
- case BsonDataType.Long:
- position += 8;
- return reader.ReadInt64 ();
- case BsonDataType.Date:
- position += 8;
- long millis = reader.ReadInt64 ();
- return BsonInfo.Epoch.AddMilliseconds(millis);
- case BsonDataType.Oid:
- position += 12;
- return new Oid (reader.ReadBytes (12));
- case BsonDataType.Number:
- position += 8;
- return reader.ReadDouble ();
- case BsonDataType.String:{
- return ReadLenString ();
- }
- case BsonDataType.Obj:{
- Document doc = this.ReadDocument();
- if(DBRef.IsDocumentDBRef(doc)){
- return DBRef.FromDocument(doc);
- }
- return doc;
- }
-
- case BsonDataType.Array:{
- Document doc = this.ReadDocument();
- return ConvertToArray (doc);
- }
- case BsonDataType.Regex:{
- MongoRegex r = new MongoRegex ();
- r.Expression = this.ReadString ();
- r.Options = this.ReadString ();
- return r;
- }
- case BsonDataType.Code:{
- Code c = new Code ();
- c.Value = ReadLenString();
- return c;
- }
- case BsonDataType.CodeWScope:{
- int startpos = position;
- int size = reader.ReadInt32 ();
- position += 4;
-
- String val = this.ReadLenString();
- Document scope = this.ReadDocument();
- if (size != position - startpos) {
- throw new System.IO.InvalidDataException (string.Format ("Should have read {0} bytes from stream but read {1} in CodeWScope", size, position - startpos));
- }
- return new CodeWScope (val, scope);
- }
- case BsonDataType.Binary:{
- int size = reader.ReadInt32 ();
- position += 4;
- byte subtype = reader.ReadByte ();
- position ++;
- if (subtype == (byte)Binary.TypeCode.General) {
- size = reader.ReadInt32 ();
- position += 4;
- }
- byte[] bytes = reader.ReadBytes (size);
- position += size;
-
- // From http://en.wikipedia.org/wiki/Universally_Unique_Identifier
- // The most widespread use of this standard is in Microsoft's Globally Unique Identifiers (GUIDs).
- if (subtype == 3 && 16 == size)
- {
- return new Guid(bytes);
- }
-
- Binary b = new Binary();
- b.Bytes = bytes;
- b.Subtype = (Binary.TypeCode)subtype;
- return b;
- }
- default:
- throw new ArgumentOutOfRangeException (String.Format ("Type Number: {0} not recognized", typeNum));
- }
- }
-
- public string ReadString (){
- EnsureBuffers ();
-
- StringBuilder builder = new StringBuilder();
- int totalBytesRead = 0;
- int offset = 0;
- do {
- int byteCount = 0;
- int count = offset;
- byte b = 0;;
- while (count < MaxCharBytesSize && (b = reader.ReadByte ()) > 0) {
- _byteBuffer[count++] = b;
- }
- byteCount = count - offset;
- totalBytesRead += byteCount;
- position += byteCount;
-
- if(count == 0) break; //first byte read was the terminator.
- int lastFullCharStop = GetLastFullCharStop(count - 1);
-
- int charCount = Encoding.UTF8.GetChars (_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
- builder.Append (_charBuffer, 0, charCount);
-
- if(lastFullCharStop < byteCount - 1){
- offset = byteCount - lastFullCharStop - 1;
- //Copy end bytes to begining
- Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
- }else{
- offset = 0;
- }
-
- if(b == 0){
- break;
- }
- } while (true);
- position++;
- return builder.ToString();
-
- }
-
- public string ReadLenString (){
- int length = reader.ReadInt32 ();
- string s = GetString (length - 1);
- reader.ReadByte ();
-
- position += (4 + 1);
- return s;
- }
-
- private string GetString (int length){
- if (length == 0)
- return string.Empty;
-
- EnsureBuffers ();
-
- StringBuilder builder = new StringBuilder (length);;
-
- int totalBytesRead = 0;
- int offset = 0;
- do {
- int byteCount = 0;
- int count = ((length - totalBytesRead) > MaxCharBytesSize - offset) ? (MaxCharBytesSize - offset) :
- (length - totalBytesRead);
-
- byteCount = reader.BaseStream.Read (_byteBuffer, offset, count);
- totalBytesRead += byteCount;
- byteCount += offset;
-
- int lastFullCharStop = 0;
- lastFullCharStop = GetLastFullCharStop(byteCount - 1);
-
- if (byteCount == 0)
- throw new EndOfStreamException ("Unable to read beyond the end of the stream.");
-
- int charCount = Encoding.UTF8.GetChars (_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
- builder.Append (_charBuffer, 0, charCount);
-
- if(lastFullCharStop < byteCount - 1){
- offset = byteCount - lastFullCharStop - 1;
- //Copy end bytes to begining
- Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
- }else{
- offset = 0;
- }
-
- } while (totalBytesRead < length);
-
- position += totalBytesRead;
- return builder.ToString ();
- }
-
- private int GetLastFullCharStop(int start){
- int lookbackPos = start;
- int bis = 0;
- while(lookbackPos >= 0){
- bis = BytesInSequence(_byteBuffer[lookbackPos]);
- if(bis == 0){
- lookbackPos--;
- continue;
- }else if(bis == 1){
- break;
- }else{
- lookbackPos--;
- break;
- }
- }
- if(bis == start - lookbackPos){
- //Full character.
- return start;
- }else{
- return lookbackPos;
- }
- }
-
- private int BytesInSequence(byte b){
- if(b <= seqRange1[1]) return 1;
- if(b >= seqRange2[0] && b <= seqRange2[1]) return 2;
- if(b >= seqRange3[0] && b <= seqRange3[1]) return 3;
- if(b >= seqRange4[0] && b <= seqRange4[1]) return 4;
- return 0;
- }
-
- private void EnsureBuffers (){
- if (_byteBuffer == null) {
- _byteBuffer = new byte[MaxCharBytesSize];
- }
- if (_charBuffer == null) {
- int charBufferSize = Encoding.UTF8.GetMaxCharCount (MaxCharBytesSize);
- _charBuffer = new char[charBufferSize];
- }
- }
-
- private Type GetTypeForIEnumerable (Document doc){
- if (doc.Keys.Count < 1)
- return typeof(Object);
- Type comp = null;
- foreach (String key in doc.Keys) {
- Object obj = doc[key];
- Type test = obj.GetType ();
- if (comp == null) {
- comp = test;
- } else {
- if (comp != test)
- return typeof(Object);
- }
- }
- return comp;
- }
-
- private IEnumerable ConvertToArray (Document doc){
- var genericListType = typeof(List<>);
- var arrayType = GetTypeForIEnumerable(doc);
- var listType = genericListType.MakeGenericType(arrayType);
-
- var list = (IList)Activator.CreateInstance(listType);
-
- foreach (String key in doc.Keys) {
- list.Add(doc[key]);
- }
-
- return list;
- }
- }
-}
diff --git a/MongoDBDriver/Bson/BsonWriter.cs b/MongoDBDriver/Bson/BsonWriter.cs
deleted file mode 100644
index e4eaf8a1..00000000
--- a/MongoDBDriver/Bson/BsonWriter.cs
+++ /dev/null
@@ -1,319 +0,0 @@
-using System;
-using System.Collections;
-using System.IO;
-using System.Text;
-
-namespace MongoDB.Driver.Bson
-{
- ///
- /// Class that knows how to format a native object into bson bits.
- ///
- public class BsonWriter
- {
- private Stream stream;
- private BinaryWriter writer;
- private Encoding encoding = Encoding.UTF8;
- private int buffLength = 256;
- private byte[] buffer;
- int maxChars;
-
- public BsonWriter(Stream stream){
- this.stream = stream;
- writer = new BinaryWriter(this.stream);
- buffer = new byte[buffLength];
- maxChars = buffLength / encoding.GetMaxByteCount(1);
- }
-
- public void Write(Document doc){
- int size = CalculateSize(doc);
- if(size >= BsonInfo.MaxDocumentSize) throw new ArgumentException("Maximum document size exceeded.");
- writer.Write(size);
- foreach(String key in doc.Keys){
- Object val = doc[key];
- BsonDataType t = TranslateToBsonType(val);
- writer.Write((byte)t);
- this.WriteString(key);
- this.WriteValue(t,val);
- }
- writer.Write((byte)0);
- }
-
- public void WriteArray(IEnumerable arr){
- int size = CalculateSize(arr);
- writer.Write(size);
- int keyname = 0;
- foreach(Object val in arr){
- BsonDataType t = TranslateToBsonType(val);
- writer.Write((byte)t);
- this.WriteString(keyname.ToString());
- this.WriteValue(t,val);
- keyname++;
- }
- writer.Write((byte)0);
- }
-
- public void WriteValue(BsonDataType dt, Object obj){
- switch (dt){
- case BsonDataType.MinKey:
- case BsonDataType.MaxKey:
- case BsonDataType.Null:
- return;
- case BsonDataType.Boolean:
- writer.Write((bool)obj);
- return;
- case BsonDataType.Integer:
- writer.Write((int)obj);
- return;
- case BsonDataType.Long:
- writer.Write((long)obj);
- return;
- case BsonDataType.Date:
- DateTime d = (DateTime)obj;
- TimeSpan diff = d.ToUniversalTime() - BsonInfo.Epoch;
- double time = Math.Floor(diff.TotalMilliseconds);
- writer.Write((long)time);
- return;
- case BsonDataType.Oid:
- Oid id = (Oid) obj;
- writer.Write(id.ToByteArray());
- return;
- case BsonDataType.Number:
- writer.Write((double)obj);
- return;
- case BsonDataType.String:{
- String str = (String)obj;
- writer.Write(CalculateSize(str,false));
- this.WriteString(str);
- return;
- }
- case BsonDataType.Obj:
- if(obj is Document){
- this.Write((Document)obj);
- }else if(obj is DBRef){
- this.Write((Document)((DBRef)obj));
- }
- return;
- case BsonDataType.Array:
- this.WriteArray((IEnumerable)obj);
- return;
- case BsonDataType.Regex:{
- MongoRegex r = (MongoRegex)obj;
- this.WriteString(r.Expression);
- this.WriteString(r.Options);
- return;
- }
- case BsonDataType.Code:{
- Code c = (Code)obj;
- this.WriteValue(BsonDataType.String,c.Value);
- return;
- }
- case BsonDataType.CodeWScope:{
- CodeWScope cw = (CodeWScope)obj;
- writer.Write(CalculateSize(cw));
- this.WriteValue(BsonDataType.String,cw.Value);
- this.WriteValue(BsonDataType.Obj,cw.Scope);
- return;
- }
- case BsonDataType.Binary:{
- if (obj is Guid) {
- writer.Write((int)16);
- writer.Write((byte)3);
- writer.Write(((Guid)obj).ToByteArray());
- } else {
- Binary b = (Binary)obj;
- if(b.Subtype == Binary.TypeCode.General){
- writer.Write(b.Bytes.Length + 4);
- writer.Write((byte)b.Subtype);
- writer.Write(b.Bytes.Length);
- }else{
- writer.Write(b.Bytes.Length);
- writer.Write((byte)b.Subtype);
- }
- writer.Write(b.Bytes);
- }
- return;
- }
- default:
- throw new NotImplementedException(String.Format("Writing {0} types not implemented.",obj.GetType().Name));
- }
- }
-
- public void WriteString(String str){
- int byteCount = encoding.GetByteCount(str);
- if(byteCount < buffLength){
- encoding.GetBytes(str,0,str.Length,buffer,0);
- writer.Write(buffer,0,byteCount);
- }else{
- int charCount;
- int totalCharsWritten = 0;
-
- for (int i = str.Length; i > 0; i -= charCount){
- charCount = (i > maxChars) ? maxChars : i;
- int count = encoding.GetBytes(str, totalCharsWritten, charCount, buffer, 0);
- writer.Write(buffer, 0, count);
- totalCharsWritten += charCount;
- }
- }
- writer.Write((byte)0);
- }
-
- public int CalculateSize(Object val){
- if(val == null) return 0;
- switch (TranslateToBsonType(val)){
- case BsonDataType.MinKey:
- case BsonDataType.MaxKey:
- case BsonDataType.Null:
- return 0;
- case BsonDataType.Boolean:
- return 1;
- case BsonDataType.Integer:
- return 4;
- case BsonDataType.Long:
- case BsonDataType.Date:
- return 8;
- case BsonDataType.Oid:
- return 12;
- case BsonDataType.Number:
- return sizeof(Double);
- case BsonDataType.String:
- return CalculateSize((string)val);
- case BsonDataType.Obj:{
- Type t = val.GetType();
- if(t == typeof(Document)){
- return CalculateSize((Document)val);
- }
- if(t == typeof(DBRef)){
- return CalculateSize((Document)((DBRef)val));
- }
- throw new NotImplementedException(String.Format("Calculating size of {0} is not implemented yet.",t.Name));
- }
- case BsonDataType.Array:
- return CalculateSize((IEnumerable)val);
- case BsonDataType.Regex:{
- MongoRegex r = (MongoRegex)val;
- int size = CalculateSize(r.Expression,false);
- size += CalculateSize(r.Options,false);
- return size;
- }
- case BsonDataType.Code:
- Code c = (Code)val;
- return CalculateSize(c.Value,true);
- case BsonDataType.CodeWScope:{
- CodeWScope cw = (CodeWScope)val;
- int size = 4;
- size += CalculateSize(cw.Value,true);
- size += CalculateSize(cw.Scope);
- return size;
- }
- case BsonDataType.Binary:{
- if (val is Guid)
- return 21;
- Binary b = (Binary)val;
- int size = 4; //size int
- size += 1; //subtype
- if (b.Subtype == Binary.TypeCode.General)
- {
- size += 4; //embedded size int
- }
- size += b.Bytes.Length;
- return size;
- }
- default:
- throw new NotImplementedException(String.Format("Calculating size of {0} is not implemented.",val.GetType().Name));
- }
- }
-
- public int CalculateSize(Document doc){
- int size = 4;
- foreach(String key in doc.Keys){
- int elsize = 1; //type
- elsize += CalculateSize(key,false);
- elsize += CalculateSize(doc[key]);
- size += elsize;
- }
- size += 1; //terminator
- return size;
- }
-
- public int CalculateSize(IEnumerable arr){
- int size = 4;//base size for the object
- int keyname = 0;
- foreach(Object o in arr){
- int elsize = 1; //type
- size += CalculateSize(keyname.ToString(),false); //element name
- size += CalculateSize(o);
- size += elsize;
- keyname++;
- }
- size += 1; //terminator
- return size;
- }
-
- public int CalculateSize(String val){
- return CalculateSize(val, true);
- }
-
- public int CalculateSize(String val, bool includeLen){
- int size = 1; //terminator
- if(includeLen) size += 4;
- if(val != null) size += encoding.GetByteCount(val);
- return size;
- }
-
- public void Flush(){
- writer.Flush();
- }
-
- protected BsonDataType TranslateToBsonType(Object val){
- if(val == null)return BsonDataType.Null;
- Type t = val.GetType();
- //special case enums
- if(val is Enum){
- t = Enum.GetUnderlyingType(t);
- }
- BsonDataType ret;
- if(t == typeof(Double)){
- ret = BsonDataType.Number;
- }else if(t == typeof(Single)){
- ret = BsonDataType.Number;
- }else if(t == typeof(String)){
- ret = BsonDataType.String;
- }else if(t == typeof(Document)){
- ret = BsonDataType.Obj;
- }else if(t == typeof(int)){
- ret = BsonDataType.Integer;
- }else if(t == typeof(long)){
- ret = BsonDataType.Long;
- }else if(t == typeof(bool)){
- ret = BsonDataType.Boolean;
- }else if(t == typeof(Oid)){
- ret = BsonDataType.Oid;
- }else if(t == typeof(DateTime)){
- ret = BsonDataType.Date;
- }else if(t == typeof(MongoRegex)){
- ret = BsonDataType.Regex;
- }else if(t == typeof(DBRef)){
- ret = BsonDataType.Obj;
- }else if(t == typeof(Code)){
- ret = BsonDataType.Code;
- }else if(t == typeof(CodeWScope)){
- ret = BsonDataType.CodeWScope;
- }else if(t == typeof(DBNull)){
- ret = BsonDataType.Null;
- }else if(t == typeof(Binary)){
- ret = BsonDataType.Binary;
- }else if(t == typeof(Guid)){
- ret = BsonDataType.Binary;
- }else if(t == typeof(MongoMinKey)){
- ret = BsonDataType.MinKey;
- }else if(t == typeof(MongoMaxKey)){
- ret = BsonDataType.MaxKey;
- }else if(val is IEnumerable){
- ret = BsonDataType.Array;
- }else{
- throw new ArgumentOutOfRangeException(String.Format("Type: {0} not recognized",t.FullName));
- }
- return ret;
- }
- }
-}
diff --git a/MongoDBDriver/Code.cs b/MongoDBDriver/Code.cs
deleted file mode 100644
index 52378708..00000000
--- a/MongoDBDriver/Code.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-namespace MongoDB.Driver
-{
- public class Code
- {
- public string Value {get; set;}
-
- public Code(){}
-
- public Code(string value){
- this.Value = value;
- }
-
- public override string ToString() {
- return string.Format(@"{{ ""$code"": ""{0}"" }}", JsonFormatter.Escape(Value));
- }
- }
-}
diff --git a/MongoDBDriver/CodeWScope.cs b/MongoDBDriver/CodeWScope.cs
deleted file mode 100644
index 15409ed4..00000000
--- a/MongoDBDriver/CodeWScope.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-using System;
-
-namespace MongoDB.Driver
-{
- public class CodeWScope : Code
- {
- public Document Scope {get;set;}
-
- public CodeWScope(){}
-
- public CodeWScope(String code):this(code, new Document()){}
-
- public CodeWScope(String code, Document scope){
- this.Value = code;
- this.Scope = scope;
- }
- }
-}
diff --git a/MongoDBDriver/Collection.cs b/MongoDBDriver/Collection.cs
deleted file mode 100644
index a753f9a0..00000000
--- a/MongoDBDriver/Collection.cs
+++ /dev/null
@@ -1,336 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using MongoDB.Driver.Connections;
-using MongoDB.Driver.Protocol;
-
-namespace MongoDB.Driver
-{
- public class Collection : IMongoCollection
- {
- private Connection connection;
-
- private string name;
- public string Name {
- get { return name; }
- }
-
- private string dbName;
- public string DbName {
- get { return dbName; }
- }
-
- public string FullName{
- get{ return dbName + "." + name;}
- }
-
- private CollectionMetaData metaData;
- public CollectionMetaData MetaData {
- get {
- if(metaData == null){
- metaData = new CollectionMetaData(this.dbName,this.name, this.connection);
- }
- return metaData;
- }
- }
-
- private Database db;
- private Database Db{
- get{
- if(db == null)
- db = new Database(this.connection, this.dbName);
- return db;
- }
- }
- public Collection(string name, Connection conn, string dbName)
- {
- this.name = name;
- this.connection = conn;
- this.dbName = dbName;
- }
-
- ///
- /// Finds and returns the first document in a query.
- ///
- ///
- /// A representing the query.
- ///
- ///
- /// A from the collection.
- ///
- public Document FindOne(Document spec){
- ICursor cur = this.Find(spec, -1, 0, null);
- foreach(Document doc in cur.Documents){
- cur.Dispose();
- return doc;
- }
- //FIXME Decide if this should throw a not found exception instead of returning null.
- return null; //this.Find(spec, -1, 0, null)[0];
- }
-
- public ICursor FindAll() {
- Document spec = new Document();
- return this.Find(spec, 0, 0, null);
- }
-
- public ICursor Find(String where){
- Document spec = new Document();
- spec.Append("$where", new Code(where));
- return this.Find(spec, 0, 0, null);
- }
-
- public ICursor Find(Document spec) {
- return this.Find(spec, 0, 0, null);
- }
-
- public ICursor Find(Document spec, int limit, int skip) {
- return this.Find(spec, limit, skip, null);
- }
-
- public ICursor Find(Document spec, int limit, int skip, Document fields) {
- if(spec == null) spec = new Document();
- Cursor cur = new Cursor(connection, this.FullName, spec, limit, skip, fields);
- return cur;
- }
-
- ///
- /// Entrypoint into executing a map/reduce query against the collection.
- ///
- ///
- /// A
- ///
- public MapReduce MapReduce(){
- return new MapReduce(this.Db, this.Name);
- }
-
- public MapReduceBuilder MapReduceBuilder(){
- return new MapReduceBuilder(this.MapReduce());
- }
-
-
- ///
- ///Count all items in the collection.
- ///
- public long Count(){
- return this.Count(new Document());
- }
-
- ///
- /// Count all items in a collection that match the query spec.
- ///
- ///
- /// It will return 0 if the collection doesn't exist yet.
- ///
- public long Count(Document spec){
- try{
- //Database db = new Database(this.connection, this.dbName);
- Document ret = this.Db.SendCommand(new Document().Append("count",this.Name).Append("query",spec));
- double n = (double)ret["n"];
- return Convert.ToInt64(n);
- }catch(MongoCommandException){
- //FIXME This is an exception condition when the namespace is missing.
- //-1 might be better here but the console returns 0.
- return 0;
- }
-
- }
-
- ///
- /// Inserts the Document into the collection.
- ///
- public void Insert (Document doc, bool safemode){
- Insert(doc);
- CheckError(safemode);
- }
-
- public void Insert(Document doc){
- Document[] docs = new Document[]{doc,};
- this.Insert(docs);
- }
-
- public void Insert (IEnumerable docs, bool safemode){
- if(safemode)this.Db.ResetError();
- this.Insert(docs);
- CheckPreviousError(safemode);
- }
-
- public void Insert(IEnumerable docs){
- InsertMessage im = new InsertMessage();
- im.FullCollectionName = this.FullName;
- List idocs = new List();
- foreach(Document doc in docs){
- if(doc.Contains("_id") == false){
- Oid _id = Oid.NewOid();
- doc.Prepend("_id",_id);
- }
- }
- idocs.AddRange(docs);
- im.Documents = idocs.ToArray();
- try{
- this.connection.SendMessage(im);
- }catch(IOException ioe){
- throw new MongoCommException("Could not insert document, communication failure", this.connection,ioe);
- }
- }
-
- ///
- /// Deletes documents from the collection according to the spec.
- ///
- /// An empty document will match all documents in the collection and effectively truncate it.
- ///
- public void Delete (Document selector, bool safemode){
- Delete(selector);
- CheckError(safemode);
- }
-
- ///
- /// Deletes documents from the collection according to the spec.
- ///
- /// An empty document will match all documents in the collection and effectively truncate it.
- ///
- public void Delete(Document selector){
- DeleteMessage dm = new DeleteMessage();
- dm.FullCollectionName = this.FullName;
- dm.Selector = selector;
- try{
- this.connection.SendMessage(dm);
- }catch(IOException ioe){
- throw new MongoCommException("Could not delete document, communication failure", this.connection,ioe);
- }
- }
-
-
- public void Update (Document doc, bool safemode){
- Update(doc);
- CheckError(safemode);
- }
-
- ///
- /// Saves a document to the database using an upsert.
- ///
- ///
- /// The document will contain the _id that is saved to the database. This is really just an alias
- /// to Update(Document) to maintain consistency between drivers.
- ///
- public void Save(Document doc){
- Update(doc);
- }
-
- ///
- /// Updates a document with the data in doc as found by the selector.
- ///
- ///
- /// _id will be used in the document to create a selector. If it isn't in
- /// the document then it is assumed that the document is new and an upsert is sent to the database
- /// instead.
- ///
- public void Update(Document doc){
- //Try to generate a selector using _id for an existing document.
- //otherwise just set the upsert flag to 1 to insert and send onward.
- Document selector = new Document();
- int upsert = 0;
- if(doc.Contains("_id") & doc["_id"] != null){
- selector["_id"] = doc["_id"];
- }else{
- //Likely a new document
- doc.Prepend("_id",Oid.NewOid());
- upsert = 1;
- }
- this.Update(doc, selector, upsert);
- }
-
- public void Update (Document doc, Document selector, bool safemode){
- Update(doc, selector,0,safemode);
- }
-
- ///
- /// Updates a document with the data in doc as found by the selector.
- ///
- public void Update(Document doc, Document selector){
- this.Update(doc, selector, 0);
- }
-
- public void Update (Document doc, Document selector, UpdateFlags flags, bool safemode){
- Update(doc,selector,flags);
- CheckError(safemode);
- }
-
- ///
- /// Updates a document with the data in doc as found by the selector.
- ///
- /// The to update with
- ///
- ///
- /// The query spec to find the document to update.
- ///
- ///
- ///
- ///
- public void Update(Document doc, Document selector, UpdateFlags flags){
- UpdateMessage um = new UpdateMessage();
- um.FullCollectionName = this.FullName;
- um.Selector = selector;
- um.Document = doc;
- um.Flags = (int)flags;
- try{
- this.connection.SendMessage(um);
- }catch(IOException ioe){
- throw new MongoCommException("Could not update document, communication failure", this.connection,ioe);
- }
-
- }
-
- public void Update (Document doc, Document selector, int flags, bool safemode){
- Update(doc,selector,flags);
- CheckError(safemode);
- }
-
- public void Update(Document doc, Document selector, int flags){
- //TODO Update the interface and make a breaking change.
- this.Update(doc,selector,(UpdateFlags)flags);
- }
-
- ///
- /// Runs a multiple update query against the database. It will wrap any
- /// doc with $set if the passed in doc doesn't contain any '$' ops.
- ///
- ///
- ///
- public void UpdateAll(Document doc, Document selector){
- bool foundOp = false;
- foreach(string key in doc.Keys){
- if(key.IndexOf('$') == 0){
- foundOp = true;
- break;
- }
- }
- if(foundOp == false){
- //wrap document in a $set.
- Document s = new Document().Append("$set", doc);
- doc = s;
- }
- this.Update(doc, selector, UpdateFlags.MultiUpdate);
- }
-
-
- public void UpdateAll (Document doc, Document selector, bool safemode){
- if(safemode)this.Db.ResetError();
- this.UpdateAll(doc, selector);
- CheckPreviousError(safemode);
- }
-
-
- private void CheckError(bool safemode){
- if(safemode){
- Document err = this.Db.GetLastError();
- if(ErrorTranslator.IsError(err)) throw ErrorTranslator.Translate(err);
- }
- }
- private void CheckPreviousError(bool safemode){
- if(safemode){
- Document err = this.Db.GetPreviousError();
- if(ErrorTranslator.IsError(err)) throw ErrorTranslator.Translate(err);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/CollectionMetaData.cs b/MongoDBDriver/CollectionMetaData.cs
deleted file mode 100644
index bd72c5c5..00000000
--- a/MongoDBDriver/CollectionMetaData.cs
+++ /dev/null
@@ -1,107 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using MongoDB.Driver.Connections;
-
-namespace MongoDB.Driver
-{
- ///
- /// Lazily loaded meta data on the collection.
- ///
- public class CollectionMetaData
- {
- private string fullName;
- private string name;
- private Database db;
-
- public CollectionMetaData (string dbName, string name, Connection conn){
- this.fullName = dbName + "." + name;
- this.name = name;
- this.db = new Database (conn, dbName);
- }
-
- private Document options = null;
- public Document Options {
- get {
- if (options != null)
- return options;
- Document doc = db["system.namespaces"].FindOne (new Document ().Append ("name", this.fullName));
- if (doc == null)
- doc = new Document ();
- if (doc.Contains ("create"))
- doc.Remove ("create");
- //Not sure why this is here. The python driver has it.
- this.options = doc;
- return this.options;
- }
- }
-
- private bool gotIndexes = false;
- private Dictionary indexes = new Dictionary ();
- public Dictionary Indexes {
- get {
- if (gotIndexes)
- return indexes;
-
- indexes.Clear ();
-
- ICursor docs = db["system.indexes"].Find (new Document ().Append ("ns", this.fullName));
- foreach (Document doc in docs.Documents) {
- indexes.Add ((string)doc["name"], doc);
- }
-
- return indexes;
- }
- }
-
- public void CreateIndex (string name, Document fieldsAndDirections, bool unique){
- Document index = new Document ();
- index["name"] = name;
- index["ns"] = this.fullName;
- index["key"] = fieldsAndDirections;
- index["unique"] = unique;
- db["system.indexes"].Insert (index);
- this.refresh ();
- }
-
- public void CreateIndex (Document fieldsAndDirections, bool unique){
- string name = this.generateIndexName (fieldsAndDirections, unique);
- this.CreateIndex (name, fieldsAndDirections, unique);
- }
-
- public void DropIndex (string name){
- Document cmd = new Document ();
- cmd.Append ("deleteIndexes", this.name).Append ("index", name);
- db.SendCommand (cmd);
- this.refresh ();
- }
-
- public void Rename (string newName){
- if (string.IsNullOrEmpty (newName))
- throw new ArgumentException ("Name must not be null or empty", "newName");
-
- Document cmd = new Document ();
- cmd.Append ("renameCollection", fullName).Append ("to", db.Name + "." + newName);
- db.GetSisterDatabase ("admin").SendCommand (cmd);
- this.refresh ();
- }
-
- public void refresh (){
- indexes.Clear ();
- gotIndexes = false;
- options = null;
- }
-
- protected string generateIndexName (Document fieldsAndDirections, bool unique){
- StringBuilder sb = new StringBuilder ("_");
- foreach (string key in fieldsAndDirections.Keys) {
- sb.Append (key).Append ("_");
- }
- if (unique)
- sb.Append ("unique_");
-
- return sb.ToString ();
- }
-
- }
-}
diff --git a/MongoDBDriver/Configuration/ConnectionCollection.cs b/MongoDBDriver/Configuration/ConnectionCollection.cs
deleted file mode 100644
index da8419cd..00000000
--- a/MongoDBDriver/Configuration/ConnectionCollection.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-using System;
-using System.Configuration;
-
-namespace MongoDB.Driver.Configuration
-{
- public class ConnectionCollection : ConfigurationElementCollection
- {
-
- public override ConfigurationElementCollectionType CollectionType {
- get { return ConfigurationElementCollectionType.AddRemoveClearMap; }
- }
-
- protected override ConfigurationElement CreateNewElement ()
- {
- return new ConnectionElement ();
- }
-
- protected override Object GetElementKey (ConfigurationElement element)
- {
- return ((ConnectionElement)element).Name;
- }
-
- public ConnectionElement this[int index] {
- get { return (ConnectionElement)BaseGet (index); }
- set {
- if (BaseGet (index) != null) {
- BaseRemoveAt (index);
- }
- BaseAdd (index, value);
- }
- }
- public new ConnectionElement this[string Name] {
- get { return (ConnectionElement)BaseGet (Name); }
- }
-
- public int IndexOf (ConnectionElement conn)
- {
- return BaseIndexOf (conn);
- }
- public void Add (ConnectionElement conn)
- {
- BaseAdd (conn);
- }
- protected override void BaseAdd (ConfigurationElement element)
- {
- BaseAdd (element, false);
- }
-
- public void Remove (ConnectionElement conn)
- {
- if (BaseIndexOf (conn) >= 0)
- BaseRemove (conn.Name);
- }
-
- public void RemoveAt (int index)
- {
- BaseRemoveAt (index);
- }
-
- public void Remove (string name)
- {
- BaseRemove (name);
- }
-
- public void Clear ()
- {
- BaseClear ();
- }
- }
-}
diff --git a/MongoDBDriver/Configuration/ConnectionElement.cs b/MongoDBDriver/Configuration/ConnectionElement.cs
deleted file mode 100755
index 6821ec18..00000000
--- a/MongoDBDriver/Configuration/ConnectionElement.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System;
-using System.Configuration;
-
-namespace MongoDB.Driver.Configuration
-{
-
- public class ConnectionElement : ConfigurationElement
- {
- [ConfigurationProperty("key", IsRequired = true)]
- public string Name{
- get{return (String)this["key"];}
- set{this["key"] = value;}
- }
-
- [ConfigurationProperty("connectionString", DefaultValue = "Server=localhost:27017")]
- public string ConnectionString{
- get { return (String)this["connectionString"]; }
- set { this["connectionString"] = value; }
- }
- }
-}
diff --git a/MongoDBDriver/Configuration/MongoConfiguration.cs b/MongoDBDriver/Configuration/MongoConfiguration.cs
deleted file mode 100644
index ec60afad..00000000
--- a/MongoDBDriver/Configuration/MongoConfiguration.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System;
-using System.Configuration;
-
-namespace MongoDB.Driver.Configuration
-{
- public class MongoConfiguration : ConfigurationSection
- {
-
- public MongoConfiguration() { }
-
- [ConfigurationProperty("connections", IsDefaultCollection = false)]
- [ConfigurationCollection(typeof(ConnectionCollection),
- AddItemName = "add",
- ClearItemsName = "clear",
- RemoveItemName = "remove")]
- public ConnectionCollection Connections{
- get{return (ConnectionCollection)this["connections"];}
- }
- }
-}
diff --git a/MongoDBDriver/Connections/Connection.cs b/MongoDBDriver/Connections/Connection.cs
deleted file mode 100644
index da2a93a6..00000000
--- a/MongoDBDriver/Connections/Connection.cs
+++ /dev/null
@@ -1,172 +0,0 @@
-using System;
-using System.IO;
-using MongoDB.Driver.Protocol;
-
-namespace MongoDB.Driver.Connections
-{
- ///
- /// Connection is a managment unit which uses a RawConnection from connection pool
- /// to comunicate with the server.
- ///
- /// If an connection error occure, the RawConnection is transparently replaced
- /// by a new fresh connection.
- ///
- ///
- public class Connection : IDisposable
- {
- private readonly IConnectionFactory _factory;
- private RawConnection _connection;
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The pool.
- public Connection(IConnectionFactory factory)
- {
- if (factory == null)
- throw new ArgumentNullException ("factory");
-
- _factory = factory;
- }
-
- ///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
- ///
- ~Connection (){
- // make sure the connection returns to pool if the user forget it.
- Dispose ();
- }
-
- ///
- /// Gets or sets a value indicating whether this instance is authenticated.
- ///
- ///
- /// true if this instance is authenticated; otherwise, false.
- ///
- public bool IsAuthenticated {
- get { return _connection.IsAuthenticated; }
- }
-
- ///
- /// Masks as authenticated.
- ///
- public void MaskAuthenticated (){
- _connection.MarkAuthenticated ();
- }
-
- ///
- /// Gets the connection string.
- ///
- /// The connection string.
- public string ConnectionString {
- get { return _factory.ConnectionString; }
- }
-
- ///
- /// Used for sending a message that gets a reply such as a query.
- ///
- ///
- ///
- /// A reconnect will be issued but it is up to the caller to handle the error.
- public ReplyMessage SendTwoWayMessage (IRequestMessage msg){
- if (this.State != ConnectionState.Opened) {
- throw new MongoCommException ("Operation cannot be performed on a closed connection.", this);
- }
- try {
- ReplyMessage reply = new ReplyMessage ();
- lock (_connection) {
- msg.Write (_connection.GetStream ());
- reply.Read (_connection.GetStream ());
- }
- return reply;
- } catch (IOException) {
- ReplaceInvalidConnection ();
- throw;
- }
-
- }
-
- ///
- /// Used for sending a message that gets no reply such as insert or update.
- ///
- ///
- ///
- /// A reconnect will be issued but it is up to the caller to handle the error.
- public void SendMessage (IRequestMessage msg){
- if (this.State != ConnectionState.Opened) {
- throw new MongoCommException ("Operation cannot be performed on a closed connection.", this);
- }
- try {
- lock (_connection) {
- msg.Write (_connection.GetStream ());
- }
- } catch (IOException) {
- //Sending doesn't seem to always trigger the detection of a closed socket.
- ReplaceInvalidConnection ();
- throw;
- }
- }
-
- ///
- /// Gets the state.
- ///
- /// The state.
- public ConnectionState State {
- get { return _connection != null ? ConnectionState.Opened : ConnectionState.Closed; }
- }
-
- ///
- /// Just sends a simple message string to the database.
- ///
- ///
- /// A
- ///
- public void SendMsgMessage (String message){
- MsgMessage msg = new MsgMessage ();
- msg.Message = message;
- this.SendMessage (msg);
- }
-
- ///
- /// Opens this instance.
- ///
- public void Open (){
- _connection = _factory.Open();
- }
-
- ///
- /// Closes this instance.
- ///
- public void Close (){
- if (_connection == null)
- return;
-
- _factory.Close(_connection);
- _connection = null;
- }
-
- ///
- /// Replaces the invalid connection.
- ///
- private void ReplaceInvalidConnection (){
- if (_connection == null)
- return;
-
- _connection.MarkAsInvalid ();
- _factory.Close (_connection);
- _connection = _factory.Open();
- }
-
- public Stream GetStream (){
- return _connection.GetStream ();
- }
-
- ///
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- ///
- public void Dispose (){
- Close ();
- }
- }
-}
diff --git a/MongoDBDriver/Connections/ConnectionState.cs b/MongoDBDriver/Connections/ConnectionState.cs
deleted file mode 100644
index 0eddb664..00000000
--- a/MongoDBDriver/Connections/ConnectionState.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace MongoDB.Driver.Connections
-{
- public enum ConnectionState{
- Closed = 0,
- Opened = 1,
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/Cursor.cs b/MongoDBDriver/Cursor.cs
deleted file mode 100644
index dab68b79..00000000
--- a/MongoDBDriver/Cursor.cs
+++ /dev/null
@@ -1,219 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using MongoDB.Driver.Connections;
-using MongoDB.Driver.Protocol;
-
-namespace MongoDB.Driver
-{
- public class Cursor : ICursor {
- private Connection connection;
-
- private long id = -1;
- public long Id{
- get {return id;}
- }
-
- private String fullCollectionName;
- public string FullCollectionName {
- get {return fullCollectionName;}
- }
-
- private Document spec;
- public ICursor Spec (Document spec){
- TryModify();
- this.spec = spec;
- return this;
- }
-
- private int limit;
- public ICursor Limit (int limit){
- TryModify();
- this.limit = limit;
- return this;
- }
-
- private int skip;
- public ICursor Skip (int skip){
- TryModify();
- this.skip = skip;
- return this;
- }
-
- private Document fields;
- public ICursor Fields (Document fields){
- TryModify();
- this.fields = fields;
- return this;
- }
-
- private QueryOptions options;
- public ICursor Options(QueryOptions options){
- TryModify();
- this.options = options;
- return this;
- }
-
- #region "Spec Options"
- private Document specOpts = new Document();
-
- public ICursor Sort(string field){
- return this.Sort(field, IndexOrder.Ascending);
- }
-
- public ICursor Sort(string field, IndexOrder order){
- return this.Sort(new Document().Append(field, order));
- }
-
- public ICursor Sort(Document fields){
- TryModify();
- AddOrRemoveSpecOpt("$orderby", fields);
- return this;
- }
-
- public ICursor Hint(Document index){
- TryModify();
- AddOrRemoveSpecOpt("$hint", index);
- return this;
- }
-
- public ICursor Snapshot(Document index){
- TryModify();
- AddOrRemoveSpecOpt("$snapshot", index);
- return this;
- }
-
- public Document Explain(){
- TryModify();
- specOpts["$explain"] = true;
-
- IEnumerable docs = this.Documents;
- using((IDisposable)docs){
- foreach(Document doc in docs){
- return doc;
- }
- }
- throw new InvalidOperationException("Explain failed.");
- }
-
- #endregion
-
- private bool modifiable = true;
- public bool Modifiable{
- get {return modifiable;}
- }
-
- private ReplyMessage reply;
-
- public Cursor(Connection conn, string fullCollectionName){
- this.connection = conn;
- this.fullCollectionName = fullCollectionName;
- }
-
- public Cursor(Connection conn, String fullCollectionName, Document spec, int limit, int skip, Document fields):
- this(conn,fullCollectionName){
- if(spec == null)spec = new Document();
- this.spec = spec;
- this.limit = limit;
- this.skip = skip;
- this.fields = fields;
- }
-
- public IEnumerable Documents{
- get{
- if(this.reply == null){
- RetrieveData();
- }
- int docsReturned = 0;
- Document[] docs = this.reply.Documents;
- Boolean shouldBreak = false;
- while(!shouldBreak){
- foreach(Document doc in docs){
- if((this.limit == 0) || (this.limit != 0 && docsReturned < this.limit)){
- docsReturned++;
- yield return doc;
- }else{
- shouldBreak = true;
- yield break;
- }
- }
- if(this.Id != 0 && shouldBreak == false){
- RetrieveMoreData();
- docs = this.reply.Documents;
- if(docs == null){
- shouldBreak = true;
- }
- }else{
- shouldBreak = true;
- }
- }
- }
- }
-
- private void RetrieveData(){
- QueryMessage query = new QueryMessage();
- query.FullCollectionName = this.FullCollectionName;
- query.Query = BuildSpec();
- query.NumberToReturn = this.limit;
- query.NumberToSkip = this.skip;
- query.Options = options;
-
- if(this.fields != null){
- query.ReturnFieldSelector = this.fields;
- }
- try{
- this.reply = connection.SendTwoWayMessage(query);
- this.id = this.reply.CursorID;
- if(this.limit < 0)this.limit = this.limit * -1;
- }catch(IOException ioe){
- throw new MongoCommException("Could not read data, communication failure", this.connection,ioe);
- }
-
- }
-
- private void RetrieveMoreData(){
- GetMoreMessage gmm = new GetMoreMessage(this.fullCollectionName, this.Id, this.limit);
- try{
- this.reply = connection.SendTwoWayMessage(gmm);
- this.id = this.reply.CursorID;
- }catch(IOException ioe){
- this.id = 0;
- throw new MongoCommException("Could not read data, communication failure", this.connection,ioe);
- }
- }
-
-
- public void Dispose(){
- if(this.Id == 0) return; //All server side resources disposed of.
- KillCursorsMessage kcm = new KillCursorsMessage(this.Id);
- try{
- this.id = 0;
- connection.SendMessage(kcm);
- }catch(IOException ioe){
- throw new MongoCommException("Could not read data, communication failure", this.connection,ioe);
- }
- }
-
- private void TryModify(){
- if(this.modifiable) return;
- throw new InvalidOperationException("Cannot modify a cursor that has already returned documents.");
- }
-
- private void AddOrRemoveSpecOpt(string key, Document doc){
- if(doc == null){
- specOpts.Remove(key);
- }else{
- specOpts[key] = doc;
- }
- }
-
- private Document BuildSpec(){
- if(this.specOpts.Count == 0) return this.spec;
- Document doc = new Document();
- this.specOpts.CopyTo(doc);
- doc["$query"] = this.spec;
- return doc;
- }
-
- }
-}
diff --git a/MongoDBDriver/DBRef.cs b/MongoDBDriver/DBRef.cs
deleted file mode 100644
index 7f130d3b..00000000
--- a/MongoDBDriver/DBRef.cs
+++ /dev/null
@@ -1,117 +0,0 @@
-using System;
-
-namespace MongoDB.Driver
-{
- ///
- /// Native type that maps to a database reference. Use Database.FollowReference(DBRef) to retrieve the document
- /// that it refers to.
- ///
- /// DBRefs are just a specification for a specially formatted Document. At this time the database
- /// does no special handling of them. Any referential integrity must be maintained by the application
- /// not the database.
- ///
- public class DBRef
- {
- public const string RefName = "$ref";
- public const string IdName = "$id";
- public const string MetaName = "metadata";
-
- private Document document;
-
- ///
- /// Initializes a new instance of the class.
- ///
- public DBRef(){
- document = new Document();
- }
-
- private string collectionName;
- ///
- /// The name of the collection the referenced document is in.
- ///
- public string CollectionName {
- get { return collectionName; }
- set {
- collectionName = value;
- document[RefName] = value;
- }
- }
-
- private object id;
- ///
- /// Object value of the id. It isn't an Oid because document ids are not required to be oids.
- ///
- public object Id {
- get { return id; }
- set {
- id = value;
- document[IdName] = value;
- }
- }
-
- private Document metadata;
- ///
- /// An extension to the spec that allows storing of arbitrary data about a reference.
- ///
- /// This is a non-standard feature.
- ///
- public Document MetaData {
- get{return metadata; }
- set{
- metadata = value;
- document[MetaName] = value;
- }
- }
-
- ///
- /// Constructs a DBRef from a document that matches the DBref specification.
- ///
- public DBRef(Document document){
- if(IsDocumentDBRef(document) == false) throw new ArgumentException("Document is not a valid DBRef");
- collectionName = (String)document[RefName];
- id = document[IdName];
- this.document = document;
- if(document.Contains("metadata")) this.MetaData = (Document)document["metadata"];
- }
-
- public DBRef(string collectionName, object id){
- document = new Document();
- this.CollectionName = collectionName;
- this.Id = id;
- }
-
- public override bool Equals(object obj){
- if(obj is DBRef){
- DBRef comp = (DBRef)obj;
- return comp.Id.Equals(this.Id) && comp.CollectionName.Equals(this.CollectionName);
- }
- return base.Equals(obj);
- }
-
- public override int GetHashCode(){
- unchecked{
- return ((this.collectionName != null ? this.collectionName.GetHashCode() : 0) * 397) ^ (this.id != null ? this.id.GetHashCode() : 0);
- }
- }
-
- public override string ToString (){
- return document.ToString();
- }
-
-
- ///
- /// Deprecated. Use the new DBRef(Document) constructor instead.
- ///
- public static DBRef FromDocument(Document doc){
- return new DBRef(doc);;
- }
-
- public static bool IsDocumentDBRef(Document doc){
- return doc != null && doc.Contains(RefName) && doc.Contains(IdName);
- }
-
- public static explicit operator Document(DBRef d){
- return d.document;
- }
- }
-}
diff --git a/MongoDBDriver/Database.cs b/MongoDBDriver/Database.cs
deleted file mode 100644
index 14a424b8..00000000
--- a/MongoDBDriver/Database.cs
+++ /dev/null
@@ -1,207 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Text;
-using MongoDB.Driver.Connections;
-
-namespace MongoDB.Driver
-{
- public class Database
- {
- private Connection connection;
- private IMongoCollection command;
-
- public Database(string connectionString, String name){
- this.connection = ConnectionFactory.GetConnection(connectionString);
- this.Name = name;
- this.command = this["$cmd"];
- }
-
- public Database(Connection conn, String name){
- this.connection = conn;
- this.Name = name;
- this.command = this["$cmd"];
- }
-
- public string Name { get; private set; }
-
- private DatabaseMetaData metaData;
- public DatabaseMetaData MetaData {
- get { return metaData ?? (metaData = new DatabaseMetaData(this.Name, this.connection)); }
- }
-
- private DatabaseJS js;
- public DatabaseJS JS {
- get { return js ?? (js = new DatabaseJS(this)); }
- }
-
- public List GetCollectionNames(){
- IMongoCollection namespaces = this["system.namespaces"];
- ICursor cursor = namespaces.Find(new Document());
- List names = new List();
- foreach (Document doc in cursor.Documents){
- names.Add((String)doc["name"]); //Fix Me: Should filter built-ins
- }
- return names;
- }
-
- public IMongoCollection this[ String name ] {
- get{
- return this.GetCollection(name);
- }
- }
-
- public IMongoCollection GetCollection(String name){
- IMongoCollection col = new Collection(name, this.connection, this.Name);
- return col;
- }
-
- ///
- /// Gets the document that a reference is pointing to.
- ///
- public Document FollowReference(DBRef reference){
- if(reference == null)
- throw new ArgumentNullException("reference", "cannot be null");
- Document query = new Document().Append("_id", reference.Id);
- return this[reference.CollectionName].FindOne(query);
- }
-
- ///
- /// Most operations do not have a return code in order to save the client from having to wait for results.
- /// GetLastError can be called to retrieve the return code if clients want one.
- ///
- public Document GetLastError(){
- return SendCommand("getlasterror");
- }
-
- ///
- /// Retrieves the last error and forces the database to fsync all files before returning.
- ///
- /// Server version 1.3+
- public Document GetLastErrorAndFSync(){
- return SendCommand(new Document {{"getlasterror", 1.0},{"fsync", true}});
- }
-
- ///
- /// Call after sending a bulk operation to the database.
- ///
- public Document GetPreviousError(){
- return SendCommand("getpreverror");
- }
-
- ///
- /// Gets the sister database on the same Mongo connection with the given name.
- ///
- public Database GetSisterDatabase(string sisterDbName){
- return new Database(connection, sisterDbName);
- }
-
- ///
- /// Resets last error. This is good to call before a bulk operation.
- ///
- public void ResetError(){
- SendCommand("reseterror");
- }
-
- public Document Eval(string javascript){
- return Eval(javascript, new Document());
- }
-
- public Document Eval(string javascript, Document scope){
- return Eval(new CodeWScope(javascript, scope));
- }
-
- public Document Eval(CodeWScope cw){
- Document cmd = new Document().Append("$eval", cw);
- return SendCommand(cmd);
- }
-
- public Document SendCommand(string command){
- AuthenticateIfRequired();
- return SendCommandCore(command);
- }
-
- public Document SendCommand(Document cmd)
- {
- AuthenticateIfRequired();
- return SendCommandCore(cmd);
- }
-
- private Document SendCommandCore(string command)
- {
- var cmd = new Document().Append(command,1.0);
- return SendCommandCore(cmd);
- }
-
- private Document SendCommandCore(Document cmd)
- {
- Document result = this.command.FindOne(cmd);
- double ok = (double)result["ok"];
- if(ok != 1.0)
- {
- var msg = string.Empty;
- if(result.Contains("msg"))
- {
- msg = (string)result["msg"];
- }
- else if(result.Contains("errmsg"))
- {
- msg = (string)result["errmsg"];
- }
- throw new MongoCommandException(msg, result, cmd);
- }
- return result;
- }
-
- ///
- /// Authenticates the on first request.
- ///
- private void AuthenticateIfRequired()
- {
- if(connection.IsAuthenticated)
- return;
-
- var builder = new MongoConnectionStringBuilder(connection.ConnectionString);
-
- if(string.IsNullOrEmpty(builder.Username))
- return;
-
- var nonceResult = SendCommandCore("getnonce");
- var nonce = (String)nonceResult["nonce"];
-
- if(nonce == null)
- throw new MongoException("Error retrieving nonce", null);
-
- var pwd = Hash(builder.Username + ":mongo:" + builder.Password);
- var auth = new Document
- {
- {"authenticate", 1.0},
- {"user", builder.Username},
- {"nonce", nonce},
- {"key", Hash(nonce + builder.Username + pwd)}
- };
- try
- {
- SendCommandCore(auth);
- }
- catch(MongoCommandException exception)
- {
- //Todo: use custom exception?
- throw new MongoException("Authentication faild for " + builder.Username, exception);
- }
-
- connection.MaskAuthenticated();
- }
-
- ///
- /// Hashes the specified text.
- ///
- /// The text.
- ///
- internal static string Hash(string text){
- MD5 md5 = MD5.Create();
- byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(text));
- return BitConverter.ToString(hash).Replace("-","").ToLower();
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/DatabaseJS.cs b/MongoDBDriver/DatabaseJS.cs
deleted file mode 100644
index 540a02a7..00000000
--- a/MongoDBDriver/DatabaseJS.cs
+++ /dev/null
@@ -1,165 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace MongoDB.Driver{
-
- ///
- /// Encapsulates and provides access to the serverside javascript stored in db.system.js.
- ///
- public class DatabaseJS : ICollection
- {
- //private Connection connection;
- private Database db;
- private IMongoCollection js;
-
- internal DatabaseJS (Database db){
- this.db = db;
- this.js = db["system.js"];
- //Needed for some versions of the db to retrieve the functions.
- js.MetaData.CreateIndex(new Document().Append("_id",1),true);
- }
-
- public Document this[ String name ] {
- get{
- return GetFunction(name);
- }
- set{
- Add(value);
- }
- }
-
- ///
- /// Gets the document representing the function in the database.
- ///
- ///
- /// A
- ///
- ///
- /// A
- ///
- public Document GetFunction(string name){
- return js.FindOne(new Document().Append("_id", name));
- }
-
- ///
- /// Returns a listing of the names of all the functions in the database
- ///
- public List GetFunctionNames(){
- List l = new List();
- foreach(Document d in js.FindAll().Documents){
- l.Add((String)d["_id"]);
- }
- return l;
- }
-
- public void Add (string name, string func){
- Add(name, new Code(func));
- }
-
- public void Add (string name, Code func){
- Add(new Document().Append("_id", name).Append("value", func));
- }
-
- ///
- /// Store a function in the database with an extended attribute called version.
- ///
- /// Version attributes are an extension to the spec. Function names must be unique
- /// to the database so only one version can be stored at a time. This is most useful for libraries
- /// that store function in the database to make sure that the function they are using is the most
- /// up to date.
- ///
- public void Add(string name, Code func, float version){
- Add(new Document().Append("_id", name).Append("value", func).Append("version",version));
- }
-
- ///
- /// Stores a function in the database.
- ///
- public void Add (Document item){
- if(js.FindOne(new Document().Append("_id", item["_id"])) != null){
- throw new ArgumentException(String.Format("Function {0} already exists in the database.", item["_id"]));
- }
- js.Insert(item);
- }
-
- ///
- /// Removes every function in the database.
- ///
- public void Clear (){
- js.Delete(new Document());
- }
-
- public bool Contains (Document item){
- return Contains((string)item["_id"]);
- }
-
- ///
- /// Checks to see if a function named name is stored in the database.
- ///
- ///
- /// A
- ///
- ///
- /// A
- ///
- public bool Contains (string name){
- return GetFunction(name) != null;
- }
-
- ///
- /// Copies the functions from the database ordered by _id (name) to the array starting at the index.
- ///
- ///
- /// A array to coppy to
- ///
- ///
- /// A
- ///
- public void CopyTo (Document[] array, int arrayIndex){
- Document query = new Document().Append("$orderby", new Document().Append("_id", 1));
- int idx = arrayIndex;
- foreach(Document doc in js.Find(query,array.Length - 1,arrayIndex).Documents){
- array[idx] = doc;
- idx++;
- }
- }
-
- public void Update(Document item){
- throw new System.NotImplementedException();
- }
-
- public bool Remove (Document item){
- return Remove((string)item["_id"]);
- }
-
- public bool Remove (string name){
- js.Delete(new Document().Append("_id", name));
- return true;
- }
-
- public int Count {
- get {
- long cnt = js.Count();
- if(cnt > int.MaxValue) return int.MaxValue; //lots of functions.
- return (int)cnt;
- }
- }
-
- public bool IsReadOnly {
- get {
- return false;
- }
- }
-
- public IEnumerator GetEnumerator (){
- foreach(Document doc in js.FindAll().Documents){
- yield return doc;
- }
- yield break;
- }
-
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator (){
- return GetEnumerator();
- }
- }
-}
diff --git a/MongoDBDriver/DatabaseMetaData.cs b/MongoDBDriver/DatabaseMetaData.cs
deleted file mode 100644
index d757c374..00000000
--- a/MongoDBDriver/DatabaseMetaData.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-using System;
-using MongoDB.Driver.Connections;
-
-namespace MongoDB.Driver
-{
- ///
- /// Administration of metadata for a database.
- ///
- public class DatabaseMetaData
- {
- private Connection connection;
- private string name;
- private Database db;
-
- public DatabaseMetaData(string name, Connection conn){
- this.connection = conn;
- this.name = name;
- this.db = new Database(conn, name);
- }
-
- public Collection CreateCollection(String name){
- return this.CreateCollection(name,null);
- }
-
- public Collection CreateCollection(String name, Document options){
- Document cmd = new Document();
- cmd.Append("create", name).Update(options);
- db.SendCommand(cmd);
- return new Collection(name, connection, this.name);
- }
-
-
- public Boolean DropCollection(Collection col){
- return this.DropCollection(col.Name);
- }
-
- public Boolean DropCollection(String name){
- Document result = db.SendCommand(new Document().Append("drop",name));
- return result.Contains("ok") && ((double)result["ok"] == 1);
- }
-
- public Boolean DropDatabase(){
- Document result = db.SendCommand("dropDatabase");
- return result.Contains("ok") && ((double)result["ok"] == 1);
- }
-
- public void AddUser(string username, string password){
- IMongoCollection users = db["system.users"];
- string pwd = Database.Hash(username + ":mongo:" + password);
- Document user = new Document().Append("user", username).Append("pwd", pwd);
-
- if (FindUser(username) != null){
- throw new MongoException("A user with the name " + username + " already exists in this database.", null);
- }
- users.Insert(user);
- }
-
- public void RemoveUser(string username){
- IMongoCollection users = db["system.users"];
- users.Delete(new Document().Append("user", username));
- }
-
- public ICursor ListUsers(){
- IMongoCollection users = db["system.users"];
- return users.FindAll();
- }
-
- public Document FindUser(string username){
- return FindUser(new Document().Append("user",username));
- }
-
- public Document FindUser(Document spec){
- return db["system.users"].FindOne(spec);
- }
- }
-}
diff --git a/MongoDBDriver/Document.cs b/MongoDBDriver/Document.cs
deleted file mode 100644
index 881aca6e..00000000
--- a/MongoDBDriver/Document.cs
+++ /dev/null
@@ -1,154 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-
-namespace MongoDB.Driver
-{
- ///
- /// Description of Document.
- ///
- public class Document : DictionaryBase
- {
- private List orderedKeys = new List ();
-
- public Object this[String key] {
- get { return Dictionary[key]; }
- set {
- if (orderedKeys.Contains (key) == false) {
- orderedKeys.Add (key);
- }
- Dictionary[key] = value;
- }
- }
-
- public ICollection Keys {
- get { return (orderedKeys); }
- }
-
- public ICollection Values {
- get { return (Dictionary.Values); }
- }
-
- public void Add (String key, Object value)
- {
- Dictionary.Add (key, value);
- //Relies on ArgumentException from above if key already exists.
- orderedKeys.Add (key);
- }
-
- public Document Append (String key, Object value)
- {
- this.Add (key, value);
- return this;
- }
-
- ///
- /// Adds an item to the Document at the specified position
- ///
- public void Insert (String key, Object value, int Position)
- {
- Dictionary.Add (key, value);
- //Relies on ArgumentException from above if key already exists.
- orderedKeys.Insert (Position, key);
- }
- public Document Prepend (String key, Object value)
- {
- this.Insert (key, value, 0);
- return this;
- }
-
- public Document Update (Document @from)
- {
- if (@from == null)
- return this;
- foreach (String key in @from.Keys) {
- this[key] = @from[key];
- }
- return this;
- }
-
- public bool Contains (String key)
- {
- return (orderedKeys.Contains (key));
- }
-
- public void Remove (String key)
- {
- Dictionary.Remove (key);
- orderedKeys.Remove (key);
- }
-
- public new void Clear ()
- {
- Dictionary.Clear ();
- orderedKeys.Clear ();
- }
-
- ///
- /// TODO Fix any accidental reordering issues.
- ///
- ///
- public void CopyTo (Document dest)
- {
- foreach (String key in orderedKeys) {
- if (dest.Contains (key))
- dest.Remove (key);
- dest[key] = this[key];
- }
- }
-
- public override bool Equals (object obj)
- {
- if (obj is Document) {
- return Equals (obj as Document);
- }
- return base.Equals (obj);
- }
-
- public bool Equals (Document obj)
- {
- if (obj == null)
- return false;
- if (orderedKeys.Count != obj.orderedKeys.Count)
- return false;
- return this.GetHashCode () == obj.GetHashCode ();
- }
-
- public override int GetHashCode (){
- int hash = 27;
- foreach (var key in orderedKeys) {
- var valueHashCode = GetValueHashCode (this[key]);
- unchecked {
- hash = (13 * hash) + key.GetHashCode ();
- hash = (13 * hash) + valueHashCode;
- }
- }
- return hash;
- }
-
- private int GetValueHashCode (object value)
- {
- if (value == null) {
- return 0;
- }
- return (value is Array) ? GetArrayHashcode ((Array)value) : value.GetHashCode ();
- }
-
- private int GetArrayHashcode (Array array)
- {
- var hash = 0;
- foreach (var value in array) {
- var valueHashCode = GetValueHashCode (value);
- unchecked {
- hash = (13 * hash) + valueHashCode;
- }
- }
- return hash;
- }
-
- public override string ToString ()
- {
- return JsonFormatter.Serialize (this);
- }
- }
-}
diff --git a/MongoDBDriver/Exceptions/MongoCommException.cs b/MongoDBDriver/Exceptions/MongoCommException.cs
deleted file mode 100644
index cdc7260c..00000000
--- a/MongoDBDriver/Exceptions/MongoCommException.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-using System;
-using MongoDB.Driver.Connections;
-
-namespace MongoDB.Driver
-{
- ///
- ///
- ///
- public class MongoCommException : MongoException
- {
- ///
- /// Gets or sets the connection string.
- ///
- /// The connection string.
- public string ConnectionString { get; private set; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The message.
- /// The connection.
- public MongoCommException(string message, Connection connection):this(message,connection,null){}
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The message.
- /// The connection.
- /// The inner.
- public MongoCommException(string message, Connection connection, Exception inner):base(message,inner){
- ConnectionString = connection.ConnectionString;
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/Exceptions/MongoCommandException.cs b/MongoDBDriver/Exceptions/MongoCommandException.cs
deleted file mode 100644
index ec33535d..00000000
--- a/MongoDBDriver/Exceptions/MongoCommandException.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-using System;
-
-namespace MongoDB.Driver
-{
- ///
- /// Raised when a command returns a failure message.
- ///
- public class MongoCommandException : MongoException
- {
- ///
- /// Gets or sets the error.
- ///
- /// The error.
- public Document Error { get; private set; }
-
- ///
- /// Gets or sets the command.
- ///
- /// The command.
- public Document Command { get; private set; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The message.
- /// The error.
- /// The command.
- public MongoCommandException(string message, Document error, Document command):base(message,null){
- this.Error = error;
- this.Command = command;
- }
- ///
- /// Initializes a new instance of the class.
- ///
- /// The message.
- /// The error.
- /// The command.
- /// The e.
- public MongoCommandException(string message, Document error, Document command, Exception e):base(message,e){
- this.Error = error;
- this.Command = command;
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/Exceptions/MongoDuplicateKeyException.cs b/MongoDBDriver/Exceptions/MongoDuplicateKeyException.cs
deleted file mode 100644
index 072ff585..00000000
--- a/MongoDBDriver/Exceptions/MongoDuplicateKeyException.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using System;
-
-namespace MongoDB.Driver
-{
- ///
- /// Raised when an action causes a unique constraint violation in an index.
- ///
- public class MongoDuplicateKeyException : MongoOperationException
- {
- ///
- /// Initializes a new instance of the class.
- ///
- /// The message.
- /// The error.
- public MongoDuplicateKeyException(string message, Document error):base(message, error,null){}
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The message.
- /// The error.
- /// The e.
- public MongoDuplicateKeyException(string message, Document error, Exception e):base(message, error,e){}
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/Exceptions/MongoException.cs b/MongoDBDriver/Exceptions/MongoException.cs
deleted file mode 100644
index 37b14a7f..00000000
--- a/MongoDBDriver/Exceptions/MongoException.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using System;
-
-namespace MongoDB.Driver
-{
- ///
- /// Base class for all Mongo Exceptions
- ///
- public class MongoException : Exception
- {
- ///
- /// Initializes a new instance of the class.
- ///
- /// The message.
- /// The inner.
- public MongoException(string message, Exception inner):base(message,inner){}
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The message.
- public MongoException(string message):base(message){}
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/Exceptions/MongoMapReduceException.cs b/MongoDBDriver/Exceptions/MongoMapReduceException.cs
deleted file mode 100644
index e327580c..00000000
--- a/MongoDBDriver/Exceptions/MongoMapReduceException.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-namespace MongoDB.Driver
-{
- ///
- /// Raised when a map reduce call fails.
- ///
- public class MongoMapReduceException : MongoCommandException
- {
- ///
- /// Gets or sets the map reduce result.
- ///
- /// The map reduce result.
- public MapReduce.MapReduceResult MapReduceResult { get; private set; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The exception.
- /// The map reduce.
- public MongoMapReduceException(MongoCommandException exception, MapReduce mapReduce)
- :base(exception.Message,exception.Error, exception.Command) {
- MapReduceResult = new MapReduce.MapReduceResult(exception.Error);
- }
- }
-}
diff --git a/MongoDBDriver/Exceptions/MongoOperationException.cs b/MongoDBDriver/Exceptions/MongoOperationException.cs
deleted file mode 100644
index e8c36d6c..00000000
--- a/MongoDBDriver/Exceptions/MongoOperationException.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-using System;
-
-namespace MongoDB.Driver
-{
- public class MongoOperationException : MongoException
- {
- ///
- /// Gets or sets the error.
- ///
- /// The error.
- public Document Error { get; private set; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The message.
- /// The error.
- public MongoOperationException(string message, Document error):this(message, error,null){}
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The message.
- /// The error.
- /// The e.
- public MongoOperationException(string message, Document error, Exception e):base(message,e){
- this.Error = error;
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/ICursor.cs b/MongoDBDriver/ICursor.cs
deleted file mode 100644
index cfd1fe36..00000000
--- a/MongoDBDriver/ICursor.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace MongoDB.Driver {
- public interface ICursor : IDisposable {
- long Id { get; }
- string FullCollectionName { get; }
- ICursor Spec(Document spec);
- ICursor Limit(int limit);
- ICursor Skip(int skip);
- ICursor Fields (Document fields);
- ICursor Sort(string field);
- ICursor Sort(string field, IndexOrder order);
- ICursor Sort(Document fields);
- ICursor Hint(Document index);
- ICursor Snapshot(Document index);
- Document Explain();
- bool Modifiable { get; }
- IEnumerable Documents { get; }
- }
-}
diff --git a/MongoDBDriver/IMongoCollection.cs b/MongoDBDriver/IMongoCollection.cs
deleted file mode 100644
index f47a2c89..00000000
--- a/MongoDBDriver/IMongoCollection.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace MongoDB.Driver
-{
- public interface IMongoCollection
- {
- string Name { get; }
- string DbName { get; }
- string FullName { get; }
- CollectionMetaData MetaData { get; }
- Document FindOne (Document spec);
- ICursor FindAll ();
- ICursor Find (String @where);
- ICursor Find (Document spec);
- ICursor Find (Document spec, int limit, int skip);
- ICursor Find (Document spec, int limit, int skip, Document fields);
- MapReduce MapReduce ();
- MapReduceBuilder MapReduceBuilder ();
- long Count ();
- long Count (Document spec);
- void Insert (Document doc);
- void Insert (Document doc, bool safemode);
- void Insert (IEnumerable docs);
- void Insert (IEnumerable docs, bool safemode);
- void Delete (Document selector);
- void Delete (Document selector, bool safemode);
- void Update (Document doc);
- void Update (Document doc, Document selector);
- void Update (Document doc, Document selector, int upsert);
- void Update (Document doc, Document selector, UpdateFlags flags);
- void Update (Document doc, bool safemode);
- void Update (Document doc, Document selector, bool safemode);
- void Update (Document doc, Document selector, int upsert, bool safemode);
- void Update (Document doc, Document selector, UpdateFlags flags, bool safemode);
- void UpdateAll (Document doc, Document selector);
- void UpdateAll (Document doc, Document selector, bool safemode);
- }
-}
diff --git a/MongoDBDriver/IndexOrder.cs b/MongoDBDriver/IndexOrder.cs
deleted file mode 100644
index 31ba930f..00000000
--- a/MongoDBDriver/IndexOrder.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace MongoDB.Driver
-{
- public enum IndexOrder {
- Descending = -1,
- Ascending = 1
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/MapReduce.cs b/MongoDBDriver/MapReduce.cs
deleted file mode 100644
index 9019ff95..00000000
--- a/MongoDBDriver/MapReduce.cs
+++ /dev/null
@@ -1,257 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace MongoDB.Driver
-{
- ///
- /// A fluent interface for executing a Map/Reduce call against a collection.
- ///
- public class MapReduce : IDisposable
- {
-
- public class MapReduceResult{
- Document result;
- Document counts;
- public MapReduceResult(Document result){
- this.result = result;
- this.counts = (Document)result["counts"];
- }
- public string CollectionName{
- get{return (string)result["result"];}
- }
- public long InputCount{
- get{return Convert.ToInt64(counts["input"]);}
- }
-
- public long EmitCount{
- get{return Convert.ToInt64(counts["emit"]);}
- }
-
- public long OutputCount{
- get{return Convert.ToInt64(counts["output"]);}
- }
-
- public long Time{
- get{return Convert.ToInt64(result["timeMillis"]);}
- }
-
- private TimeSpan span = TimeSpan.MinValue;
- public TimeSpan TimeSpan{
- get{
- if(span == TimeSpan.MinValue) span = TimeSpan.FromMilliseconds(this.Time);
- return span;
- }
- }
-
- public Boolean Ok{
- get{return (1.0 == Convert.ToDouble(result["ok"]));}
- }
-
- public String ErrorMessage{
- get{
- if(result.Contains("msg"))return (String)result["msg"];
- return String.Empty;
- }
- }
- public override string ToString (){
- return result.ToString();
- }
-
- }
-
- Database db;
- Document cmd;
-
- #region "Properties"
- string name;
- public string Name {
- get {return (String)cmd["mapreduce"];}
- }
-
- MapReduceResult result;
- ///
- /// Holds the resulting value of the execution.
- ///
- public MapReduceResult Result {
- get {return result;}
- }
-
- internal MapReduce (Database db, string name){
- this.db = db;
- this.cmd = new Document().Append("mapreduce", name);
- this.Verbose = true;
- }
-
- /// The map function references the variable this to inspect the current object under consideration.
- /// A map function must call emit(key,value) at least once, but may be invoked any number of times,
- /// as may be appropriate.
- ///
- public Code Map {
- get {return (Code)cmd["map"];}
- set {
- TryModify();
- cmd["map"] = value;}
- }
-
- ///
- /// The reduce function receives a key and an array of values. To use, reduce the received values,
- /// and return a result.
- ///
- /// The MapReduce engine may invoke reduce functions iteratively; thus, these functions
- /// must be idempotent. If you need to perform an operation only once, use a finalize function.
- public Code Reduce {
- get {return (Code)cmd["reduce"];}
- set {
- TryModify();
- cmd["reduce"] = value;
- }
- }
-
- #region "Options"
-
- public Document Query{
- get{return (Document)cmd["query"];}
- set{
- TryModify();
- cmd["query"] = value;
- }
- }
-
- ///
- /// Sort the query. Useful for optimization
- ///
- public Document Sort {
- get {return (Document)cmd["sort"];}
- set {
- TryModify();
- cmd["sort"] = value;
- }
- }
-
- ///
- /// Number of objects to return from collection
- ///
- public long Limit {
- get {return (long)cmd["limit"];}
- set {
- TryModify();
- cmd["limit"] = value;
- }
- }
-
- ///
- /// Name of the final collection the results should be stored in.
- ///
- /// A temporary collection is still used and then renamed to the target name atomically.
- ///
- public string Out {
- get {return (string)cmd["out"];}
- set {
- TryModify();
- cmd["out"] = value;
- }
- }
-
- ///
- /// When true the generated collection is not treated as temporary. Specifying out automatically makes
- /// the collection permanent
- ///
- public bool KeepTemp {
- get {return Convert.ToBoolean(cmd["keeptemp"]);}
- set {
- TryModify();
- cmd["keeptemp"] = value;
- }
- }
-
- ///
- /// Provides statistics on job execution time.
- ///
- public bool Verbose {
- get {return (bool)cmd["verbose"];}
- set {
- TryModify();
- cmd["verbose"] = value;
- }
- }
-
- ///
- /// Function to apply to all the results when finished.
- ///
- public Code Finalize {
- get {return (Code)cmd["finalize"];}
- set {
- TryModify();
- cmd["finalize"] = value;
- }
- }
-
- ///
- /// Document where fields go into javascript global scope
- ///
- public Document Scope {
- get {return (Document)cmd["scope"];}
- set {
- TryModify();
- cmd["scope"] = value;
- }
- }
-
- #endregion
- #endregion
-
- public MapReduce Execute(){
- if(cmd.Contains("map") == false || cmd.Contains("reduce") == false){
- throw new InvalidOperationException("Cannot execute without a map and reduce function");
- }
- canModify = false;
- try{
- result = new MapReduce.MapReduceResult(db.SendCommand(cmd));
- }catch(MongoCommandException mce){
- result = new MapReduce.MapReduceResult(mce.Error);
- throw new MongoMapReduceException(mce, this);
- }
- return this;
- }
-
- public IEnumerable Documents {
- get {
- if(result == null) Execute();
- if(result.Ok == false)
- throw new InvalidOperationException("Documents cannot be iterated when an error was returned from execute.");
-
- IEnumerable docs = db[result.CollectionName].FindAll().Documents;
- using((IDisposable)docs){
- foreach(Document doc in docs){
- yield return doc;
- }
- }
- }
- }
-
- bool canModify = true;
- public Boolean CanModify{
- get{return canModify;}
- }
-
- internal void TryModify(){
- if(canModify == false){
- throw new InvalidOperationException("Cannot modify a map/reduce that has already executed");
- }
- }
-
- #region IDisposable implementation
- private bool disposing = false;
- public void Dispose (){
- if(KeepTemp == true || this.Out != null || disposing == true) return;
- disposing = true;
-
- if(this.result == null || this.result.Ok == false) return; //Nothing to do.
-
- //Drop the temporary collection that was created as part of results.
- db.MetaData.DropCollection(this.result.CollectionName);
- }
-
- #endregion
- }
-}
diff --git a/MongoDBDriver/MapReduceBuilder.cs b/MongoDBDriver/MapReduceBuilder.cs
deleted file mode 100644
index c90eb629..00000000
--- a/MongoDBDriver/MapReduceBuilder.cs
+++ /dev/null
@@ -1,137 +0,0 @@
-using System;
-
-namespace MongoDB.Driver
-{
- ///
- /// Provides a Fluent interface to build and execute Map/Reduce calls.
- ///
- public class MapReduceBuilder : IDisposable
- {
- MapReduce mr;
- public MapReduce MapReduce {
- get {
- return mr;
- }
- }
-
- public MapReduceBuilder(MapReduce mr){
- this.mr = mr;
- }
-
- /// The map function references the variable this to inspect the current object under consideration.
- /// A map function must call emit(key,value) at least once, but may be invoked any number of times,
- /// as may be appropriate.
- ///
- public MapReduceBuilder Map(string function){
- return this.Map(new Code(function));
- }
-
- /// The map function references the variable this to inspect the current object under consideration.
- /// A map function must call emit(key,value) at least once, but may be invoked any number of times,
- /// as may be appropriate.
- ///
- public MapReduceBuilder Map(Code function){
- mr.Map = function;
- return this;
- }
-
- ///
- /// The reduce function receives a key and an array of values. To use, reduce the received values,
- /// and return a result.
- ///
- /// The MapReduce engine may invoke reduce functions iteratively; thus, these functions
- /// must be idempotent. If you need to perform an operation only once, use a finalize function.
- public MapReduceBuilder Reduce(string function){
- return this.Reduce(new Code(function));
- }
-
- ///
- /// The reduce function receives a key and an array of values. To use, reduce the received values,
- /// and return a result.
- ///
- /// The MapReduce engine may invoke reduce functions iteratively; thus, these functions
- /// must be idempotent. If you need to perform an operation only once, use a finalize function.
- public MapReduceBuilder Reduce(Code function){
- mr.Reduce = function;
- return this;
- }
-
- ///
- /// Query filter object
- ///
- public MapReduceBuilder Query(Document query){
- mr.Query = query;
- return this;
- }
-
- ///
- /// Sort the query. Useful for optimization
- ///
- public MapReduceBuilder Sort(Document sort){
- mr.Sort = sort;
- return this;
- }
-
- ///
- /// Number of objects to return from collection
- ///
- public MapReduceBuilder Limit(long limit){
- mr.Limit = limit;
- return this;
- }
-
- ///
- /// Name of the final collection the results should be stored in.
- ///
- /// A temporary collection is still used and then renamed to the target name atomically.
- ///
- public MapReduceBuilder Out(String name){
- mr.Out = name;
- return this;
- }
-
- ///
- /// When true the generated collection is not treated as temporary. Specifying out automatically makes
- /// the collection permanent
- ///
- public MapReduceBuilder KeepTemp(bool keep){
- mr.KeepTemp = keep;
- return this;
- }
-
- ///
- /// Provides statistics on job execution time.
- ///
- public MapReduceBuilder Verbose(bool val){
- mr.Verbose = val;
- return this;
- }
-
- ///
- /// Function to apply to all the results when finished.
- ///
- public MapReduceBuilder Finalize(Code function){
- mr.Finalize = function;
- return this;
- }
-
- ///
- /// Document where fields go into javascript global scope
- ///
- public MapReduceBuilder Scope(Document scope){
- mr.Scope = scope;
- return this;
- }
-
- public MapReduce Execute(){
- mr.Execute();
- return mr;
- }
-
- #region IDisposable implementation
- public void Dispose (){
- mr.Dispose();
- }
- #endregion
- }
-}
diff --git a/MongoDBDriver/Mongo.cs b/MongoDBDriver/Mongo.cs
deleted file mode 100644
index 365c10ee..00000000
--- a/MongoDBDriver/Mongo.cs
+++ /dev/null
@@ -1,80 +0,0 @@
-using System;
-using MongoDB.Driver.Connections;
-
-namespace MongoDB.Driver
-{
- ///
- /// Description of Mongo.
- ///
- public class Mongo : IDisposable
- {
- private Connection connection;
-
- ///
- /// Initializes a new instance of the class.
- ///
- public Mongo () : this(string.Empty){
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The connection string.
- public Mongo (string connectionString){
- if (connectionString == null)
- throw new ArgumentNullException ("connectionString");
-
- connection = ConnectionFactory.GetConnection (connectionString);
- }
-
- ///
- /// Gets the connection string.
- ///
- /// The connection string.
- public string ConnectionString {
- get { return connection.ConnectionString; }
- }
-
- ///
- /// Gets the named database.
- ///
- /// The name.
- ///
- public Database GetDatabase (String name){
- return new Database (connection, name);
- }
-
- ///
- /// Gets the with the specified name.
- ///
- ///
- public Database this[String name] {
- get { return this.GetDatabase (name); }
- }
-
- ///
- /// Connects this instance.
- ///
- ///
- public Boolean Connect (){
- connection.Open ();
- return connection.State == ConnectionState.Opened;
- }
-
- ///
- /// Disconnects this instance.
- ///
- ///
- public Boolean Disconnect (){
- connection.Close ();
- return connection.State == ConnectionState.Closed;
- }
-
- ///
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- ///
- public void Dispose (){
- connection.Dispose ();
- }
- }
-}
diff --git a/MongoDBDriver/MongoConnectionStringBuilder.cs b/MongoDBDriver/MongoConnectionStringBuilder.cs
deleted file mode 100644
index 41a98403..00000000
--- a/MongoDBDriver/MongoConnectionStringBuilder.cs
+++ /dev/null
@@ -1,317 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Text.RegularExpressions;
-
-namespace MongoDB.Driver
-{
- [Serializable]
- public class MongoConnectionStringBuilder
- {
- public const int DefaultMaximumPoolSize = 100;
- public const int DefaultMinimumPoolSize = 0;
- public const bool DefaultPooled = true;
- public static readonly TimeSpan DefaultConnectionTimeout = TimeSpan.FromSeconds(15);
- public static readonly TimeSpan DefaultConnectionLifeTime = TimeSpan.Zero;
-
- private static readonly Regex PairRegex = new Regex ("^\\s*(.*)\\s*=\\s*(.*)\\s*$");
- private static readonly Regex ServerRegex = new Regex ("\\s*([^:]+)(?::(\\d+))?\\s*$");
-
- private readonly List _servers = new List ();
-
- ///
- /// Initializes a new instance of the
- ///
- /// class. Uses the default server connection when
- /// no server is added.
- ///
- public MongoConnectionStringBuilder (){
- ConnectionLifetime = DefaultConnectionLifeTime;
- ConnectionTimeout = DefaultConnectionTimeout;
- MaximumPoolSize = DefaultMaximumPoolSize;
- MinimumPoolSize = DefaultMinimumPoolSize;
- Pooled = DefaultPooled;
- }
-
- ///
- /// Initializes a new instance of the
- ///
- /// class. Uses the default server connection when
- /// no server is added.
- ///
- /// The connection string.
- public MongoConnectionStringBuilder (string connectionString) : this(){
-
- if (!string.IsNullOrEmpty (connectionString))
- Parse (connectionString);
- }
-
- ///
- /// Gets the servers.
- ///
- /// The servers.
- public MongoServerEndPoint[] Servers {
- get { return _servers.Count == 0 ? new[] { MongoServerEndPoint.Default } : _servers.ToArray (); }
- }
-
- ///
- /// Gets or sets the password.
- ///
- /// The password.
- public string Password { get; set; }
-
- ///
- /// Gets or sets the username.
- ///
- /// The username.
- public string Username { get; set; }
-
-
- ///
- /// Gets or sets the maximum size of the connection pool.
- ///
- /// The maximum size of the pool.
- public int MaximumPoolSize { get; set; }
-
- ///
- /// Gets or sets the size of the minimum connection pool.
- ///
- /// The size of the minimal pool.
- public int MinimumPoolSize { get; set; }
-
- ///
- /// Gets or sets the connection lifetime in connection pool.
- ///
- /// The connection lifetime.
- public TimeSpan ConnectionLifetime { get; set; }
-
- ///
- /// Gets or sets the connection timeout.
- ///
- /// The connection timeout.
- public TimeSpan ConnectionTimeout { get; set; }
-
- ///
- /// Gets or sets a value indicating whether connection is pooled.
- ///
- /// true if pooled; otherwise, false.
- public bool Pooled { get; set; }
-
- ///
- /// Parses the specified connection string.
- ///
- /// The connection string.
- private void Parse (string connectionString){
- if (connectionString == null)
- throw new ArgumentNullException ("connectionString");
-
- var segments = connectionString.Split (';');
-
- foreach (var segment in segments) {
- var pairMatch = PairRegex.Match (segment);
- if (!pairMatch.Success)
- throw new FormatException (string.Format ("Invalid connection string on: {0}", pairMatch.Value));
-
- var key = pairMatch.Groups[1].Value;
- var value = pairMatch.Groups[2].Value;
-
- switch (key) {
- case "Username":
- case "User Id":
- case "User":
- {
- Username = value;
- break;
- }
- case "Password":
- {
- Password = value;
- break;
- }
- case "Pooled":
- {
- try {
- Pooled = bool.Parse(value);
- } catch(FormatException exception) {
- throw new FormatException("Invalid string for Pooled in connection string", exception);
- }
- break;
- }
- case "MaximumPoolSize":
- case "Max Pool Size":
- {
- try {
- MaximumPoolSize = int.Parse (value);
- } catch (FormatException exception) {
- throw new FormatException ("Invalid number for MaximumPoolSize in connection string", exception);
- }
- break;
- }
- case "MinimumPoolSize":
- case "Min Pool Size":
- {
- try {
- MinimumPoolSize = int.Parse (value);
- } catch (FormatException exception) {
- throw new FormatException ("Invalid number for MinimumPoolSize in connection string", exception);
- }
- break;
- }
- case "ConnectionLifetime":
- case "Connection Lifetime":
- {
- try {
- var seconds = double.Parse (value);
-
- ConnectionLifetime = seconds > 0 ? TimeSpan.FromSeconds (seconds) : DefaultConnectionLifeTime;
- } catch (FormatException exception) {
- throw new FormatException ("Invalid number for ConnectionLifetime in connection string", exception);
- }
- break;
- }
- case "ConnectionTimeout":
- case "ConnectTimeout":
- {
- try {
- var seconds = double.Parse(value);
-
- ConnectionTimeout = seconds > 0 ? TimeSpan.FromSeconds(seconds) : DefaultConnectionTimeout;
- } catch(FormatException exception) {
- throw new FormatException("Invalid number for ConnectionTimeout in connection string", exception);
- }
- break;
- }
- case "Server":
- case "Servers":
- {
- var servers = value.Split (',');
-
- foreach (var server in servers) {
- var serverMatch = ServerRegex.Match (server);
- if (!serverMatch.Success)
- throw new FormatException (string.Format ("Invalid server in connection string: {0}", serverMatch.Value));
-
- var serverHost = serverMatch.Groups[1].Value;
-
- int port;
- if (int.TryParse (serverMatch.Groups[2].Value, out port))
- AddServer (serverHost, port);
- else
- AddServer (serverHost);
- }
-
- break;
- }
- default:
- throw new FormatException (string.Format ("Unknown connection string option: {0}", key));
- }
- }
- }
-
- ///
- /// Adds the server.
- ///
- /// The end point.
- public void AddServer (MongoServerEndPoint endPoint){
- if (endPoint == null)
- throw new ArgumentNullException ("endPoint");
-
- _servers.Add (endPoint);
- }
-
- ///
- /// Clears the servers.
- ///
- public void ClearServers (){
- _servers.Clear ();
- }
-
- ///
- /// Adds the server with the given host and default port.
- ///
- /// The host.
- public void AddServer (string host){
- AddServer (new MongoServerEndPoint (host));
- }
-
- ///
- /// Adds the server with the given host and port.
- ///
- /// The host.
- /// The port.
- public void AddServer (string host, int port){
- AddServer (new MongoServerEndPoint (host, port));
- }
-
- ///
- /// Returns a
- ///
- /// that represents this instance.
- ///
- /// A
- ///
- /// that represents this instance.
- public override string ToString (){
- var builder = new StringBuilder ();
-
- if (!string.IsNullOrEmpty (Username)) {
- builder.AppendFormat ("Username={0}", Username);
- builder.Append (';');
- }
-
- if (!string.IsNullOrEmpty (Password)) {
- builder.AppendFormat ("Password={0}", Password);
- builder.Append (';');
- }
-
- if (_servers.Count > 0) {
- builder.Append ("Server=");
-
- foreach (var server in _servers) {
- builder.Append (server.Host);
-
- if (server.Port != MongoServerEndPoint.DefaultPort)
- builder.AppendFormat (":{0}", server.Port);
-
- builder.Append (',');
- }
-
- // remove last ,
- builder.Remove (builder.Length - 1, 1);
-
- builder.Append (';');
- }
-
- if(Pooled!=true){
- builder.AppendFormat("Pooled={0}", Pooled);
- builder.Append(';');
- }
-
- if (MaximumPoolSize != DefaultMaximumPoolSize) {
- builder.AppendFormat ("MaximumPoolSize={0}", MaximumPoolSize);
- builder.Append (';');
- }
-
- if (MinimumPoolSize != DefaultMinimumPoolSize) {
- builder.AppendFormat ("MinimumPoolSize={0}", MinimumPoolSize);
- builder.Append (';');
- }
-
- if (ConnectionTimeout != DefaultConnectionTimeout) {
- builder.AppendFormat("ConnectionTimeout={0}", ConnectionTimeout.TotalSeconds);
- builder.Append(';');
- }
-
- if (ConnectionLifetime != DefaultConnectionLifeTime) {
- builder.AppendFormat ("ConnectionLifetime={0}", ConnectionLifetime.TotalSeconds);
- builder.Append (';');
- }
-
- // remove last ;
- if (builder.Length > 0)
- builder.Remove (builder.Length - 1, 1);
-
- return builder.ToString ();
- }
- }
-}
diff --git a/MongoDBDriver/MongoDB.Driver.csproj b/MongoDBDriver/MongoDB.Driver.csproj
deleted file mode 100644
index ad831764..00000000
--- a/MongoDBDriver/MongoDB.Driver.csproj
+++ /dev/null
@@ -1,161 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}
- Library
- MongoDB.Driver
- C:\Documents and Settings\scorder\Application Data\ICSharpCode/SharpDevelop3.0\Settings.SourceAnalysis
- True
- False
- False
- false
-
-
- 2.0
-
-
- publish\
- true
- Disk
- false
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- false
- false
- true
- v2.0
- MongoDB.Driver
-
-
- true
- full
- false
- bin\Debug
- DEBUG TRACE
- prompt
- 4
- false
-
-
- none
- false
- bin\Release
- prompt
- 4
- false
-
-
- False
-
-
- False
- Auto
- 4194304
- AnyCPU
- 4096
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- False
-
-
- False
-
-
- False
-
-
- False
-
-
- False
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/MongoDBDriver/MongoRegex.cs b/MongoDBDriver/MongoRegex.cs
deleted file mode 100644
index 1f0af882..00000000
--- a/MongoDBDriver/MongoRegex.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-namespace MongoDB.Driver
-{
- public class MongoRegex
- {
- ///
- /// A valid regex string including the enclosing / characters.
- ///
- public string Expression {get; set;}
-
- ///
- /// A string that may contain only the characters 'g', 'i', and 'm'.
- /// Because the JS and TenGen representations support a limited range of options,
- /// any nonconforming options will be dropped when converting to this representation
- ///
- public string Options {get;set;}
-
- ///
- /// Initializes a new instance of the class.
- ///
- public MongoRegex(){}
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The expression.
- public MongoRegex(string expression):this(expression,string.Empty){}
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The expression.
- /// The options.
- public MongoRegex(string expression, string options){
- this.Expression = expression;
- this.Options = options;
- }
-
- ///
- /// Returns a that represents this instance.
- ///
- ///
- /// A that represents this instance.
- ///
- public override string ToString (){
- return string.Format("{0}{1}", Expression, Options);
- }
- }
-}
diff --git a/MongoDBDriver/MongoServerEndPoint.cs b/MongoDBDriver/MongoServerEndPoint.cs
deleted file mode 100644
index b8332d36..00000000
--- a/MongoDBDriver/MongoServerEndPoint.cs
+++ /dev/null
@@ -1,72 +0,0 @@
-using System;
-using System.Net;
-
-namespace MongoDB.Driver
-{
- ///
- /// Represents a mongodb server with host and port.
- ///
- [Serializable]
- public class MongoServerEndPoint : EndPoint
- {
- public const string DefaultHost = "localhost";
- public const int DefaultPort = 27017;
-
- ///
- /// The default MongoServerEndPoint.
- ///
- public static readonly MongoServerEndPoint Default = new MongoServerEndPoint();
-
- ///
- /// Initializes a new instance of the class.
- ///
- public MongoServerEndPoint()
- : this(DefaultHost, DefaultPort)
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The host.
- public MongoServerEndPoint(string host)
- : this(host, DefaultPort)
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The port.
- public MongoServerEndPoint(int port)
- : this(DefaultHost, port)
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The host.
- /// The port.
- public MongoServerEndPoint(string host, int port)
- {
- if(host == null)
- throw new ArgumentNullException("host");
-
- Host = host;
- Port = port;
- }
-
- ///
- /// Gets or sets the host.
- ///
- /// The host.
- public string Host { get; private set; }
-
- ///
- /// Gets or sets the port.
- ///
- /// The port.
- public int Port { get; private set; }
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/Oid.cs b/MongoDBDriver/Oid.cs
deleted file mode 100644
index 3c966497..00000000
--- a/MongoDBDriver/Oid.cs
+++ /dev/null
@@ -1,173 +0,0 @@
-using System;
-using System.Text.RegularExpressions;
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver{
-
- ///
- /// Oid is an immutable object that represents a Mongo ObjectId.
- ///
- public class Oid: IEquatable, IComparable
- {
- private static OidGenerator oidGenerator = new OidGenerator();
-
- private byte[] bytes;
-
- ///
- /// Gets the created.
- ///
- /// The created.
- public DateTime Created{
- get{
- byte[] time = new byte[4];
- Array.Copy(bytes,time,4);
- Array.Reverse(time);
- int seconds = BitConverter.ToInt32(time,0);
- return BsonInfo.Epoch.AddSeconds(seconds);
- }
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The value.
- public Oid(string value){
- value = value.Replace("\"", "");
- ValidateHex(value);
- bytes = DecodeHex(value);
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The value.
- public Oid(byte[] value){
- bytes = new byte[12];
- Array.Copy(value,bytes,12);
- }
-
-
- ///
- /// Determines whether the specified is equal to this instance.
- ///
- /// The to compare with this instance.
- ///
- /// true if the specified is equal to this instance; otherwise, false.
- ///
- public override bool Equals(object obj){
- if(obj is Oid){
- return this.CompareTo((Oid)obj) == 0;
- }
- return false;
- }
-
- public bool Equals (Oid other){
- return this.CompareTo(other) == 0;
- }
-
- public int CompareTo (Oid other){
- if (System.Object.ReferenceEquals(other, null)){
- return 1;
- }
- byte[] otherBytes = other.ToByteArray();
- for(int x = 0; x < bytes.Length; x++){
- if(bytes[x] < otherBytes[x]){
- return -1;
- }else if(bytes[x] > otherBytes[x]){
- return 1;
- }
- }
- return 0;
- }
-
- ///
- /// Returns a hash code for this instance.
- ///
- ///
- /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
- ///
- public override int GetHashCode(){
- return ToString().GetHashCode();
- }
-
- ///
- /// Returns a that represents this instance.
- ///
- ///
- /// A that represents this instance.
- ///
- public override string ToString() {
- return String.Format("\"{0}\"",BitConverter.ToString(bytes).Replace("-","").ToLower());
- }
-
- ///
- /// Converts the Oid to a byte array.
- ///
- public byte[] ToByteArray(){
- byte[] ret = new byte[12];
- Array.Copy(bytes, ret,12);
- return ret;
- }
-
- ///
- /// Generates an Oid using OidGenerator.
- ///
- ///
- /// A
- ///
- public static Oid NewOid(){
- return oidGenerator.Generate();
- }
-
- public static bool operator ==(Oid a, Oid b){
- return a.Equals(b);
- }
-
- public static bool operator !=(Oid a, Oid b){
- return !(a == b);
- }
-
- public static bool operator >(Oid a, Oid b){
- return a.CompareTo(b) > 0;
- }
-
- public static bool operator <(Oid a, Oid b){
- return a.CompareTo(b) < 0;
- }
-
-
- ///
- /// Validates the hex.
- ///
- /// The value.
- protected void ValidateHex(string value){
- if(value == null || value.Length != 24) throw new ArgumentException("Oid strings should be 24 characters");
-
- Regex notHexChars = new Regex(@"[^A-Fa-f0-9]", RegexOptions.None);
- if(notHexChars.IsMatch(value)){
- throw new ArgumentOutOfRangeException("value","Value contains invalid characters");
- }
- }
-
- ///
- /// Decodes the hex.
- ///
- /// The value.
- ///
- protected static byte[] DecodeHex(string value){
- int numberChars = value.Length;
-
- byte[] bytes = new byte[numberChars / 2];
- for (int i = 0; i < numberChars; i += 2){
- try{
- bytes[i / 2] = Convert.ToByte(value.Substring(i, 2), 16);
- }
- catch{
- //failed to convert these 2 chars, they may contain illegal charracters
- bytes[i / 2] = 0;
- }
- }
- return bytes;
- }
- }
-}
diff --git a/MongoDBDriver/OidGenerator.cs b/MongoDBDriver/OidGenerator.cs
deleted file mode 100644
index eb4955fd..00000000
--- a/MongoDBDriver/OidGenerator.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-
-using System;
-using System.Diagnostics;
-using System.Security.Cryptography;
-using System.Text;
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver
-{
- public class OidGenerator
- {
- private int inc;
- private object inclock = new object();
- private byte[] machineHash;
- private byte[] procID;
-
- ///
- /// Initializes a new instance of the class.
- ///
- public OidGenerator(){
- GenerateConstants();
- }
-
- ///
- /// Generates this instance.
- ///
- ///
- public Oid Generate(){
- //FIXME Endian issues with this code.
- //.Net runs in native endian mode which is usually little endian.
- //Big endian machines don't need the reversing (Linux+PPC, XNA on XBox)
- byte[] oid = new byte[12];
- int copyidx = 0;
-
- byte[] time = BitConverter.GetBytes(GenerateTime());
- Array.Reverse(time);
- Array.Copy(time,0,oid,copyidx,4);
- copyidx += 4;
-
- Array.Copy(machineHash,0,oid,copyidx,3);
- copyidx += 3;
-
- Array.Copy(this.procID,2,oid,copyidx,2);
- copyidx += 2;
-
- byte[] inc = BitConverter.GetBytes(GenerateInc());
- Array.Reverse(inc);
- Array.Copy(inc,1,oid,copyidx,3);
-
- return new Oid(oid);
- }
-
- ///
- /// Generates the time.
- ///
- ///
- private int GenerateTime(){
- DateTime now = DateTime.UtcNow;
- //DateTime nowtime = new DateTime(epoch.Year, epoch.Month, epoch.Day, now.Hour, now.Minute, now.Second, now.Millisecond);
- TimeSpan diff = now - BsonInfo.Epoch;
- return Convert.ToInt32(Math.Floor(diff.TotalSeconds));
- }
-
- ///
- /// Generates the inc.
- ///
- ///
- private int GenerateInc(){
- lock(this.inclock){
- return ++inc;
- }
- }
-
- ///
- /// Generates the constants.
- ///
- private void GenerateConstants(){
- this.machineHash = GenerateHostHash();
- this.procID = BitConverter.GetBytes(GenerateProcId());
- Array.Reverse(this.procID);
- }
-
- ///
- /// Generates the host hash.
- ///
- ///
- private byte[] GenerateHostHash(){
- MD5 md5 = MD5.Create();
- string host = System.Net.Dns.GetHostName();
- return md5.ComputeHash(Encoding.Default.GetBytes(host));
- }
-
- ///
- /// Generates the proc id.
- ///
- ///
- private int GenerateProcId(){
- Process proc = Process.GetCurrentProcess();
- return proc.Id;
- }
- }
-}
diff --git a/MongoDBDriver/Protocol/DeleteMessage.cs b/MongoDBDriver/Protocol/DeleteMessage.cs
deleted file mode 100644
index abd75aaa..00000000
--- a/MongoDBDriver/Protocol/DeleteMessage.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * User: scorder
- */
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver.Protocol
-{
- ///
- ///
- ///
- ///
- /// struct {
- /// MsgHeader header; // standard message header
- /// int32 ZERO; // 0 - reserved for future use
- /// cstring fullCollectionName; // "dbname.collectionname"
- /// int32 ZERO; // 0 - reserved for future use
- /// BSON selector; // query object. See below for details.
- /// }
- ///
- public class DeleteMessage : RequestMessageBase
- {
- public string FullCollectionName { get; set; }
-
- public Document Selector { get; set; }
-
- public DeleteMessage(){
- this.Header = new MessageHeader(OpCode.Delete);
- }
-
- protected override void WriteBody (BsonWriter writer){
- writer.WriteValue(BsonDataType.Integer,0);
- writer.WriteString(this.FullCollectionName);
- writer.WriteValue(BsonDataType.Integer,0);
- writer.Write(this.Selector);
- }
-
- protected override int CalculateBodySize(BsonWriter writer){
- int size = 8; //first int32, second int32
- size += writer.CalculateSize(this.FullCollectionName,false);
- size += writer.CalculateSize(Selector);
- return size;
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/Protocol/GetMoreMessage.cs b/MongoDBDriver/Protocol/GetMoreMessage.cs
deleted file mode 100644
index 5582d8df..00000000
--- a/MongoDBDriver/Protocol/GetMoreMessage.cs
+++ /dev/null
@@ -1,51 +0,0 @@
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver.Protocol
-{
- ///
- /// Description of GetMoreMessage.
- ///
- ///
- /// struct {
- /// MsgHeader header; // standard message header
- /// int32 ZERO; // 0 - reserved for future use
- /// cstring fullCollectionName; // "dbname.collectionname"
- /// int32 numberToReturn; // number of documents to return
- /// int64 cursorID; // cursorID from the OP_REPLY
- /// }
- ///
- public class GetMoreMessage : RequestMessageBase
- {
- public long CursorID { get; set; }
-
- public string FullCollectionName { get; set; }
-
- public int NumberToReturn { get; set; }
-
- public GetMoreMessage(string fullCollectionName, long cursorID)
- :this(fullCollectionName, cursorID, 0){
- }
-
- public GetMoreMessage(string fullCollectionName, long cursorID, int numberToReturn){
- this.Header = new MessageHeader(OpCode.GetMore);
- this.FullCollectionName = fullCollectionName;
- this.CursorID = cursorID;
- this.NumberToReturn = numberToReturn;
- }
-
- protected override void WriteBody (BsonWriter writer){
- writer.WriteValue(BsonDataType.Integer,0);
- writer.WriteString(this.FullCollectionName);
- writer.WriteValue(BsonDataType.Integer,this.NumberToReturn);
- writer.WriteValue(BsonDataType.Long,this.CursorID);
- }
-
- protected override int CalculateBodySize(BsonWriter writer){
- int size = 4; //first int32
- size += writer.CalculateSize(this.FullCollectionName,false);
- size += 12; //number to return + cursorid
- return size;
- }
-
- }
-}
diff --git a/MongoDBDriver/Protocol/IRequestMessage.cs b/MongoDBDriver/Protocol/IRequestMessage.cs
deleted file mode 100644
index 93605fca..00000000
--- a/MongoDBDriver/Protocol/IRequestMessage.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using System.IO;
-
-namespace MongoDB.Driver.Protocol
-{
- ///
- /// A Message that is to be written to the database.
- ///
- public interface IRequestMessage
- {
- void Write (Stream stream);
- }
-}
diff --git a/MongoDBDriver/Protocol/InsertMessage.cs b/MongoDBDriver/Protocol/InsertMessage.cs
deleted file mode 100644
index a6943836..00000000
--- a/MongoDBDriver/Protocol/InsertMessage.cs
+++ /dev/null
@@ -1,107 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver.Protocol
-{
- ///
- /// Description of InsertMessage.
- ///
- ///
- /// MsgHeader header; // standard message header
- /// int32 ZERO; // 0 - reserved for future use
- /// cstring fullCollectionName; // "dbname.collectionname"
- /// BSON[] documents; // one or more documents to insert into the collection
- ///
- public class InsertMessage : MessageBase, IRequestMessage
- {
- protected struct MessageChunk{
- public int Size;
- public List Documents;
- }
-
- public string FullCollectionName { get; set; }
-
- public Document[] Documents { get; set; }
-
- private List chunks = new List();
-
- public InsertMessage(){
- this.Header = new MessageHeader(OpCode.Insert);
- }
-
- public void Write (Stream stream){
- MessageHeader header = this.Header;
- BufferedStream bstream = new BufferedStream(stream);
-
- BsonWriter bwriter = new BsonWriter(bstream);
- ChunkMessage(bwriter);
-
- foreach(MessageChunk chunk in chunks){
- WriteChunk(bstream, chunk);
- }
- }
-
- ///
- /// Breaks down an insert message that may be too large into managable sizes.
- /// When inserting only one document there will be only one chunk. However chances
- /// are that when inserting thousands of documents at once there will be many.
- ///
- protected void ChunkMessage(BsonWriter writer){
- int baseSize = CalculateBaseSize(writer);
-
- MessageChunk chunk = new MessageChunk(){Size = baseSize, Documents = new List()};
- foreach(Document doc in this.Documents){
- int docSize = writer.CalculateSize(doc);
- if(docSize + baseSize >= MessageBase.MaximumMessageSize) throw new MongoException("Document is too big to fit in a message.");
-
- if(docSize + chunk.Size > MessageBase.MaximumMessageSize){
- chunks.Add(chunk);
- chunk = new MessageChunk(){Size = baseSize, Documents = new List()};
- }
- chunk.Documents.Add(doc);
- chunk.Size += docSize;
- }
- chunks.Add(chunk);
- }
-
- ///
- /// The base size that all chunks will have.
- ///
- protected int CalculateBaseSize(BsonWriter writer){
- int size = 4; //first int32
- size += writer.CalculateSize(this.FullCollectionName,false);
- size += Header.MessageLength;
- return size;
- }
-
- ///
- /// Writes out a header and the chunk of documents.
- ///
- ///
- ///
- protected void WriteChunk (Stream stream, MessageChunk chunk){
- WriteHeader(new BinaryWriter(stream), chunk.Size);
-
- BsonWriter writer = new BsonWriter(stream);
- writer.WriteValue(BsonDataType.Integer,0);
- writer.WriteString(this.FullCollectionName);
-
- foreach(Document doc in chunk.Documents){
- writer.Write(doc);
- }
- writer.Flush();
- }
-
- protected void WriteHeader(BinaryWriter writer, int msgSize){
- MessageHeader header = this.Header;
- writer.Write(msgSize);
- writer.Write(header.RequestId);
- writer.Write(header.ResponseTo);
- writer.Write((int)header.OpCode);
- writer.Flush();
- }
- }
-}
diff --git a/MongoDBDriver/Protocol/KillCursorsMessage.cs b/MongoDBDriver/Protocol/KillCursorsMessage.cs
deleted file mode 100644
index 29eeb3f2..00000000
--- a/MongoDBDriver/Protocol/KillCursorsMessage.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver.Protocol
-{
- ///
- /// Description of KillCursorsMessage.
- ///
- ///
- /// struct {
- /// MsgHeader header; // standard message header
- /// int32 ZERO; // 0 - reserved for future use
- /// int32 numberOfCursorIDs; // number of cursorIDs in message
- /// int64[] cursorIDs; // array of cursorIDs to close
- /// }
- ///
- public class KillCursorsMessage:RequestMessageBase
- {
- public long[] CursorIDs { get; set; }
-
- public KillCursorsMessage(){
- this.Header = new MessageHeader(OpCode.KillCursors);
- }
-
- public KillCursorsMessage(long cursorID):this(){
- this.CursorIDs = new long[]{cursorID};
- }
-
- public KillCursorsMessage(long[] cursorIDs):this(){
- this.CursorIDs = cursorIDs;
- }
-
- protected override void WriteBody (BsonWriter writer){
- writer.WriteValue(BsonDataType.Integer,0);
- writer.WriteValue(BsonDataType.Integer, this.CursorIDs.Length);
-
- foreach(long id in this.CursorIDs){
- writer.WriteValue(BsonDataType.Long, id);
- }
- }
-
- protected override int CalculateBodySize(BsonWriter writer){
- int size = 8; //first int32, number of cursors
- foreach(long id in this.CursorIDs){
- size += 8;
- }
- return size;
- }
- }
-}
diff --git a/MongoDBDriver/Protocol/MessageBase.cs b/MongoDBDriver/Protocol/MessageBase.cs
deleted file mode 100644
index 94775b4c..00000000
--- a/MongoDBDriver/Protocol/MessageBase.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-namespace MongoDB.Driver.Protocol
-{
- ///
- /// Base class for all raw messages
- ///
- public abstract class MessageBase
- {
- public static int MaximumMessageSize = 1024 * 1024 * 4;
-
- public MessageHeader Header { get; set; }
- }
-}
diff --git a/MongoDBDriver/Protocol/MessageHeader.cs b/MongoDBDriver/Protocol/MessageHeader.cs
deleted file mode 100644
index 50f9ae2f..00000000
--- a/MongoDBDriver/Protocol/MessageHeader.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * User: scorder
- * Date: 7/7/2009
- */
-using System;
-
-namespace MongoDB.Driver.Protocol
-{
///
- /// In general, each Message consists of a standard message header followed by request-specific data.
- ///
- public class MessageHeader
- {
- // total size of the message, including the 4 bytes of length
- public int MessageLength { get; set; }
-
- // client or database-generated identifier for this message
- public int RequestId { get; set; }
-
- // requestID from the original request (used in reponses from db)
- public int ResponseTo { get; set; }
-
- // request type - see table below
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", MessageId = "Member")]
- public OpCode OpCode { get; set; }
-
- public MessageHeader(OpCode opCode)
- {
- this.OpCode = opCode;
- this.MessageLength = 16; //The starting size of any message.
- }
-
- public override String ToString(){
- return "length:" + this.MessageLength + " requestId:" + this.RequestId + " responseTo:" + this.ResponseTo + " opCode:" + this.OpCode;
- }
-
- }
-}
diff --git a/MongoDBDriver/Protocol/MsgMessage.cs b/MongoDBDriver/Protocol/MsgMessage.cs
deleted file mode 100644
index 5e602a34..00000000
--- a/MongoDBDriver/Protocol/MsgMessage.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver.Protocol
-{
- ///
- ///
- ///
- ///
- /// struct {
- /// MsgHeader header; // standard message header
- /// cstring message; // message for the database
- /// }
- ///
- public class MsgMessage : RequestMessageBase
- {
- public string Message { get; set; }
-
- public MsgMessage(){
- this.Header = new MessageHeader(OpCode.Msg);
- }
-
- protected override void WriteBody (BsonWriter writer){
- writer.WriteString(this.Message);
- }
-
- protected override int CalculateBodySize(BsonWriter writer){
- return writer.CalculateSize(this.Message,false);
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/Protocol/OpCode.cs b/MongoDBDriver/Protocol/OpCode.cs
deleted file mode 100644
index b72a475e..00000000
--- a/MongoDBDriver/Protocol/OpCode.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-namespace MongoDB.Driver.Protocol
-{
- public enum OpCode{
- Reply = 1, //Reply to a client request. responseTo is set
- Msg = 1000, //generic msg command followed by a string
- Update = 2001, //update document
- Insert = 2002, //insert new document
- GetByOID = 2003, //is this used?
- Query = 2004, //query a collection
- GetMore = 2005, //Get more data from a query. See Cursors
- Delete = 2006, //Delete documents
- KillCursors = 2007 //Tell database client is done with a cursor
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/Protocol/QueryMessage.cs b/MongoDBDriver/Protocol/QueryMessage.cs
deleted file mode 100644
index 8da95823..00000000
--- a/MongoDBDriver/Protocol/QueryMessage.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-using System;
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver.Protocol
-{
- ///
- /// Description of QueryMessage.
- ///
- ///
- /// MsgHeader header; // standard message header
- /// int32 opts; // query options. See QueryOptions for values
- /// cstring fullCollectionName; // "dbname.collectionname"
- /// int32 numberToSkip; // number of documents to skip when returning results
- /// int32 numberToReturn; // number of documents to return in the first OP_REPLY
- /// BSON query ; // query object. See below for details.
- /// [ BSON returnFieldSelector; ] // OPTIONAL : selector indicating the fields to return. See below for details.
- ///
- public class QueryMessage : RequestMessageBase
- {
- public QueryOptions Options { get; set; }
-
- public string FullCollectionName { get; set; }
-
- public int NumberToSkip { get; set; }
-
- public int NumberToReturn { get; set; }
-
- public Document Query { get; set; }
-
- public Document ReturnFieldSelector { get; set; }
-
- public QueryMessage(){
- this.Header = new MessageHeader(OpCode.Query);
- }
-
- public QueryMessage(Document query, String fullCollectionName)
- :this(query,fullCollectionName,0,0){
- }
-
- public QueryMessage(Document query, String fullCollectionName, Int32 numberToReturn, Int32 numberToSkip)
- :this(query,fullCollectionName,numberToReturn, numberToSkip, null){
- }
-
- public QueryMessage(Document query, String fullCollectionName, Int32 numberToReturn,
- Int32 numberToSkip, Document returnFieldSelector){
- this.Header = new MessageHeader(OpCode.Query);
- this.Query = query;
- this.FullCollectionName = fullCollectionName;
- this.NumberToReturn = numberToReturn;
- this.NumberToSkip = numberToSkip;
- this.ReturnFieldSelector = returnFieldSelector;
- }
-
- protected override void WriteBody (BsonWriter writer){
- writer.WriteValue(BsonDataType.Integer,(int)this.Options);
- writer.WriteString(this.FullCollectionName);
- writer.WriteValue(BsonDataType.Integer,(int)this.NumberToSkip);
- writer.WriteValue(BsonDataType.Integer,(int)this.NumberToReturn);
- writer.Write(this.Query);
- if(this.ReturnFieldSelector != null){
- writer.Write(this.ReturnFieldSelector);
- }
- }
-
- protected override int CalculateBodySize(BsonWriter writer){
- int size = 12; //options, numbertoskip, numbertoreturn
- size += writer.CalculateSize(this.FullCollectionName,false);
- size += writer.CalculateSize(this.Query);
- if(this.ReturnFieldSelector != null){
- size += writer.CalculateSize(this.ReturnFieldSelector);
- }
- return size;
- }
- }
-}
diff --git a/MongoDBDriver/Protocol/ReplyMessage.cs b/MongoDBDriver/Protocol/ReplyMessage.cs
deleted file mode 100644
index 1ee0159c..00000000
--- a/MongoDBDriver/Protocol/ReplyMessage.cs
+++ /dev/null
@@ -1,95 +0,0 @@
-using System.Collections.Generic;
-using System.IO;
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver.Protocol
-{
- public class ReplyMessage:MessageBase
- {
- // normally zero, non-zero on query failure
- public int ResponseFlag { get; set; }
-
- // id of the cursor created for this query response
- public long CursorID { get; set; }
-
- // indicates where in the cursor this reply is starting
- public int StartingFrom { get; set; }
-
- // number of documents in the reply
- public int NumberReturned { get; set; }
-
- public Document[] Documents { get; set; }
-
- public void Read(Stream stream){
- stream = new BufferedStream(stream, 256);
- BinaryReader reader = new BinaryReader(stream);
- this.Header = ReadHeader(reader);
- this.ResponseFlag = reader.ReadInt32();
- this.CursorID = reader.ReadInt64();
- this.StartingFrom = reader.ReadInt32();
- this.NumberReturned = reader.ReadInt32();
-
- BsonReader breader = new BsonReader(stream);
- List docs = new List();
- for(int num = 0; num < this.NumberReturned; num++){
- docs.Add(breader.Read());
- }
- this.Documents = docs.ToArray();
- }
-
- protected MessageHeader ReadHeader(BinaryReader reader){
- MessageHeader hdr = new MessageHeader(OpCode.Reply);
- hdr.MessageLength = reader.ReadInt32();
- hdr.RequestId = reader.ReadInt32();
- hdr.ResponseTo = reader.ReadInt32();
- int op = reader.ReadInt32();
- if((OpCode)op != OpCode.Reply) throw new InvalidDataException("Should have been a reply but wasn't");
- return hdr;
- }
-
-// public void Read(Stream stream){
-// /* Used during debugging of the stream.
-// BsonReader headerreader = new BsonReader(stream);
-// this.Header = ReadHeader(headerreader);
-//
-// //buffer the whole response into a memorystream for debugging.
-// MemoryStream buffer = new MemoryStream();
-// BinaryReader buffReader = new BinaryReader(stream);
-// BinaryWriter buffWriter = new BinaryWriter(buffer);
-// byte[] body = buffReader.ReadBytes(this.Header.MessageLength - 16);
-// System.Console.WriteLine(BitConverter.ToString(body));
-// buffWriter.Write(body);
-// buffer.Seek(0, SeekOrigin.Begin);
-//
-// BsonReader reader = new BsonReader(buffer);*/
-//
-// //BsonReader reader = new BsonReader(stream);
-// //BsonReader reader = new BsonReader(new BufferedStream(stream));
-// BsonReader reader = new BsonReader(new BufferedStream(stream, 4 * 1024));
-// this.Header = ReadHeader(reader);
-//
-// this.ResponseFlag = reader.ReadInt32();
-// this.CursorID = reader.ReadInt64();
-// this.StartingFrom = reader.ReadInt32();
-// this.NumberReturned = reader.ReadInt32();
-//
-// List docs = new List();
-// for(int num = 0; num < this.NumberReturned; num++){
-// BsonDocument doc = new BsonDocument();
-// doc.Read(reader);
-// docs.Add(doc);
-// }
-// this.Documents = docs.ToArray();
-// }
-//
-// protected MessageHeader ReadHeader(BsonReader reader){
-// MessageHeader hdr = new MessageHeader(OpCode.Reply);
-// hdr.MessageLength = reader.ReadInt32();
-// hdr.RequestId = reader.ReadInt32();
-// hdr.ResponseTo = reader.ReadInt32();
-// int op = reader.ReadInt32();
-// if((OpCode)op != OpCode.Reply) throw new InvalidDataException("Should have been a reply but wasn't");
-// return hdr;
-// }
- }
-}
diff --git a/MongoDBDriver/Protocol/RequestMessageBase.cs b/MongoDBDriver/Protocol/RequestMessageBase.cs
deleted file mode 100644
index c29388ea..00000000
--- a/MongoDBDriver/Protocol/RequestMessageBase.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-using System.IO;
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver.Protocol
-{
- ///
- /// Description of Message.
- ///
- public abstract class RequestMessageBase : MessageBase, IRequestMessage
- {
- public void Write (Stream stream){
- MessageHeader header = this.Header;
- BufferedStream bstream = new BufferedStream(stream);
- BinaryWriter writer = new BinaryWriter(bstream);
- BsonWriter bwriter = new BsonWriter(bstream);
-
- Header.MessageLength += this.CalculateBodySize(bwriter);
- if(Header.MessageLength > MessageBase.MaximumMessageSize){
- throw new MongoException("Maximum message length exceeded");
- }
-
- writer.Write(header.MessageLength);
- writer.Write(header.RequestId);
- writer.Write(header.ResponseTo);
- writer.Write((int)header.OpCode);
- writer.Flush();
- WriteBody(bwriter);
- bwriter.Flush();
- }
-
- protected abstract void WriteBody(BsonWriter writer);
-
- protected abstract int CalculateBodySize(BsonWriter writer);
- }
-}
diff --git a/MongoDBDriver/Protocol/UpdateMessage.cs b/MongoDBDriver/Protocol/UpdateMessage.cs
deleted file mode 100644
index dfd4036b..00000000
--- a/MongoDBDriver/Protocol/UpdateMessage.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver.Protocol
-{
- ///
- ///
- ///
- ///
- /// struct {
- /// MsgHeader header; // standard message header
- /// int32 ZERO; // 0 - reserved for future use
- /// cstring fullCollectionName; // "dbname.collectionname"
- /// int32 flags; // value 0 for upsert 1 for multiupdate operation
- /// BSON selector; // the query to select the document
- /// BSON document; // the document data to update with or insert
- /// }
- ///
- public class UpdateMessage : RequestMessageBase
- {
- public string FullCollectionName { get; set; }
-
- public Document Selector { get; set; }
-
- public Document Document { get; set; }
-
- public int Flags { get; set; }
-
- public UpdateMessage(){
- this.Header = new MessageHeader(OpCode.Update);
- }
-
- protected override void WriteBody (BsonWriter writer){
- writer.WriteValue(BsonDataType.Integer,0);
- writer.WriteString(this.FullCollectionName);
- writer.WriteValue(BsonDataType.Integer,this.Flags);
- writer.Write(Selector);
- writer.Write(Document);
- }
-
- protected override int CalculateBodySize(BsonWriter writer){
- int size = 4; //first int32
- size += writer.CalculateSize(this.FullCollectionName,false);
- size += 4; //flags
- size += writer.CalculateSize(this.Selector);
- size += writer.CalculateSize(this.Document);
- return size;
- }
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/QueryOptions.cs b/MongoDBDriver/QueryOptions.cs
deleted file mode 100644
index 6b10bf33..00000000
--- a/MongoDBDriver/QueryOptions.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace MongoDB.Driver
-{
- public enum QueryOptions {
- None = 0,
- TailableCursor = 2,
- SlaveOK = 4,
- NoCursorTimeout = 16
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/UpdateFlags.cs b/MongoDBDriver/UpdateFlags.cs
deleted file mode 100644
index cb53e5e6..00000000
--- a/MongoDBDriver/UpdateFlags.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace MongoDB.Driver
-{
- public enum UpdateFlags {
- Upsert = 1,
- MultiUpdate = 2
- }
-}
\ No newline at end of file
diff --git a/MongoDBDriver/bin/Debug/.gitignore b/MongoDBDriver/bin/Debug/.gitignore
deleted file mode 100644
index 5d657c34..00000000
--- a/MongoDBDriver/bin/Debug/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-*.mdb
-
diff --git a/MongoDBDriver/bin/Debug/en/LC_MESSAGES/.mo b/MongoDBDriver/bin/Debug/en/LC_MESSAGES/.mo
deleted file mode 100644
index 1e036f81..00000000
Binary files a/MongoDBDriver/bin/Debug/en/LC_MESSAGES/.mo and /dev/null differ
diff --git a/MongoDBDriver2010.sln b/MongoDBDriver2010.sln
deleted file mode 100644
index 304f3550..00000000
--- a/MongoDBDriver2010.sln
+++ /dev/null
@@ -1,92 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 10.00
-# Visual Studio 2008
-# SharpDevelop 3.1.1.5327
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Driver", "MongoDBDriver\MongoDB.Driver.csproj", "{B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}"
-EndProject
-Project("{9344bdbb-3e7f-41fc-a0dd-8665d75ee146}") = "Packages", "Packages.mdproj", "{502F3381-58AA-461B-B9D8-12578A588C61}"
-EndProject
-Project("{9344bdbb-3e7f-41fc-a0dd-8665d75ee146}") = "MongoDBDriverTranslation", "MongoDBDriverTranslation\MongoDBDriverTranslation.mdproj", "{DCBE47DD-59A6-4212-AA4A-142838088B69}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Driver.Tests", "MongoDB.Net-Tests\MongoDB.Driver.Tests.csproj", "{C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Linq", "MongoDB.Linq\MongoDB.Linq.csproj", "{2E48891E-72F9-445D-9A5A-DBA787BFFE9E}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Linq.Tests", "MongoDB.Linq.Tests\MongoDB.Linq.Tests.csproj", "{870FE8E1-3461-4C79-BF25-9C35E41BF582}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Driver.Benchmark", "MongoDB.Driver.Benchmark\MongoDB.Driver.Benchmark.csproj", "{5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.GridFS", "MongoDB.GridFS\MongoDB.GridFS.csproj", "{B42DBBF9-0A1F-4749-9787-013BF8D8F435}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.GridFS.Tests", "MongoDB.GridFS.Tests\MongoDB.GridFS.Tests.csproj", "{0C293FE9-F670-4FEF-A60F-20F8C978B1CD}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Release|Any CPU = Release|Any CPU
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}.Release|Any CPU.Build.0 = Release|Any CPU
- {2E48891E-72F9-445D-9A5A-DBA787BFFE9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {2E48891E-72F9-445D-9A5A-DBA787BFFE9E}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {2E48891E-72F9-445D-9A5A-DBA787BFFE9E}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {2E48891E-72F9-445D-9A5A-DBA787BFFE9E}.Release|Any CPU.Build.0 = Release|Any CPU
- {502F3381-58AA-461B-B9D8-12578A588C61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {502F3381-58AA-461B-B9D8-12578A588C61}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {5ACD68A0-0F2E-452A-90E3-3D1CB82C055B}.Release|Any CPU.Build.0 = Release|Any CPU
- {870FE8E1-3461-4C79-BF25-9C35E41BF582}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {870FE8E1-3461-4C79-BF25-9C35E41BF582}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {870FE8E1-3461-4C79-BF25-9C35E41BF582}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {870FE8E1-3461-4C79-BF25-9C35E41BF582}.Release|Any CPU.Build.0 = Release|Any CPU
- {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}.Release|Any CPU.Build.0 = Release|Any CPU
- {B42DBBF9-0A1F-4749-9787-013BF8D8F435}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {B42DBBF9-0A1F-4749-9787-013BF8D8F435}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {B42DBBF9-0A1F-4749-9787-013BF8D8F435}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {B42DBBF9-0A1F-4749-9787-013BF8D8F435}.Release|Any CPU.Build.0 = Release|Any CPU
- {C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}.Release|Any CPU.Build.0 = Release|Any CPU
- {DCBE47DD-59A6-4212-AA4A-142838088B69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {DCBE47DD-59A6-4212-AA4A-142838088B69}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {DCBE47DD-59A6-4212-AA4A-142838088B69}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {DCBE47DD-59A6-4212-AA4A-142838088B69}.Release|Any CPU.Build.0 = Release|Any CPU
- {502F3381-58AA-461B-B9D8-12578A588C61}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {502F3381-58AA-461B-B9D8-12578A588C61}.Release|Any CPU.Build.0 = Release|Any CPU
- EndGlobalSection
- GlobalSection(MonoDevelopProperties) = preSolution
- StartupItem = MongoDBDriver\MongoDB.Driver.csproj
- Policies = $0
- $0.DotNetNamingPolicy = $1
- $1.DirectoryNamespaceAssociation = None
- $1.ResourceNamePolicy = FileFormatDefault
- $0.TextStylePolicy = $2
- $2.FileWidth = 120
- $2.TabWidth = 4
- $2.inheritsSet = Mono
- $2.inheritsScope = text/plain
- $2.scope = text/plain
- $0.TextStylePolicy = $3
- $3.FileWidth = 120
- $3.NoTabsAfterNonTabs = True
- $3.inheritsSet = VisualStudio
- $3.inheritsScope = text/plain
- $3.scope = text/x-csharp
- $0.CSharpFormattingPolicy = $4
- $4.inheritsSet = Mono
- $4.inheritsScope = text/x-csharp
- $4.scope = text/x-csharp
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
-EndGlobal
diff --git a/Packages.mdproj b/Packages.mdproj
deleted file mode 100644
index c7163d49..00000000
--- a/Packages.mdproj
+++ /dev/null
@@ -1,56 +0,0 @@
-
-
-
- PackagingProject
- 8.0.50727
- 2.0
- {502F3381-58AA-461B-B9D8-12578A588C61}
-
-
-
-
-
-
-
-
-
-
- MongoDB.Linq,ProgramFiles,MongoDB.Linq.dll.mdb
- MongoDB.Linq,ProgramFiles,MongoDB.Driver.dll.mdb
- MongoDB.GridFS,ProgramFiles,MongoDB.GridFS.dll.mdb
- MongoDB.GridFS,ProgramFiles,MongoDB.Driver.dll.mdb
- MongoDB.Driver,ProgramFiles,MongoDB.Driver.dll.mdb
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/README.rst b/README.rst
index 41fa7a6d..b913ec9d 100644
--- a/README.rst
+++ b/README.rst
@@ -41,7 +41,7 @@ Patches
=======
Patches are welcome and will likely be accepted. By submitting a patch you assign the copyright to me, Sam Corder. This is necessary to simplify the number of copyright holders should it become necessary that the copyright need to be reassigned or the code relicensed. The code will always be available under an OSI approved license.
-A bug fix patch should contain a test case that reproduces the issue along with the actual fix. Try to follow the same style that the code is already in so that things remain clean.
+A bug fix patch should contain a test case that reproduces the issue along with the actual fix. Try to follow the same style that the code is already in so that things remain clean. Keep your whitespace settings the same as the code to make reading and applying diffs manageable. We use 4 spaces for tabs and Windows line endings.
Usage
=====
@@ -62,15 +62,22 @@ Getting Help
============
The Google Group mongodb-csharp at (http://groups.google.com/group/mongodb-csharp) is the best place to go.
+Reporting Bugs
+==============
+The bug tracker is the same as the Mongodb bug tracker located at http://jira.mongodb.org
+
Contributors
============
- Sam Corder (samus)
+- Steve Wagner (lanwin)
+- Craig Wilson (craiggwilson)
- Seth Edwards (Sedward)
- Arne Classen (Sdether)
-- Steve Wagner (lanwin)
- Andrew Rondeau (GWBasic)
- Doug Mayer (dougtmayer)
- Andrew Kempe
- Kevin Smith (codebrulee)
- Rashadh (rashadh)
- Sergey Bartunov (sbos)
+- David O'Hara (davidmohara)
+- Tim Raybrun (trayburn)
diff --git a/StrongName.snk b/StrongName.snk
new file mode 100644
index 00000000..c5dfd6e3
Binary files /dev/null and b/StrongName.snk differ
diff --git a/examples/Simple/Main.cs b/examples/Simple/Main.cs
index 8539644b..237d2c4a 100644
--- a/examples/Simple/Main.cs
+++ b/examples/Simple/Main.cs
@@ -1,99 +1,186 @@
-using System;
-using System.Configuration;
-
-using MongoDB.Driver;
-
-namespace Simple
-{
- ///
- /// Illustrates some simple operations on the database.
- /// Creating a database connection.
- /// Remove some documents.
- /// Insert some documents
- /// Find one document
- /// Find several documents and iterate through them.
- ///
- class MainClass
- {
- Mongo mongo;
- Database simple;
- IMongoCollection categories;
-
- public static void Main (string[] args){
- MainClass main = new MainClass();
- main.Setup();
- main.Run();
- }
-
-
- ///
- /// Setup the collection and insert some data into it.
- ///
- public void Setup(){
- string connstr = ConfigurationManager.AppSettings["simple"];
- if(String.IsNullOrEmpty(connstr)) throw new ArgumentNullException("Connection string not found.");
- mongo = new Mongo(connstr);
- mongo.Connect();
- simple = mongo["simple"];
- categories = simple["categories"];
- Clean();
-
- var names = new string[]{"Bluez", "Jazz", "Classical", "Rock", "Oldies", "Heavy Metal"};
- foreach(string name in names){
- categories.Insert(new Document(){{"name", name}});
- }
- }
-
- public void Clean(){
- categories.Delete(new Document(){{"name", "Jazz"}}); //remove documents with the name Jazz.
- categories.Delete(new Document()); //remove everything from the categories collection.
- }
-
- public void Run(){
- var category = categories.FindOne(new Document { { "name", "Bluez" } });
-
- Console.WriteLine ("The id findOne" + category["_id"]);
-
- Document selector = new Document(){{"_id", category["_id"]}};
-
- category["name"] = "Bluess";
- //The following will do the same thing.
- categories.Update(category);
-
- Console.WriteLine("Category after one update " + categories.FindOne(selector).ToString());
-
- category["name"] = "Blues";
- categories.Update(category, selector);
-
- Console.WriteLine("Category after two updates " + categories.FindOne(selector).ToString());
-
- //Find it by _id that has been converted to a string now.
- string id = ((Oid)category["_id"]).ToString();
-
- Console.WriteLine("Found by string id converted back to Oid");
- Console.WriteLine(categories.FindOne(new Document(){{"_id", id.ToOid()}}));
-
- //Find(new Document()) is equivalent to FindAll();
- //Specifying the cursor in a using block will close it on the server if we decide not
- //to iterate through the whole thing.
- using(ICursor all = categories.Find(new Document())){
- foreach(Document doc in all.Documents){
- Console.WriteLine(doc.ToString());
- }
- }
-
- mongo.Disconnect();
- }
-
- }
-}
-
-public static class OidExtensions
-{
- public static Oid ToOid (this string str){
- if (str.Length == 24)
- return new Oid (str);
-
- return new Oid (str.Replace ("\"", ""));
- }
-}
+using System;
+using System.Configuration;
+using System.Linq;
+using MongoDB;
+using MongoDB.Configuration;
+using MongoDB.Linq;
+
+namespace Simple
+{
+ ///
+ /// Illustrates some simple operations on the database.
+ /// Creating a database connection.
+ /// Remove some documents.
+ /// Insert some documents
+ /// Find one document
+ /// Find several documents and iterate through them.
+ ///
+ internal class MainClass
+ {
+ private IMongoCollection categories;
+ private Mongo mongo;
+ private IMongoDatabase simple;
+
+ private class MyClass
+ {
+ public string Name { get; set; }
+ public int Corners { get; set; }
+ }
+
+ private class SubClass : MyClass
+ {
+ public double Ratio { get; set; }
+ }
+
+ public static void Main(string[] args)
+ {
+ var config = new MongoConfigurationBuilder();
+
+ // COMMENT OUT FROM HERE
+ config.Mapping(mapping =>
+ {
+ mapping.DefaultProfile(profile =>
+ {
+ profile.SubClassesAre(t => t.IsSubclassOf(typeof(MyClass)));
+ });
+ mapping.Map();
+ mapping.Map();
+ });
+ // TO HERE
+
+ config.ConnectionString("Server=127.0.0.1");
+
+ using (Mongo mongo = new Mongo(config.BuildConfiguration()))
+ {
+ mongo.Connect();
+ try
+ {
+ var db = mongo.GetDatabase("TestDb");
+ var collection = db.GetCollection();
+
+ MyClass square = new MyClass()
+ {
+ Corners = 4,
+ Name = "Square"
+ };
+
+ MyClass circle = new MyClass()
+ {
+ Corners = 0,
+ Name = "Circle"
+ };
+
+ SubClass sub = new SubClass()
+ {
+ Name = "SubClass",
+ Corners = 6,
+ Ratio = 3.43
+ };
+
+ collection.Save(square);
+ collection.Save(circle);
+ collection.Save(sub);
+
+ var superclass = (from item in db.GetCollection("MyClass").Linq()
+ where item.Corners > 1
+ select item.Corners).ToList();
+
+ var subclass = (from item in db.GetCollection("MyClass").Linq()
+ where item.Ratio > 1
+ select item.Corners).ToList();
+
+ Console.WriteLine("Count by LINQ on typed collection: {0}", collection.Linq().Count(x => x.Corners > 1));
+ Console.WriteLine("Count by LINQ on typed collection2: {0}", db.GetCollection().Linq().Count(x => x.Corners > 1));
+ //Console.WriteLine("Count by LINQ on typed collection3: {0}", db.GetCollection().Count(new { Corners = Op.GreaterThan(1) }));
+ Console.WriteLine("Count on typed collection: {0}", collection.Count(new { Corners = Op.GreaterThan(1) }));
+
+ var coll = db.GetCollection("MyClass");
+ var count = coll.Count(new Document("Corners", Op.GreaterThan(1)));
+ Console.WriteLine("Count: {0}", count);
+ Console.ReadKey();
+ }
+ finally
+ {
+ mongo.Disconnect();
+ }
+ }
+
+ //var main = new MainClass();
+ //main.Setup();
+ //main.Run();
+ }
+
+ ///
+ /// Setup the collection and insert some data into it.
+ ///
+ public void Setup()
+ {
+ var connstr = ConfigurationManager.AppSettings["simple"];
+ if(String.IsNullOrEmpty(connstr))
+ throw new ArgumentNullException("Connection string not found.");
+ mongo = new Mongo(connstr);
+ mongo.Connect();
+ simple = mongo["simple"];
+ categories = simple.GetCollection("categories");
+ Clean();
+
+ var names = new[] {"Bluez", "Jazz", "Classical", "Rock", "Oldies", "Heavy Metal"};
+ foreach(var name in names)
+ categories.Insert(new Document {{"name", name}});
+ }
+
+ public void Clean()
+ {
+ categories.Remove(new Document {{"name", "Jazz"}}); //remove documents with the name Jazz.
+ categories.Remove(new Document()); //remove everything from the categories collection.
+ }
+
+ public void Run()
+ {
+ var category = categories.FindOne(new Document {{"name", "Bluez"}});
+
+ Console.WriteLine("The id findOne" + category["_id"]);
+
+ var selector = new Document {{"_id", category["_id"]}};
+
+ category["name"] = "Bluess";
+ //The following will do the same thing.
+ categories.Save(category);
+
+ Console.WriteLine("Category after one update " + categories.FindOne(selector));
+
+ category["name"] = "Blues";
+ categories.Update(category, selector);
+
+ Console.WriteLine("Category after two updates " + categories.FindOne(selector));
+
+ //Find it by _id that has been converted to a string now.
+ var id = (category["_id"]).ToString();
+
+ Console.WriteLine("Found by string id converted back to Oid");
+ Console.WriteLine(categories.FindOne(new Document {{"_id", id.ToOid()}}));
+
+ //Find(new Document()) is equivalent to FindAll();
+ //Specifying the cursor in a using block will close it on the server if we decide not
+ //to iterate through the whole thing.
+ using(var all = categories.Find(new Document()))
+ {
+ foreach(var doc in all.Documents)
+ Console.WriteLine(doc.ToString());
+ }
+
+ mongo.Disconnect();
+ }
+ }
+}
+
+public static class OidExtensions
+{
+ public static Oid ToOid(this string str)
+ {
+ if(str.Length == 24)
+ return new Oid(str);
+
+ return new Oid(str.Replace("\"", ""));
+ }
+}
\ No newline at end of file
diff --git a/examples/Simple/Simple.csproj b/examples/Simple/Simple.csproj
index 692ab0e4..b6aa7839 100644
--- a/examples/Simple/Simple.csproj
+++ b/examples/Simple/Simple.csproj
@@ -1,15 +1,34 @@
-
+
Debug
AnyCPU
- 9.0.21022
+ 9.0.30729
2.0
{131BDB5F-5C6F-4AC7-B03E-394B1B75E120}
Exe
Simple
Simple
v3.5
+
+
+ 3.5
+
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ false
+ true
true
@@ -19,6 +38,7 @@
DEBUG
prompt
4
+ AllRules.ruleset
none
@@ -26,20 +46,22 @@
bin\Release
prompt
4
+ AllRules.ruleset
+
-
+
{B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}
- MongoDB.Driver
+ MongoDB
@@ -48,4 +70,21 @@
PreserveNewest
+
+
+ False
+ .NET Framework 3.5 SP1 Client Profile
+ false
+
+
+ False
+ .NET Framework 3.5 SP1
+ true
+
+
+ False
+ Windows Installer 3.1
+ true
+
+
\ No newline at end of file
diff --git a/examples/SimpleVB/Application.vb b/examples/SimpleVB/Application.vb
index f866cdc2..32e83e5f 100644
--- a/examples/SimpleVB/Application.vb
+++ b/examples/SimpleVB/Application.vb
@@ -1,7 +1,8 @@
imports System
imports System.Configuration
+Imports Microsoft.VisualBasic
-imports MongoDB.Driver
+Imports MongoDB
Namespace Simple
@@ -15,11 +16,12 @@ Namespace Simple
'''
Public Class Application
Private mongo as Mongo
- Private simple as Database
- Private categories as IMongoCollection
+ Private simple as IMongoDatabase
+ Private categories As IMongoCollection(Of Document)
Public Shared Sub Main()
Dim app As New Application()
+
app.Setup()
app.Run()
Console.WriteLine("Press any key to continue...")
@@ -35,30 +37,30 @@ Namespace Simple
mongo = new Mongo(connstr)
mongo.Connect()
simple = mongo("simple")
- categories = simple("categories")
+ categories = simple.GetCollection(Of Document)("categories")
Clean()
Dim names() As String = {"Bluez", "Jazz", "Classical", "Rock", "Oldies", "Heavy Metal"}
For Each name As string In names
- categories.Insert(new Document().Append("name", name))
+ categories.Insert(New Document().Add("name", name))
Next
End Sub
Public Sub Clean()
- categories.Delete(new Document().Append("name", "Jazz")) 'remove documents with the name Jazz.
- categories.Delete(new Document()) 'remove everything from the categories collection.
+ categories.Remove(New Document().Add("name", "Jazz")) 'remove documents with the name Jazz.
+ categories.Remove(New Document()) 'remove everything from the categories collection.
End Sub
Public Sub Run()
- Dim category As Document = categories.FindOne(new Document().Append("name", "Bluez"))
+ Dim category As Document = categories.FindOne(New Document().Add("name", "Bluez"))
Console.WriteLine ("The id findOne" & category("_id").ToString())
- Dim selector As Document = New Document().Append("_id", category("_id"))
+ Dim selector As Document = New Document().Add("_id", category("_id"))
category("name") = "Bluess"
'The following will do the same thing.
- categories.Update(category)
+ categories.Save(category)
Console.WriteLine("Category after one update " + categories.FindOne(selector).ToString())
@@ -71,12 +73,12 @@ Namespace Simple
Dim id As String = CType(category("_id"),Oid).ToString()
Console.WriteLine("Found by string id converted back to Oid")
- Console.WriteLine(categories.FindOne(new Document().Append("_id", new Oid(id.Replace("""", "")))).ToString())
+ Console.WriteLine(categories.FindOne(New Document().Add("_id", New Oid(id.Replace("""", "")))).ToString())
'Find(new Document()) is equivalent to FindAll()
'Specifying the cursor in a using block will close it on the server if we decide not
'to iterate through the whole thing.
- Dim all As ICursor = categories.Find(New Document())
+ Dim all As ICursor(Of Document) = categories.Find(New Document())
Try
For Each doc As Document In all.Documents
Console.WriteLine(doc.ToString())
diff --git a/examples/SimpleVB/SimpleVB.vbproj b/examples/SimpleVB/SimpleVB.vbproj
index 3c1ab5bd..56a0da12 100644
--- a/examples/SimpleVB/SimpleVB.vbproj
+++ b/examples/SimpleVB/SimpleVB.vbproj
@@ -1,9 +1,9 @@
-
+
Debug
AnyCPU
- 9.0.21022
+ 9.0.30729
2.0
{1BAAE3D8-7720-4AA5-9335-E59824E7B667}
Exe
@@ -12,6 +12,25 @@
On
SimpleVB
v3.5
+
+
+ 3.5
+
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ false
+ true
true
@@ -20,6 +39,8 @@
false
false
+ 42353,42354,42355
+ AllRules.ruleset
bin\Release
@@ -27,11 +48,15 @@
false
false
+ 42353,42354,42355
+ AllRules.ruleset
+
+
@@ -41,10 +66,30 @@
-
+
{B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}
- MongoDB.Driver
+ MongoDB
+
+
+ False
+ .NET Framework 3.5 SP1 Client Profile
+ false
+
+
+ False
+ .NET Framework 3.5 SP1
+ true
+
+
+ False
+ Windows Installer 3.1
+ true
+
+
+
+
+
\ No newline at end of file
diff --git a/MongoDB.GridFS.Tests/GridFileInfoTest.cs b/source/MongoDB.GridFS.Tests/GridFileInfoTest.cs
similarity index 95%
rename from MongoDB.GridFS.Tests/GridFileInfoTest.cs
rename to source/MongoDB.GridFS.Tests/GridFileInfoTest.cs
index 81373e1c..2c3617da 100644
--- a/MongoDB.GridFS.Tests/GridFileInfoTest.cs
+++ b/source/MongoDB.GridFS.Tests/GridFileInfoTest.cs
@@ -4,7 +4,7 @@
using NUnit.Framework;
-using MongoDB.Driver;
+using MongoDB;
namespace MongoDB.GridFS
{
@@ -68,9 +68,11 @@ public void TestDelete(){
String filename = "gfi-delete.txt";
GridFile gf = new GridFile(DB,"gfdelete");
GridFileInfo gfi = new GridFileInfo(DB,"gfdelete", filename);
+ var id = gfi.Id;
GridFileStream gfs = gfi.Create(); //TODO Expand Test to make sure that chunks for the file got deleted too.
gfi.Delete();
Assert.IsFalse(gf.Exists(filename), "File should have been deleted.");
+ Assert.IsTrue(0 == gf.Chunks.Count(new Document("_id", id)));
}
[Test]
diff --git a/MongoDB.GridFS.Tests/GridFileStreamTest.cs b/source/MongoDB.GridFS.Tests/GridFileStreamTest.cs
old mode 100755
new mode 100644
similarity index 96%
rename from MongoDB.GridFS.Tests/GridFileStreamTest.cs
rename to source/MongoDB.GridFS.Tests/GridFileStreamTest.cs
index 7532005b..307709eb
--- a/MongoDB.GridFS.Tests/GridFileStreamTest.cs
+++ b/source/MongoDB.GridFS.Tests/GridFileStreamTest.cs
@@ -3,7 +3,7 @@
using NUnit.Framework;
-using MongoDB.Driver;
+using MongoDB;
namespace MongoDB.GridFS
{
@@ -343,7 +343,7 @@ public void TestSeekingBeyondEOF(){
protected Document GrabChunk(Object fileid, int chunk){
- return DB[filesystem + ".chunks"].FindOne(new Document().Append("files_id", fileid).Append("n", chunk));
+ return DB[filesystem + ".chunks"].FindOne(new Document().Add("files_id", fileid).Add("n", chunk));
}
protected Object CreateDummyFile(string filename, int size, int chunksize, int initialOffset){
diff --git a/MongoDB.GridFS.Tests/GridFileTest.cs b/source/MongoDB.GridFS.Tests/GridFileTest.cs
similarity index 68%
rename from MongoDB.GridFS.Tests/GridFileTest.cs
rename to source/MongoDB.GridFS.Tests/GridFileTest.cs
index 32c4c786..6c25ee1c 100644
--- a/MongoDB.GridFS.Tests/GridFileTest.cs
+++ b/source/MongoDB.GridFS.Tests/GridFileTest.cs
@@ -3,7 +3,7 @@
using NUnit.Framework;
-using MongoDB.Driver;
+using MongoDB;
namespace MongoDB.GridFS
{
@@ -54,6 +54,23 @@ public void TestModeCreateNew(){
tw.Close();
}
Assert.AreEqual(1, CountChunks("gfcreate", id));
- }
+ }
+
+ [Test]
+ public void TestDeleteRemovesChunks(){
+ Object id;
+ string filename = "deletebyname.txt";
+ string fs = "fs";
+ GridFile gf = new GridFile(DB,fs);
+ using(GridFileStream gfs = gf.Create(filename, FileMode.CreateNew)){
+ id = gfs.GridFileInfo.Id;
+ TextWriter tw = new StreamWriter(gfs);
+ tw.WriteLine("test");
+ tw.Close();
+ }
+ Assert.AreEqual(1, CountChunks(fs, id), "Chunks not found");
+ gf.Delete("deletebyname.txt");
+ Assert.AreEqual(0, CountChunks(fs, id), "Chunks found");
+ }
}
}
diff --git a/MongoDB.GridFS.Tests/GridTestBase.cs b/source/MongoDB.GridFS.Tests/GridTestBase.cs
old mode 100755
new mode 100644
similarity index 92%
rename from MongoDB.GridFS.Tests/GridTestBase.cs
rename to source/MongoDB.GridFS.Tests/GridTestBase.cs
index 221124ab..3c95a72c
--- a/MongoDB.GridFS.Tests/GridTestBase.cs
+++ b/source/MongoDB.GridFS.Tests/GridTestBase.cs
@@ -4,7 +4,7 @@
using NUnit.Framework;
-using MongoDB.Driver;
+using MongoDB;
namespace MongoDB.GridFS
{
@@ -31,7 +31,7 @@ public override string TestCollections {
}
public long CountChunks(string filesystem, Object fileid){
- return DB[filesystem + ".chunks"].Count(new Document().Append("files_id", fileid));
+ return DB[filesystem + ".chunks"].Count(new Document().Add("files_id", fileid));
}
}
diff --git a/source/MongoDB.GridFS.Tests/MongoDB.GridFS.Tests.csproj b/source/MongoDB.GridFS.Tests/MongoDB.GridFS.Tests.csproj
new file mode 100644
index 00000000..f07f774f
--- /dev/null
+++ b/source/MongoDB.GridFS.Tests/MongoDB.GridFS.Tests.csproj
@@ -0,0 +1,110 @@
+
+
+
+ Debug
+ AnyCPU
+ 9.0.30729
+ 2.0
+ {0C293FE9-F670-4FEF-A60F-20F8C978B1CD}
+ Library
+ MongoDB.GridFS.Tests
+ v3.5
+ MongoDB.GridFS.Tests
+ true
+ ..\..\StrongName.snk
+
+
+
+
+ 3.5
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ false
+ true
+
+
+ true
+ full
+ false
+ bin\Debug
+ DEBUG
+ prompt
+ 4
+ false
+ AllRules.ruleset
+
+
+ none
+ false
+ bin\Release
+ prompt
+ 4
+ false
+ AllRules.ruleset
+
+
+
+
+
+ False
+ ..\..\redist\nunit.framework.dll
+
+
+
+
+
+
+
+
+ StrongName.snk
+
+
+ App.config
+ PreserveNewest
+
+
+
+
+
+ False
+ .NET Framework 3.5 SP1 Client Profile
+ false
+
+
+ False
+ .NET Framework 3.5 SP1
+ true
+
+
+ False
+ Windows Installer 3.1
+ true
+
+
+
+
+ {B42DBBF9-0A1F-4749-9787-013BF8D8F435}
+ MongoDB.GridFS
+
+
+ {C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}
+ MongoDB.Tests
+
+
+ {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}
+ MongoDB
+
+
+
+
\ No newline at end of file
diff --git a/source/MongoDB.GridFS/AssemblyInfo.cs b/source/MongoDB.GridFS/AssemblyInfo.cs
new file mode 100644
index 00000000..39b333a3
--- /dev/null
+++ b/source/MongoDB.GridFS/AssemblyInfo.cs
@@ -0,0 +1,11 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+
+// Information about this assembly is defined by the following attributes.
+// Change them to the values specific to your project.
+
+[assembly: AssemblyTitle("MongoDB.GridFS")]
+[assembly: AssemblyDescription("GridFS implementation for MongoDB-CSharp driver")]
+[assembly: AssemblyProduct("MongoDB-CSharp")]
+
+[assembly: InternalsVisibleTo("MongoDB.GridFS.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100ed9e936c4563336be2e14ca802ea727ff49cad3bb1c0b287beed2a9b5eb823c4c44becc80be4bb11dcd7e49d5d6171f68b488853dcbdeb3152ea3db95ba13a70855a715ee21ac76b67f50bcbc93f2e29e409530a00b98fa79b06ac008dd1f4f3582ba6746af3d218b43b70a63254b094be1a2d493590837273f357fc56b2a7a0")]
diff --git a/source/MongoDB.GridFS/GridException.cs b/source/MongoDB.GridFS/GridException.cs
new file mode 100644
index 00000000..bec61639
--- /dev/null
+++ b/source/MongoDB.GridFS/GridException.cs
@@ -0,0 +1,32 @@
+using System;
+
+namespace MongoDB.GridFS
+{
+ ///
+ ///
+ ///
+ public class MongoGridFSException : Exception
+ {
+ private string filename;
+ ///
+ /// Gets the filename.
+ ///
+ /// The filename.
+ public string Filename
+ {
+ get { return filename; }
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The message.
+ /// The filename.
+ /// The inner.
+ public MongoGridFSException(string message, string filename, Exception inner)
+ : base(message, inner)
+ {
+ this.filename = filename;
+ }
+ }
+}
diff --git a/MongoDB.GridFS/GridFile.cs b/source/MongoDB.GridFS/GridFile.cs
old mode 100755
new mode 100644
similarity index 54%
rename from MongoDB.GridFS/GridFile.cs
rename to source/MongoDB.GridFS/GridFile.cs
index a147cd46..835758dd
--- a/MongoDB.GridFS/GridFile.cs
+++ b/source/MongoDB.GridFS/GridFile.cs
@@ -1,46 +1,83 @@
using System;
using System.IO;
-using MongoDB.Driver;
+using MongoDB;
namespace MongoDB.GridFS
{
+ ///
+ ///
+ ///
public class GridFile{
- private Database db;
+ private IMongoDatabase db;
private string name;
+ ///
+ /// Gets the name.
+ ///
+ /// The name.
public string Name {
get { return name; }
}
-
+
private IMongoCollection files;
- public IMongoCollection Files{
+ ///
+ /// Gets the files.
+ ///
+ /// The files.
+ public IMongoCollection Files
+ {
get { return this.files; }
}
private IMongoCollection chunks;
- public IMongoCollection Chunks{
+ ///
+ /// Gets the chunks.
+ ///
+ /// The chunks.
+ public IMongoCollection Chunks
+ {
get { return this.chunks; }
- }
-
- public GridFile(Database db):this(db,"fs"){}
+ }
- public GridFile(Database db, string bucket){
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The db.
+ public GridFile(IMongoDatabase db):this(db,"fs"){}
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The db.
+ /// The bucket.
+ public GridFile(IMongoDatabase db, string bucket){
this.db = db;
this.files = db[bucket + ".files"];
this.chunks = db[bucket + ".chunks"];
- this.chunks.MetaData.CreateIndex(new Document().Append("files_id", 1).Append("n", 1),true);
+ this.chunks.Metadata.CreateIndex(new Document().Add("files_id", 1).Add("n", 1), true);
+ this.files.Metadata.CreateIndex(new Document().Add("filename", 1).Add("n", 1), false);
this.name = bucket;
}
-
+
+ ///
+ /// Lists the files.
+ ///
+ ///
public ICursor ListFiles(){
return this.ListFiles(new Document());
}
-
- public ICursor ListFiles(Document query){
- return this.files.Find(new Document().Append("query",query)
- .Append("orderby", new Document()
- .Append("filename", 1)));
+
+ ///
+ /// Lists the files.
+ ///
+ /// The query.
+ ///
+ public ICursor ListFiles(Document query)
+ {
+ return this.files.Find(new Document().Add("query", query)
+ .Add("orderby", new Document()
+ .Add("filename", 1)));
}
///
@@ -52,8 +89,8 @@ public ICursor ListFiles(Document query){
public void Copy(String src, String dest){
if(Exists(src) == false) throw new FileNotFoundException("Not found in the database.", src);
if(Exists(dest) == true) throw new IOException("Destination file already exists.");
-
- Document scope = new Document().Append("bucket", this.name).Append("srcfile", src).Append("destfile",dest);
+
+ Document scope = new Document().Add("bucket", this.name).Add("srcfile", src).Add("destfile", dest);
String func ="function(){\n" +
//" print(\"copying \" + srcfile);\n" +
" var files = db[bucket + \".files\"];\n" +
@@ -76,18 +113,36 @@ public void Copy(String src, String dest){
" }\n" +
" return false;\n" +
"}";
- Document result = db.Eval(func,scope);
+ db.Eval(func,scope);
}
#region Create
+ ///
+ /// Creates the specified filename.
+ ///
+ /// The filename.
+ ///
public GridFileStream Create(String filename){
return Create(filename, FileMode.Create);
}
-
+
+ ///
+ /// Creates the specified filename.
+ ///
+ /// The filename.
+ /// The mode.
+ ///
public GridFileStream Create(String filename, FileMode mode){
return Create(filename,mode,FileAccess.ReadWrite);
}
-
+
+ ///
+ /// Creates the specified filename.
+ ///
+ /// The filename.
+ /// The mode.
+ /// The access.
+ ///
public GridFileStream Create(String filename, FileMode mode, FileAccess access){
//Create is delegated to a GridFileInfo because the stream needs access to the gfi and it
//is easier to do it this way and only write the implementation once.
@@ -98,15 +153,32 @@ public GridFileStream Create(String filename, FileMode mode, FileAccess access){
#endregion
#region Opens
+ ///
+ /// Opens the specified filename.
+ ///
+ /// The filename.
+ /// The mode.
+ /// The access.
+ ///
public GridFileStream Open(string filename, FileMode mode, FileAccess access){
return new GridFileInfo(this.db, this.name, filename).Open(mode, access);
}
+ ///
+ /// Opens the read.
+ ///
+ /// The filename.
+ ///
public GridFileStream OpenRead(String filename){
GridFileInfo gfi = new GridFileInfo(this.db, this.name, filename);
return gfi.OpenRead();
}
+ ///
+ /// Opens the write.
+ ///
+ /// The filename.
+ ///
public GridFileStream OpenWrite(String filename){
GridFileInfo gfi = new GridFileInfo(this.db, this.name, filename);
return gfi.OpenWrite();
@@ -120,15 +192,15 @@ public GridFileStream OpenWrite(String filename){
/// Permanently removes a file from the database.
///
public void Delete(Object id){
- files.Delete(new Document().Append("_id",id));
- chunks.Delete(new Document().Append("files_id",id));
+ files.Remove(new Document().Add("_id", id));
+ chunks.Remove(new Document().Add("files_id", id));
}
///
/// Permanently removes a file from the database.
///
public void Delete(String filename){
- files.Delete(new Document().Append("filename",filename));
+ this.Delete(new Document().Add("filename", filename));
}
///
@@ -146,23 +218,33 @@ public void Delete(Document query ){
/// Gets a value indicating whether the file exists.
///
public Boolean Exists(string name){
- return this.files.FindOne(new Document().Append("filename",name)) != null;
+ return this.files.FindOne(new Document().Add("filename", name)) != null;
}
///
/// Gets a value indicating whether the file exists.
///
public Boolean Exists(Object id){
- return this.files.FindOne(new Document().Append("_id",id)) != null;
+ return this.files.FindOne(new Document().Add("_id", id)) != null;
}
#endregion
#region Move
+ ///
+ /// Moves the specified SRC.
+ ///
+ /// The SRC.
+ /// The dest.
public void Move(String src, String dest){
- this.files.Update(new Document().Append("$set", new Document().Append("filename",dest)), new Document().Append("filename", src));
+ this.files.Update(new Document().Add("$set", new Document().Add("filename", dest)), new Document().Add("filename", src));
}
-
+
+ ///
+ /// Moves the specified id.
+ ///
+ /// The id.
+ /// The dest.
public void Move(Object id, String dest){
- this.files.Update(new Document().Append("$set", new Document().Append("filename",dest)), new Document().Append("_id", id));
+ this.files.Update(new Document().Add("$set", new Document().Add("filename", dest)), new Document().Add("_id", id));
}
#endregion
diff --git a/MongoDB.GridFS/GridFileInfo.cs b/source/MongoDB.GridFS/GridFileInfo.cs
similarity index 70%
rename from MongoDB.GridFS/GridFileInfo.cs
rename to source/MongoDB.GridFS/GridFileInfo.cs
index 076b3906..39aad7eb 100644
--- a/MongoDB.GridFS/GridFileInfo.cs
+++ b/source/MongoDB.GridFS/GridFileInfo.cs
@@ -2,7 +2,7 @@
using System.Collections.Generic;
using System.IO;
-using MongoDB.Driver;
+using MongoDB;
namespace MongoDB.GridFS
{
@@ -18,24 +18,36 @@ public class GridFileInfo
private const string DEFAULT_CONTENT_TYPE = "text/plain";
private GridFile gridFile;
- private Database db;
+ private IMongoDatabase db;
private string bucket;
#region "filedata properties"
private Document filedata = new Document();
+ ///
+ /// Gets or sets the id.
+ ///
+ /// The id.
public Object Id{
get { return filedata["_id"]; }
set { filedata["_id"] = value; }
}
+ ///
+ /// Gets or sets the name of the file.
+ ///
+ /// The name of the file.
public string FileName
{
get { return (String)filedata["filename"]; }
set { filedata["filename"] = value; }
}
+ ///
+ /// Gets or sets the type of the content.
+ ///
+ /// The type of the content.
public string ContentType{
get { return (String)filedata["contentType"]; }
set { filedata["contentType"] = value; }
@@ -50,41 +62,66 @@ public long Length{
set { filedata["length"] = value; }
}
+ ///
+ /// Gets or sets the aliases.
+ ///
+ /// The aliases.
public IList Aliases{
get {
- if(filedata.Contains("aliases") == false || filedata["aliases"] == null){
+ if(filedata.ContainsKey("aliases") == false || filedata["aliases"] == null){
return null;
}
if(filedata["aliases"] is IList){
return (List)filedata["aliases"];
- }else{
- return null;
}
+ return new List();
}
set { filedata["aliases"] = value; }
}
+ ///
+ /// Gets or sets the size of the chunk.
+ ///
+ /// The size of the chunk.
public int ChunkSize{
get { return Convert.ToInt32(filedata["chunkSize"]); }
set { filedata["chunkSize"] = value; }
}
+ ///
+ /// Gets the metadata.
+ ///
+ /// The metadata.
public Object Metadata{
get { return (Document)filedata["metadata"]; }
}
+ ///
+ /// Gets or sets the upload date.
+ ///
+ /// The upload date.
public DateTime? UploadDate{
get { return Convert.ToDateTime(filedata["uploadDate"]); }
set { filedata["uploadDate"] = value; }
}
+ ///
+ /// Gets or sets the MD5.
+ ///
+ /// The MD5.
public string Md5{
get { return (String)filedata["md5"]; }
set { filedata["md5"] = value; }
}
#endregion
- public GridFileInfo(Database db, string bucket, string filename){
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The db.
+ /// The bucket.
+ /// The filename.
+ public GridFileInfo(IMongoDatabase db, string bucket, string filename){
this.db = db;
this.bucket = bucket;
this.gridFile = new GridFile(db,bucket);
@@ -92,7 +129,12 @@ public GridFileInfo(Database db, string bucket, string filename){
if(gridFile.Exists(filename)) this.LoadFileData();
}
- public GridFileInfo(Database db, string filename){
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The db.
+ /// The filename.
+ public GridFileInfo(MongoDatabase db, string filename){
this.db = db;
this.bucket = "fs";
this.gridFile = new GridFile(db);
@@ -112,15 +154,27 @@ private void SetFileDataDefaults(string filename){
///
/// Creates the file named FileName and returns the GridFileStream
///
- /// If the file already exists
+ ///
+ /// If the file already exists
public GridFileStream Create(){
return Create(FileMode.CreateNew);
}
-
+
+ ///
+ /// Creates the specified mode.
+ ///
+ /// The mode.
+ ///
public GridFileStream Create(FileMode mode){
return Create(mode,FileAccess.ReadWrite);
- }
-
+ }
+
+ ///
+ /// Creates the specified mode.
+ ///
+ /// The mode.
+ /// The access.
+ ///
public GridFileStream Create(FileMode mode, FileAccess access){
switch (mode) {
case FileMode.CreateNew:
@@ -157,15 +211,20 @@ public GridFileStream OpenRead(){
public GridFileStream OpenWrite(){
return this.Open(FileMode.Open, FileAccess.Write);
}
-
+
+ ///
+ /// Opens the specified mode.
+ ///
+ /// The mode.
+ /// The access.
+ ///
public GridFileStream Open(FileMode mode, FileAccess access){
switch (mode) {
case FileMode.Create:
if(gridFile.Exists(this.FileName) == true){
return this.Open(FileMode.Truncate, access);
- }else{
- return this.Create(FileMode.CreateNew, access);
}
+ return this.Create(FileMode.CreateNew, access);
case FileMode.CreateNew:
return this.Create(mode, access);
case FileMode.Open:
@@ -215,19 +274,24 @@ public Boolean Exists{
return this.gridFile.Exists(this.FileName);
}
}
-
+
///
/// Deletes all data in a file and sets the length to 0.
///
public void Truncate(){
- if(filedata.Contains("_id") == false) return;
- this.gridFile.Chunks.Delete(new Document().Append("files_id", filedata["_id"]));
+ if(filedata.ContainsKey("_id") == false)
+ return;
+ this.gridFile.Chunks.Remove(new Document().Add("files_id", filedata["_id"]));
this.Length = 0;
- this.gridFile.Files.Update(filedata);
+ this.gridFile.Files.Save(filedata);
}
+ ///
+ /// Calcs the M d5.
+ ///
+ ///
public string CalcMD5(){
- Document doc = this.db.SendCommand(new Document().Append("filemd5", this.Id).Append("root",this.bucket));
+ Document doc = this.db.SendCommand(new Document().Add("filemd5", this.Id).Add("root", this.bucket));
return (String)doc["md5"];
}
@@ -254,18 +318,28 @@ public void Refresh(){
}
private void LoadFileData(){
- Document doc = this.gridFile.Files.FindOne(new Document().Append("filename",this.FileName));
+ Document doc = this.gridFile.Files.FindOne(new Document().Add("filename", this.FileName));
if(doc != null){
filedata = doc;
}else{
throw new DirectoryNotFoundException(this.gridFile.Name + Path.VolumeSeparatorChar + this.FileName);
}
}
-
+
+ ///
+ /// Toes the document.
+ ///
+ ///
public Document ToDocument(){
return this.filedata;
}
-
+
+ ///
+ /// Returns a that represents this instance.
+ ///
+ ///
+ /// A that represents this instance.
+ ///
public override string ToString(){
return filedata.ToString();
}
diff --git a/source/MongoDB.GridFS/GridFileStream.cs b/source/MongoDB.GridFS/GridFileStream.cs
new file mode 100644
index 00000000..68199806
--- /dev/null
+++ b/source/MongoDB.GridFS/GridFileStream.cs
@@ -0,0 +1,451 @@
+using System;
+using System.IO;
+
+using MongoDB;
+
+namespace MongoDB.GridFS
+{
+ ///
+ /// Stream for reading and writing to a file in GridFS.
+ ///
+ ///
+ /// When using the stream for random io it is possible to produce chunks in the begining and middle of the
+ /// file that are not full size followed by other chunks that are full size. This only affects the md5 sum
+ /// that is calculated on the file on close. Because of this do not rely on the md5 sum of a file when doing
+ /// random io. Writing to the stream sequentially works fine and will produce a consistent md5.
+ ///
+ public class GridFileStream : Stream
+ {
+
+ private IMongoCollection files;
+ private IMongoCollection chunks;
+ private Document chunk;
+ private bool chunkDirty;
+ private long chunkLower = -1;
+ private long chunkUpper = -1;
+
+ private byte[] buffer;
+ private byte[] blankBuffer;
+ private int buffPosition;
+ private int highestBuffPosition;
+ private long highestPosWritten;
+
+
+ #region Properties
+ private GridFileInfo gridFileInfo;
+ ///
+ /// Gets or sets the grid file info.
+ ///
+ /// The grid file info.
+ public GridFileInfo GridFileInfo {
+ get { return gridFileInfo; }
+ set { gridFileInfo = value; }
+ }
+
+ private bool canRead;
+ ///
+ /// When overridden in a derived class, gets a value indicating whether the current stream supports reading.
+ ///
+ ///
+ /// true if the stream supports reading; otherwise, false.
+ ///
+ public override bool CanRead {
+ get { return canRead; }
+ }
+
+ private bool canWrite;
+ ///
+ /// When overridden in a derived class, gets a value indicating whether the current stream supports writing.
+ ///
+ ///
+ /// true if the stream supports writing; otherwise, false.
+ ///
+ public override bool CanWrite {
+ get { return canRead; }
+ }
+
+ ///
+ /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
+ ///
+ ///
+ /// true if the stream supports seeking; otherwise, false.
+ ///
+ public override bool CanSeek {
+ get { return true; }
+ }
+
+ ///
+ /// When overridden in a derived class, gets the length in bytes of the stream.
+ ///
+ ///
+ ///
+ /// A long value representing the length of the stream in bytes.
+ ///
+ ///
+ /// A class derived from Stream does not support seeking.
+ ///
+ ///
+ /// Methods were called after the stream was closed.
+ ///
+ public override long Length {
+ get { return gridFileInfo.Length; }
+ }
+
+ private long position;
+ ///
+ /// When overridden in a derived class, gets or sets the position within the current stream.
+ ///
+ ///
+ ///
+ /// The current position within the stream.
+ ///
+ ///
+ /// An I/O error occurs.
+ ///
+ ///
+ /// The stream does not support seeking.
+ ///
+ ///
+ /// Methods were called after the stream was closed.
+ ///
+ public override long Position {
+ get { return position; }
+ set { this.Seek (value, SeekOrigin.Begin); }
+ }
+ #endregion
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The gridfileinfo.
+ /// The files.
+ /// The chunks.
+ /// The access.
+ public GridFileStream (GridFileInfo gridfileinfo, IMongoCollection files,
+ IMongoCollection chunks, FileAccess access)
+ {
+ switch (access) {
+ case FileAccess.Read:
+ canRead = true;
+ break;
+ case FileAccess.ReadWrite:
+ canRead = true;
+ canWrite = true;
+ break;
+ case FileAccess.Write:
+ canWrite = true;
+ break;
+ }
+ this.gridFileInfo = gridfileinfo;
+ this.files = files;
+ this.chunks = chunks;
+ this.buffer = new byte[gridFileInfo.ChunkSize];
+ this.blankBuffer = new byte[gridFileInfo.ChunkSize];
+ this.highestPosWritten = this.gridFileInfo.Length;
+ this.MoveTo (0);
+ }
+
+ ///
+ /// Reads data from the stream into the specified array. It will fill the array in starting at offset and
+ /// adding count bytes returning the number of bytes read from the stream.
+ ///
+ public override int Read (byte[] array, int offset, int count)
+ {
+ ValidateReadState (array, offset, count);
+
+ int bytesLeftToRead = count;
+ int bytesRead = 0;
+ while (bytesLeftToRead > 0 && this.position < this.Length) {
+ int buffAvailable = buffer.Length - buffPosition;
+ int readCount = 0;
+ if (buffAvailable > bytesLeftToRead) {
+ readCount = bytesLeftToRead;
+ } else {
+ readCount = buffAvailable;
+ }
+ if (readCount + position > highestPosWritten) {
+ //adjust readcount so that we don't read past the end of file.
+ readCount = readCount - (int)(readCount + position - highestPosWritten);
+ }
+ Array.Copy (buffer, buffPosition, array, offset, readCount);
+ buffPosition += readCount;
+ bytesLeftToRead -= readCount;
+ bytesRead += readCount;
+ offset += readCount;
+ MoveTo (position + readCount);
+ }
+ return bytesRead;
+ }
+
+ private void ValidateReadState (byte[] array, int offset, int count)
+ {
+ if (array == null) {
+ throw new ArgumentNullException ("array", new Exception ("array is null"));
+ } else if (offset < 0) {
+ throw new ArgumentOutOfRangeException ("offset", new Exception ("offset is negative"));
+ } else if (count < 0) {
+ throw new ArgumentOutOfRangeException ("count", new Exception ("count is negative"));
+ } else if ((array.Length - offset) < count) {
+ throw new MongoGridFSException ("Invalid count argument", gridFileInfo.FileName, null);
+ } else if (!canRead) {
+ throw new MongoGridFSException ("Reading this file is not supported", gridFileInfo.FileName, null);
+ }
+ }
+
+ ///
+ /// Copies from the source array into the grid file.
+ ///
+ /// The array.
+ /// A The offset within the source array.
+ /// A The number of bytes from within the source array to copy.
+ public override void Write (byte[] array, int offset, int count)
+ {
+ ValidateWriteState (array, offset, count);
+
+ int bytesLeftToWrite = count;
+ while (bytesLeftToWrite > 0) {
+ int buffAvailable = buffer.Length - buffPosition;
+ int writeCount = 0;
+ if (buffAvailable > bytesLeftToWrite) {
+ writeCount = bytesLeftToWrite;
+ } else {
+ writeCount = buffAvailable;
+ }
+ Array.Copy (array, offset, buffer, buffPosition, writeCount);
+ chunkDirty = true;
+ buffPosition += writeCount;
+ offset += writeCount;
+ bytesLeftToWrite -= writeCount;
+ MoveTo (position + writeCount);
+ highestPosWritten = Math.Max (highestPosWritten, position);
+ }
+ }
+
+ private void ValidateWriteState (byte[] array, int offset, int count)
+ {
+ if (array == null) {
+ throw new ArgumentNullException ("array", new Exception ("array is null"));
+ } else if (offset < 0) {
+ throw new ArgumentOutOfRangeException ("offset", new Exception ("offset is negative"));
+ } else if (count < 0) {
+ throw new ArgumentOutOfRangeException ("count", new Exception ("count is negative"));
+ } else if ((array.Length - offset) < count) {
+ throw new MongoGridFSException ("Invalid count argument", gridFileInfo.FileName, null);
+ } else if (!canWrite) {
+ throw new System.NotSupportedException ("Stream does not support writing.");
+ }
+ }
+
+
+ ///
+ /// Flushes any changes to current chunk to the database. It can be called in client code at any time or it
+ /// will automatically be called on Close() and when the stream position moves off the bounds of the current
+ /// chunk.
+ ///
+ ///
+ /// An I/O error occurs.
+ ///
+ public override void Flush ()
+ {
+ if (chunkDirty == false)
+ return;
+ //avoid a copy if possible.
+ if (highestBuffPosition == buffer.Length) {
+ chunk["data"] = new Binary (buffer);
+ } else {
+ byte[] data = new byte[highestBuffPosition];
+ Array.Copy (buffer, data, highestBuffPosition);
+ chunk["data"] = new Binary (data);
+ }
+
+
+ if(chunk.ContainsKey("_id"))
+ {
+ chunks.Save (chunk);
+ } else {
+ chunks.Insert (chunk);
+ }
+ this.gridFileInfo.Length = highestPosWritten;
+ }
+
+ ///
+ /// Seek to any location in the stream. Seeking past the end of the file is allowed. Any writes to that
+ /// location will cause the file to grow to that size. Any holes that may be created from the seek will
+ /// be zero filled on close.
+ ///
+ public override long Seek (long offset, SeekOrigin origin)
+ {
+ if ((origin < SeekOrigin.Begin) || (origin > SeekOrigin.End)) {
+ throw new ArgumentException ("Invalid Seek Origin");
+ }
+
+ switch (origin) {
+ case SeekOrigin.Begin:
+ if (offset < 0) {
+ throw new ArgumentException ("Attempted seeking before the begining of the stream");
+ } else {
+ MoveTo (offset);
+ }
+ break;
+ case SeekOrigin.Current:
+ MoveTo (position + offset);
+ break;
+ case SeekOrigin.End:
+ if (offset <= 0) {
+ throw new ArgumentException ("Attempted seeking after the end of the stream");
+ }
+ MoveTo (this.Length - offset);
+ break;
+ }
+ return position;
+ }
+
+ ///
+ /// Sets the length of this stream to the given value.
+ ///
+ ///
+ /// A
+ ///
+ public override void SetLength (long value)
+ {
+ if (value < 0)
+ throw new ArgumentOutOfRangeException ("length");
+ if (this.CanSeek == false || this.CanWrite == false) {
+ throw new NotSupportedException ("The stream does not support both writing and seeking.");
+ }
+
+ if (value < highestPosWritten) {
+ TruncateAfter (value);
+ } else {
+ this.Seek (value, SeekOrigin.Begin);
+ }
+ chunkDirty = true;
+ this.gridFileInfo.Length = value;
+ highestPosWritten = value;
+
+ }
+
+ ///
+ /// Close the stream and flush any changes to the database.
+ ///
+ public override void Close ()
+ {
+ this.Flush ();
+ this.gridFileInfo.Length = highestPosWritten;
+ EnsureNoHoles ();
+ string md5 = gridFileInfo.CalcMD5 ();
+ gridFileInfo.Md5 = md5;
+ this.files.Save (gridFileInfo.ToDocument ());
+ base.Close ();
+ }
+
+ ///
+ /// Moves the current position to the new position. If this causes a new chunk to need to be loaded it will take
+ /// care of flushing the buffer and loading a new chunk.
+ ///
+ ///
+ /// A designating where to go to.
+ ///
+ private void MoveTo (long position)
+ {
+ this.position = position;
+ int chunkSize = this.gridFileInfo.ChunkSize;
+ bool chunkInRange = (chunk != null && position >= chunkLower && position < chunkUpper);
+ if (chunkInRange == false) {
+ if (chunk != null && chunkDirty) {
+ highestBuffPosition = Math.Max (highestBuffPosition, buffPosition);
+ this.Flush ();
+ }
+ int chunknum = (int)Math.Floor ((double)(position / chunkSize));
+ Array.Copy (blankBuffer, buffer, buffer.Length);
+ LoadOrCreateChunk (chunknum);
+ chunkDirty = false;
+ chunkLower = chunknum * chunkSize;
+ chunkUpper = chunkLower + chunkSize;
+ }
+ buffPosition = (int)(position % chunkSize);
+ highestBuffPosition = Math.Max (highestBuffPosition, buffPosition);
+
+ }
+
+ ///
+ /// Loads a chunk from the chunks collection if it exists. Otherwise it creates a blank chunk Document.
+ ///
+ ///
+ private void LoadOrCreateChunk (int num)
+ {
+ Object fid = this.GridFileInfo.Id;
+ Document spec = new Document().Add("files_id", fid).Add("n", num);
+ chunk = this.chunks.FindOne (spec);
+ if (chunk == null) {
+ chunk = spec;
+ highestBuffPosition = 0;
+ } else {
+ Binary b = (Binary)chunk["data"];
+ highestBuffPosition = b.Bytes.Length;
+ Array.Copy (b.Bytes, buffer, highestBuffPosition);
+ }
+ }
+
+
+ ///
+ /// Deletes all chunks after the specified position and clears out any extra bytes if the position doesn't fall on
+ /// a chunk boundry.
+ ///
+ private void TruncateAfter (long value)
+ {
+ int chunknum = CalcChunkNum (value);
+ Document spec = new Document().Add("files_id", this.gridFileInfo.Id).Add("n", new Document().Add("$gt", chunknum));
+ this.chunks.Remove(spec);
+ this.MoveTo (value);
+ Array.Copy (blankBuffer, 0, buffer, buffPosition, buffer.Length - buffPosition);
+ highestBuffPosition = buffPosition;
+ }
+
+ private int CalcChunkNum (long position)
+ {
+ int chunkSize = this.gridFileInfo.ChunkSize;
+ return (int)Math.Floor ((double)(position / chunkSize));
+ }
+
+ ///
+ /// Makes sure that at least a skelton chunk exists for all numbers. If not the MD5 calculation will fail on a sparse file.
+ ///
+ private void EnsureNoHoles ()
+ {
+ int highChunk = CalcChunkNum (this.GridFileInfo.Length);
+ Document query = new Document().Add("files_id", this.GridFileInfo.Id).Add("n", new Document().Add("$lte", highChunk));
+ Document sort = new Document().Add("n", 1);
+ Document fields = new Document().Add("_id", 1).Add("n", 1);
+
+ Binary data = new Binary (this.blankBuffer);
+ int i = 0;
+ using(ICursor cur = chunks.Find(new Document().Add("query", query).Add("sort", sort), 0, 0, fields)){
+ foreach (Document doc in cur.Documents) {
+ int n = Convert.ToInt32 (doc["n"]);
+ if (i < n) {
+ while (i < n) {
+ chunks.Insert (new Document ().Add("files_id", this.gridFileInfo.Id).Add("n", i).Add("data", data));
+ i++;
+ }
+ } else {
+ i++;
+ }
+ }
+ }
+
+ }
+
+ ///
+ /// Releases the unmanaged resources used by the and optionally releases the managed resources.
+ ///
+ /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ protected override void Dispose (bool disposing)
+ {
+ this.canRead = false;
+ this.canWrite = false;
+
+ base.Dispose (disposing);
+ }
+ }
+}
diff --git a/source/MongoDB.GridFS/MongoDB.GridFS.csproj b/source/MongoDB.GridFS/MongoDB.GridFS.csproj
new file mode 100644
index 00000000..6f83193c
--- /dev/null
+++ b/source/MongoDB.GridFS/MongoDB.GridFS.csproj
@@ -0,0 +1,105 @@
+
+
+
+ Debug
+ AnyCPU
+ 9.0.30729
+ 2.0
+ {B42DBBF9-0A1F-4749-9787-013BF8D8F435}
+ Library
+ MongoDB.GridFS
+ v3.5
+ MongoDB.GridFS
+ true
+ ..\..\StrongName.snk
+
+
+
+
+ 3.5
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ false
+ true
+
+
+ true
+ full
+ false
+ bin\Debug
+ DEBUG
+ prompt
+ 4
+ false
+ false
+ bin\Debug\MongoDB.GridFS.xml
+ AllRules.ruleset
+ 0618
+
+
+ none
+ false
+ bin\Release\
+ prompt
+ 4
+ false
+ false
+ bin\Release\MongoDB.GridFS.xml
+ AllRules.ruleset
+ true
+
+
+
+
+
+
+
+ AssemblyInfoGlobal.cs
+
+
+
+
+
+
+
+
+
+ False
+ .NET Framework 3.5 SP1 Client Profile
+ false
+
+
+ False
+ .NET Framework 3.5 SP1
+ true
+
+
+ False
+ Windows Installer 3.1
+ true
+
+
+
+
+ StrongName.snk
+
+
+
+
+ {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}
+ MongoDB
+
+
+
+
\ No newline at end of file
diff --git a/source/MongoDB.Tests/App.config b/source/MongoDB.Tests/App.config
new file mode 100644
index 00000000..79807133
--- /dev/null
+++ b/source/MongoDB.Tests/App.config
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/source/MongoDB.Tests/IntegrationTests/Connections/TestConnection.cs b/source/MongoDB.Tests/IntegrationTests/Connections/TestConnection.cs
new file mode 100644
index 00000000..feb82c82
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/Connections/TestConnection.cs
@@ -0,0 +1,72 @@
+using System.IO;
+using System.Text;
+using MongoDB.Bson;
+using MongoDB.Connections;
+using MongoDB.Protocol;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests.Connections
+{
+ [TestFixture]
+ public class TestConnection
+ {
+ private void WriteBadMessage(Connection conn)
+ {
+ //Write a bad message to the socket to force mongo to shut down our connection.
+ var writer = new BinaryWriter(conn.GetStream());
+ var encoding = new UTF8Encoding();
+ var msg = encoding.GetBytes("Goodbye MongoDB!");
+ writer.Write(16 + msg.Length + 1);
+ writer.Write(1);
+ writer.Write(1);
+ writer.Write(1001);
+ writer.Write(msg);
+ writer.Write((byte)0);
+ }
+
+ private QueryMessage GenerateQueryMessage()
+ {
+ var qdoc = new Document {{"listDatabases", 1.0}};
+ //QueryMessage qmsg = new QueryMessage(qdoc,"system.namespaces");
+ return new QueryMessage(new BsonWriterSettings(), qdoc, "admin.$cmd")
+ {
+ NumberToReturn = -1
+ };
+ }
+
+ [Test]
+ public void TestReconnectOnce()
+ {
+ var conn = ConnectionFactoryFactory.GetConnection(string.Empty);
+ conn.Open();
+
+ WriteBadMessage(conn);
+ try
+ {
+ var qmsg = GenerateQueryMessage();
+ conn.SendTwoWayMessage(qmsg,string.Empty);
+ }
+ catch(IOException)
+ {
+ //Should be able to resend.
+ Assert.IsTrue(conn.IsConnected);
+ var qmsg = GenerateQueryMessage();
+ var rmsg = conn.SendTwoWayMessage(qmsg, string.Empty);
+ Assert.IsNotNull(rmsg);
+ }
+ }
+
+ [Test]
+ public void TestSendQueryMessage()
+ {
+ //Connection conn = new Connection("10.141.153.2");
+ var conn = ConnectionFactoryFactory.GetConnection(string.Empty);
+ conn.Open();
+
+ var qmsg = GenerateQueryMessage();
+ conn.SendTwoWayMessage(qmsg, string.Empty);
+
+ conn.Close();
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/IntegrationTests/Connections/TestConnectionFactory.cs b/source/MongoDB.Tests/IntegrationTests/Connections/TestConnectionFactory.cs
new file mode 100644
index 00000000..01468aea
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/Connections/TestConnectionFactory.cs
@@ -0,0 +1,44 @@
+using System;
+using MongoDB.Connections;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests.Connections
+{
+ [TestFixture]
+ public class TestConnectionFactory
+ {
+ [TearDown]
+ public void TearDown (){
+ ConnectionFactoryFactory.Shutdown ();
+ }
+
+ [Test]
+ public void TestGetConnection (){
+ var connection1 = ConnectionFactoryFactory.GetConnection (string.Empty);
+ var connection2 = ConnectionFactoryFactory.GetConnection (string.Empty);
+ Assert.IsNotNull (connection1);
+ Assert.IsNotNull (connection2);
+ Assert.AreEqual (1, ConnectionFactoryFactory.PoolCount);
+ }
+
+ [Test]
+ public void TestCreatePoolForEachUniqeConnectionString (){
+ ConnectionFactoryFactory.GetConnection (string.Empty);
+ ConnectionFactoryFactory.GetConnection (string.Empty);
+ ConnectionFactoryFactory.GetConnection ("Username=test");
+ ConnectionFactoryFactory.GetConnection ("Username=test");
+ ConnectionFactoryFactory.GetConnection ("Server=localhost");
+ Assert.AreEqual (3, ConnectionFactoryFactory.PoolCount);
+ }
+
+ [Test]
+ public void TestExceptionWhenMinimumPoolSizeIsGreaterThenMaximumPoolSize (){
+ try{
+ ConnectionFactoryFactory.GetConnection("MinimumPoolSize=50; MaximumPoolSize=10");
+ }catch(ArgumentException){
+ }catch(Exception){
+ Assert.Fail("Wrong exception thrown");
+ }
+ }
+ }
+}
diff --git a/MongoDB.Net-Tests/Connections/TestPooledConnectionFactory.cs b/source/MongoDB.Tests/IntegrationTests/Connections/TestPooledConnectionFactory.cs
similarity index 80%
rename from MongoDB.Net-Tests/Connections/TestPooledConnectionFactory.cs
rename to source/MongoDB.Tests/IntegrationTests/Connections/TestPooledConnectionFactory.cs
index 0991bea3..442fa761 100644
--- a/MongoDB.Net-Tests/Connections/TestPooledConnectionFactory.cs
+++ b/source/MongoDB.Tests/IntegrationTests/Connections/TestPooledConnectionFactory.cs
@@ -1,8 +1,9 @@
using System;
using System.Threading;
+using MongoDB.Connections;
using NUnit.Framework;
-namespace MongoDB.Driver.Connections
+namespace MongoDB.IntegrationTests.Connections
{
[TestFixture]
public class TestPooledConnectionFactory
@@ -10,7 +11,7 @@ public class TestPooledConnectionFactory
[TestFixtureSetUp]
public void SetUp()
{
- ConnectionFactory.Shutdown();
+ ConnectionFactoryFactory.Shutdown();
}
[Test]
@@ -87,28 +88,6 @@ public void TestExceptionIfMaximumPoolSizeAndConnectionTimeoutAreReached()
}
}
- [Test]
- public void TestServerCirculationWorks()
- {
- var builder = new MongoConnectionStringBuilder();
- builder.AddServer("localhost");
- builder.AddServer("localhost", 27018);
- builder.AddServer("localhost", 27019);
- using(var pool = new PooledConnectionFactory(builder.ToString()))
- {
- var connection1 = pool.Open();
- var connection2 = pool.Open();
- var connection3 = pool.Open();
- var connection4 = pool.Open();
- var connection5 = pool.Open();
- Assert.AreEqual(27017, connection1.EndPoint.Port);
- Assert.AreEqual(27018, connection2.EndPoint.Port);
- Assert.AreEqual(27019, connection3.EndPoint.Port);
- Assert.AreEqual(27017, connection4.EndPoint.Port);
- Assert.AreEqual(27018, connection5.EndPoint.Port);
- }
- }
-
[Test]
public void TestBorrowOneConnection()
{
@@ -159,7 +138,7 @@ public void TestDisconnectedConnectionsArentReturndToPool()
}
[Test]
- public void TestIfConnectionLifetimeIsReachedItDosenotReturndToPool()
+ public void TestIfConnectionLifetimeIsReachedItDoesNotReturndToPool()
{
var builder = new MongoConnectionStringBuilder
{
diff --git a/MongoDB.Net-Tests/Connections/TestSimpleConnectionFactory.cs b/source/MongoDB.Tests/IntegrationTests/Connections/TestSimpleConnectionFactory.cs
similarity index 88%
rename from MongoDB.Net-Tests/Connections/TestSimpleConnectionFactory.cs
rename to source/MongoDB.Tests/IntegrationTests/Connections/TestSimpleConnectionFactory.cs
index 78593ded..47c1ff9b 100644
--- a/MongoDB.Net-Tests/Connections/TestSimpleConnectionFactory.cs
+++ b/source/MongoDB.Tests/IntegrationTests/Connections/TestSimpleConnectionFactory.cs
@@ -1,6 +1,7 @@
+using MongoDB.Connections;
using NUnit.Framework;
-namespace MongoDB.Driver.Connections
+namespace MongoDB.IntegrationTests.Connections
{
[TestFixture]
public class TestSimpleConnectionFactory
diff --git a/source/MongoDB.Tests/IntegrationTests/Inheritance/TestInheritanceWithAbstractBaseClass.cs b/source/MongoDB.Tests/IntegrationTests/Inheritance/TestInheritanceWithAbstractBaseClass.cs
new file mode 100644
index 00000000..c3fd8b18
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/Inheritance/TestInheritanceWithAbstractBaseClass.cs
@@ -0,0 +1,280 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests.Inheritance
+{
+ [TestFixture]
+ public class TestInheritanceWithAbstractBaseClass : MongoTestBase
+ {
+ abstract class Animal
+ {
+ public Oid Id { get; set; }
+
+ public int Age { get; set; }
+
+ public string Name { get; set; }
+ }
+
+ class Bear : Animal
+ { }
+
+ abstract class Cat : Animal
+ { }
+
+ class Tiger : Cat
+ { }
+
+ class Lion : Cat
+ { }
+
+ public override string TestCollections
+ {
+ get { return "Animal"; }
+ }
+
+ [SetUp]
+ public void TestSetup()
+ {
+ CleanDB();
+ }
+
+ protected override Configuration.MongoConfigurationBuilder GetConfiguration()
+ {
+ var builder = base.GetConfiguration();
+ builder.Mapping(mapping =>
+ {
+ mapping.DefaultProfile(profile =>
+ {
+ profile.SubClassesAre(x => x.IsSubclassOf(typeof(Animal)));
+ });
+
+ mapping.Map();
+ mapping.Map();
+ mapping.Map();
+ mapping.Map();
+ });
+
+ return builder;
+ }
+
+ [Test]
+ public void Should_persist_discriminator_using_base_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var docCollection = DB.GetCollection("Animal");
+
+ var docs = docCollection.FindAll().Sort("Age", IndexOrder.Ascending).Documents.ToList();
+
+ Assert.AreEqual(new[] { "Cat", "Tiger" }, (List)docs[0]["_t"]);
+ Assert.AreEqual("Bear", (string)docs[1]["_t"]);
+ }
+
+ [Test]
+ public void Should_persist_discriminator_using_concrete_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Lion() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var docCollection = DB.GetCollection("Animal");
+
+ var docs = docCollection.FindAll().Sort("Age", IndexOrder.Ascending).Documents.ToList();
+
+ Assert.AreEqual(new[] { "Cat", "Tiger" }, (List)docs[0]["_t"]);
+ Assert.AreEqual(new[] { "Cat", "Lion" }, (List)docs[1]["_t"]);
+ }
+
+ [Test]
+ public void Should_fetch_with_base_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var animals = animalCollection.FindAll().Sort("Age", IndexOrder.Ascending).Documents.ToList();
+
+ Assert.AreEqual(2, animals.Count);
+ Assert.IsInstanceOfType(typeof(Tiger), animals[0]);
+ Assert.AreEqual(19, animals[0].Age);
+ Assert.AreEqual("Bob", animals[0].Name);
+ Assert.IsInstanceOfType(typeof(Bear), animals[1]);
+ Assert.AreEqual(20, animals[1].Age);
+ Assert.AreEqual("Jim", animals[1].Name);
+ }
+
+ [Test]
+ public void Should_fetch_with_base_class_collection_through_linq()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var animals = (from a in animalCollection.Linq()
+ orderby a.Age ascending
+ select a).ToList();
+
+ Assert.AreEqual(2, animals.Count);
+ Assert.IsInstanceOfType(typeof(Tiger), animals[0]);
+ Assert.AreEqual(19, animals[0].Age);
+ Assert.AreEqual("Bob", animals[0].Name);
+ Assert.IsInstanceOfType(typeof(Bear), animals[1]);
+ Assert.AreEqual(20, animals[1].Age);
+ Assert.AreEqual("Jim", animals[1].Name);
+ }
+
+ [Test]
+ public void Should_support_projections_with_base_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var animals = animalCollection.FindAll().Fields(new { Age = true }).Sort("Age", IndexOrder.Ascending).Documents.ToList();
+
+ Assert.AreEqual(2, animals.Count);
+ Assert.IsInstanceOfType(typeof(Tiger), animals[0]);
+ Assert.AreEqual(19, animals[0].Age);
+ Assert.IsNull(animals[0].Name);
+ Assert.IsInstanceOfType(typeof(Bear), animals[1]);
+ Assert.AreEqual(20, animals[1].Age);
+ Assert.IsNull(animals[1].Name);
+ }
+
+ [Test]
+ public void Should_support_projections_with_base_class_collections_with_linq()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var animals = (from a in animalCollection.Linq()
+ orderby a.Age ascending
+ select new { a.Name, a.Age }).ToList();
+
+ Assert.AreEqual(2, animals.Count);
+ Assert.AreEqual(19, animals[0].Age);
+ Assert.AreEqual("Bob", animals[0].Name);
+ Assert.AreEqual(20, animals[1].Age);
+ Assert.AreEqual("Jim", animals[1].Name);
+ }
+
+ [Test]
+ public void Should_support_projections_with_concrete_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var catCollection = DB.GetCollection();
+
+ var cats = catCollection.FindAll().Fields(new { Age = true }).Sort("Age", IndexOrder.Ascending).Documents.ToList();
+
+ Assert.AreEqual(1, cats.Count);
+ Assert.IsInstanceOfType(typeof(Tiger), cats[0]);
+ Assert.AreEqual(19, cats[0].Age);
+ Assert.IsNull(cats[0].Name);
+ }
+
+ [Test]
+ public void Should_support_projections_with_concrete_class_collections_with_linq()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var catCollection = DB.GetCollection();
+
+ var cats = (from a in catCollection.Linq()
+ orderby a.Age ascending
+ select new { a.Name, a.Age }).ToList();
+
+ Assert.AreEqual(1, cats.Count);
+ Assert.AreEqual(19, cats[0].Age);
+ Assert.AreEqual("Bob", cats[0].Name);
+ }
+
+ [Test]
+ public void Should_fetch_with_concrete_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var catCollection = DB.GetCollection();
+
+ var cats = catCollection.FindAll().Sort("Age", IndexOrder.Ascending).Documents.ToList();
+
+ Assert.AreEqual(1, cats.Count);
+ Assert.IsInstanceOfType(typeof(Tiger), cats[0]);
+ Assert.AreEqual(19, cats[0].Age);
+ }
+
+ [Test]
+ public void Should_fetch_with_concrete_class_collection_through_linq()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var catCollection = DB.GetCollection();
+
+ var animals = (from a in catCollection.Linq()
+ orderby a.Age ascending
+ select a).ToList();
+
+ Assert.AreEqual(1, animals.Count);
+ Assert.IsInstanceOfType(typeof(Tiger), animals[0]);
+ Assert.AreEqual(19, animals[0].Age);
+ }
+
+ [Test]
+ public void Should_get_correct_count_with_base_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ Assert.AreEqual(2, animalCollection.Count());
+ }
+
+ [Test]
+ public void Should_get_correct_count_with_base_class_collection_using_linq()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ Assert.AreEqual(2, animalCollection.Linq().Count());
+ }
+
+ [Test]
+ public void Should_get_correct_count_with_concrete_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20 });
+ animalCollection.Save(new Tiger() { Age = 19 });
+
+ var catCollection = DB.GetCollection();
+
+ Assert.AreEqual(1, catCollection.Count());
+ }
+
+ [Test]
+ public void Should_get_correct_count_with_concrete_class_collection_using_linq()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Bear() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var catCollection = DB.GetCollection();
+
+ Assert.AreEqual(1, catCollection.Linq().Count());
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/IntegrationTests/Inheritance/TestInheritanceWithConcreteBaseClass.cs b/source/MongoDB.Tests/IntegrationTests/Inheritance/TestInheritanceWithConcreteBaseClass.cs
new file mode 100644
index 00000000..953497df
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/Inheritance/TestInheritanceWithConcreteBaseClass.cs
@@ -0,0 +1,276 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests.Inheritance
+{
+ [TestFixture]
+ public class TestInheritanceWithConcreteBaseClass : MongoTestBase
+ {
+ class Animal
+ {
+ public Oid Id { get; set; }
+
+ public int Age { get; set; }
+
+ public string Name { get; set; }
+ }
+
+ class Bear : Animal
+ { }
+
+ abstract class Cat : Animal
+ { }
+
+ class Tiger : Cat
+ { }
+
+ class Lion : Cat
+ { }
+
+ public override string TestCollections
+ {
+ get { return "Animal"; }
+ }
+
+ [SetUp]
+ public void TestSetup()
+ {
+ CleanDB();
+ }
+
+ protected override Configuration.MongoConfigurationBuilder GetConfiguration()
+ {
+ var builder = base.GetConfiguration();
+ builder.Mapping(mapping =>
+ {
+ mapping.DefaultProfile(profile =>
+ {
+ profile.SubClassesAre(x => x.IsSubclassOf(typeof(Animal)));
+ });
+
+ mapping.Map();
+ mapping.Map();
+ mapping.Map();
+ mapping.Map();
+ });
+
+ return builder;
+ }
+
+ [Test]
+ public void Should_persist_discriminator_using_base_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20 });
+ animalCollection.Save(new Tiger() { Age = 19 });
+
+ var docCollection = DB.GetCollection("Animal");
+
+ var docs = docCollection.FindAll().Sort("Age", IndexOrder.Ascending).Documents.ToList();
+
+ Assert.AreEqual(new[] { "Cat", "Tiger" }, (List)docs[0]["_t"]);
+ Assert.IsNull(docs[1]["_t"]);
+ }
+
+ [Test]
+ public void Should_persist_discriminator_using_inherited_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Lion() { Age = 20 });
+ animalCollection.Save(new Tiger() { Age = 19 });
+
+ var docCollection = DB.GetCollection("Animal");
+
+ var docs = docCollection.FindAll().Sort("Age", IndexOrder.Ascending).Documents.ToList();
+
+ Assert.AreEqual(new[] { "Cat", "Tiger" }, (List)docs[0]["_t"]);
+ Assert.AreEqual(new[] { "Cat", "Lion" }, (List)docs[1]["_t"]);
+ }
+
+ [Test]
+ public void Should_fetch_with_base_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20 });
+ animalCollection.Save(new Tiger() { Age = 19 });
+
+ var animals = animalCollection.FindAll().Sort("Age", IndexOrder.Ascending).Documents.ToList();
+
+ Assert.AreEqual(2, animals.Count);
+ Assert.IsInstanceOfType(typeof(Tiger), animals[0]);
+ Assert.AreEqual(19, animals[0].Age);
+ Assert.IsInstanceOfType(typeof(Animal), animals[1]);
+ Assert.AreEqual(20, animals[1].Age);
+ }
+
+ [Test]
+ public void Should_fetch_with_base_class_collection_through_linq()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20 });
+ animalCollection.Save(new Tiger() { Age = 19 });
+
+ var animals = (from a in animalCollection.Linq()
+ orderby a.Age ascending
+ select a).ToList();
+
+ Assert.AreEqual(2, animals.Count);
+ Assert.IsInstanceOfType(typeof(Tiger), animals[0]);
+ Assert.AreEqual(19, animals[0].Age);
+ Assert.IsInstanceOfType(typeof(Animal), animals[1]);
+ Assert.AreEqual(20, animals[1].Age);
+ }
+
+ [Test]
+ public void Should_fetch_with_inherited_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20 });
+ animalCollection.Save(new Tiger() { Age = 19 });
+
+ var catCollection = DB.GetCollection();
+
+ var cats = catCollection.FindAll().Sort("Age", IndexOrder.Ascending).Documents.ToList();
+
+ Assert.AreEqual(1, cats.Count);
+ Assert.IsInstanceOfType(typeof(Tiger), cats[0]);
+ Assert.AreEqual(19, cats[0].Age);
+ }
+
+ [Test]
+ public void Should_fetch_with_inherited_class_collection_through_linq()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20 });
+ animalCollection.Save(new Tiger() { Age = 19 });
+
+ var catCollection = DB.GetCollection();
+
+ var animals = (from a in catCollection.Linq()
+ orderby a.Age ascending
+ select a).ToList();
+
+ Assert.AreEqual(1, animals.Count);
+ Assert.IsInstanceOfType(typeof(Tiger), animals[0]);
+ Assert.AreEqual(19, animals[0].Age);
+ }
+
+ [Test]
+ public void Should_support_projections_with_base_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var animals = animalCollection.FindAll().Fields(new { Age = true }).Sort("Age", IndexOrder.Ascending).Documents.ToList();
+
+ Assert.AreEqual(2, animals.Count);
+ Assert.IsInstanceOfType(typeof(Tiger), animals[0]);
+ Assert.AreEqual(19, animals[0].Age);
+ Assert.IsNull(animals[0].Name);
+ Assert.IsInstanceOfType(typeof(Animal), animals[1]);
+ Assert.AreEqual(20, animals[1].Age);
+ Assert.IsNull(animals[1].Name);
+ }
+
+ [Test]
+ public void Should_support_projections_with_base_class_collections_with_linq()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var animals = (from a in animalCollection.Linq()
+ orderby a.Age ascending
+ select new { a.Name, a.Age }).ToList();
+
+ Assert.AreEqual(2, animals.Count);
+ Assert.AreEqual(19, animals[0].Age);
+ Assert.AreEqual("Bob", animals[0].Name);
+ Assert.AreEqual(20, animals[1].Age);
+ Assert.AreEqual("Jim", animals[1].Name);
+ }
+
+ [Test]
+ public void Should_support_projections_with_inherited_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var catCollection = DB.GetCollection();
+
+ var cats = catCollection.FindAll().Fields(new { Age = true }).Sort("Age", IndexOrder.Ascending).Documents.ToList();
+
+ Assert.AreEqual(1, cats.Count);
+ Assert.IsInstanceOfType(typeof(Tiger), cats[0]);
+ Assert.AreEqual(19, cats[0].Age);
+ Assert.IsNull(cats[0].Name);
+ }
+
+ [Test]
+ public void Should_support_projections_with_inherited_class_collections_with_linq()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20, Name = "Jim" });
+ animalCollection.Save(new Tiger() { Age = 19, Name = "Bob" });
+
+ var catCollection = DB.GetCollection();
+
+ var cats = (from a in catCollection.Linq()
+ orderby a.Age ascending
+ select new { a.Name, a.Age }).ToList();
+
+ Assert.AreEqual(1, cats.Count);
+ Assert.AreEqual(19, cats[0].Age);
+ Assert.AreEqual("Bob", cats[0].Name);
+ }
+
+ [Test]
+ public void Should_get_correct_count_with_base_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20 });
+ animalCollection.Save(new Tiger() { Age = 19 });
+
+ Assert.AreEqual(2, animalCollection.Count());
+ }
+
+ [Test]
+ public void Should_get_correct_count_with_base_class_collection_using_linq()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20 });
+ animalCollection.Save(new Tiger() { Age = 19 });
+
+ Assert.AreEqual(2, animalCollection.Linq().Count());
+ }
+
+ [Test]
+ public void Should_get_correct_count_with_inherited_class_collection()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20 });
+ animalCollection.Save(new Tiger() { Age = 19 });
+
+ var catCollection = DB.GetCollection();
+
+ Assert.AreEqual(1, catCollection.Count());
+ }
+
+ [Test]
+ public void Should_get_correct_count_with_inherited_class_collection_using_linq()
+ {
+ var animalCollection = DB.GetCollection();
+ animalCollection.Save(new Animal() { Age = 20 });
+ animalCollection.Save(new Tiger() { Age = 19 });
+
+ var catCollection = DB.GetCollection();
+
+ Assert.AreEqual(1, catCollection.Linq().Count());
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/IntegrationTests/Linq/LinqDomain.cs b/source/MongoDB.Tests/IntegrationTests/Linq/LinqDomain.cs
new file mode 100644
index 00000000..cfa370df
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/Linq/LinqDomain.cs
@@ -0,0 +1,60 @@
+using System;
+using System.Collections.Generic;
+
+using MongoDB.Attributes;
+
+namespace MongoDB.IntegrationTests.Linq
+{
+ public class Person
+ {
+ [MongoAlias("fn")]
+ public string FirstName { get; set; }
+
+ [MongoAlias("ln")]
+ public string LastName { get; set; }
+
+ [MongoAlias("age")]
+ public int Age { get; set; }
+
+ [MongoAlias("add")]
+ public Address PrimaryAddress { get; set; }
+
+ [MongoAlias("otherAdds")]
+ public List Addresses { get; set; }
+
+ [MongoAlias("emps")]
+ public int[] EmployerIds { get; set; }
+
+ public string MidName { get; set; }
+
+ public Oid LinkedId { get; set; }
+ }
+
+ public class Address
+ {
+ [MongoAlias("city")]
+ public string City { get; set; }
+
+ public bool IsInternational { get; set; }
+
+ public AddressType AddressType { get; set; }
+ }
+
+ public enum AddressType
+ {
+ Company,
+ Private
+ }
+
+ public class PersonWrapper
+ {
+ public Person Person { get; set; }
+ public string Name { get; set; }
+
+ public PersonWrapper(Person person, string name)
+ {
+ Person = person;
+ Name = name;
+ }
+ }
+}
diff --git a/source/MongoDB.Tests/IntegrationTests/Linq/LinqExtensionsTests.cs b/source/MongoDB.Tests/IntegrationTests/Linq/LinqExtensionsTests.cs
new file mode 100644
index 00000000..22451e62
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/Linq/LinqExtensionsTests.cs
@@ -0,0 +1,83 @@
+using System.Linq;
+using MongoDB.Linq;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests.Linq
+{
+ [TestFixture]
+ public class LinqExtensionsTests : MongoTestBase
+ {
+ private class Person
+ {
+ public string FirstName { get; set; }
+
+ public string LastName { get; set; }
+
+ public int Age { get; set; }
+
+ public Address Address { get; set; }
+
+ public string[] Aliases { get; set; }
+ }
+
+ private class Address
+ {
+ public string City { get; set; }
+ }
+
+ private class Organization
+ {
+ public string Name { get; set; }
+
+ public Address Address { get; set; }
+ }
+
+ private IMongoCollection personCollection;
+ private IMongoCollection orgCollection;
+
+ public override string TestCollections
+ {
+ get { return "people"; }
+ }
+
+ [SetUp]
+ public void TestSetup()
+ {
+ personCollection = this.DB.GetCollection("people");
+ personCollection.Delete(new { }, true);
+ personCollection.Insert(new Person { FirstName = "Bob", LastName = "McBob", Age = 42, Address = new Address { City = "London" }, Aliases = new[]{"Blub"} }, true);
+ personCollection.Insert(new Person { FirstName = "Jane", LastName = "McJane", Age = 35, Address = new Address { City = "Paris" } }, true);
+ personCollection.Insert(new Person { FirstName = "Joe", LastName = "McJoe", Age = 21, Address = new Address { City = "Chicago" } }, true);
+
+ orgCollection = this.DB.GetCollection("orgs");
+ orgCollection.Delete(new { }, true);
+ orgCollection.Insert(new Organization { Name = "The Muffler Shanty", Address = new Address { City = "London" } }, true);
+ }
+
+ [Test]
+ public void Delete()
+ {
+ personCollection.Delete(p => true);
+
+ Assert.AreEqual(0, personCollection.Count());
+ }
+
+ [Test]
+ public void Find()
+ {
+ var people = personCollection.Find(x => x.Age > 21).Documents;
+
+ Assert.AreEqual(2, people.Count());
+ }
+
+ [Test]
+ public void FindOne_WithAny()
+ {
+ var person = personCollection.FindOne(e => e.Aliases.Any(a=>a=="Blub"));
+
+ Assert.IsNotNull(person);
+ Assert.AreEqual("Bob",person.FirstName);
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/IntegrationTests/Linq/LinqTestsBase.cs b/source/MongoDB.Tests/IntegrationTests/Linq/LinqTestsBase.cs
new file mode 100644
index 00000000..bd376037
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/Linq/LinqTestsBase.cs
@@ -0,0 +1,22 @@
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests.Linq
+{
+ public class LinqTestsBase : MongoTestBase
+ {
+ public override string TestCollections
+ {
+ get { return "people"; }
+ }
+
+ protected IMongoCollection Collection;
+ protected IMongoCollection DocumentCollection;
+
+ [SetUp]
+ public virtual void TestSetup()
+ {
+ Collection = DB.GetCollection("people");
+ DocumentCollection = DB.GetCollection("people");
+ }
+ }
+}
diff --git a/source/MongoDB.Tests/IntegrationTests/Linq/MapReduceTests.cs b/source/MongoDB.Tests/IntegrationTests/Linq/MapReduceTests.cs
new file mode 100644
index 00000000..f27cd317
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/Linq/MapReduceTests.cs
@@ -0,0 +1,175 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+
+using MongoDB.Linq;
+
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests.Linq
+{
+ [TestFixture]
+ public class MapReduceTests : LinqTestsBase
+ {
+ public override void TestSetup()
+ {
+ base.TestSetup();
+
+ Collection.Delete(new { }, true);
+ Collection.Insert(
+ new Person
+ {
+ FirstName = "Bob",
+ LastName = "McBob",
+ Age = 42,
+ PrimaryAddress = new Address { City = "London" },
+ Addresses = new List
+ {
+ new Address { City = "London" },
+ new Address { City = "Tokyo" },
+ new Address { City = "Seattle" }
+ },
+ EmployerIds = new[] { 1, 2 }
+ }, true);
+
+ Collection.Insert(
+ new Person
+ {
+ FirstName = "Jane",
+ LastName = "McJane",
+ Age = 35,
+ PrimaryAddress = new Address { City = "Paris" },
+ Addresses = new List
+ {
+ new Address { City = "Paris" }
+ },
+ EmployerIds = new[] { 1 }
+
+ }, true);
+
+ Collection.Insert(
+ new Person
+ {
+ FirstName = "Joe",
+ LastName = "McJoe",
+ Age = 21,
+ PrimaryAddress = new Address { City = "Chicago" },
+ Addresses = new List
+ {
+ new Address { City = "Chicago" },
+ new Address { City = "London" }
+ },
+ EmployerIds = new[] { 3 }
+ }, true);
+ }
+
+ [Test]
+ public void Off_of_select()
+ {
+ var minAge = Collection.Linq().Select(x => x.Age).Min();
+
+ Assert.AreEqual(21, minAge);
+ }
+
+ [Test]
+ public void Off_of_root()
+ {
+ var minAge = Collection.Linq().Min(x => x.Age);
+
+ Assert.AreEqual(21, minAge);
+ }
+
+ [Test]
+ public void NoGrouping()
+ {
+ var grouping = Enumerable.ToList(from p in Collection.Linq()
+ where p.Age > 21
+ group p by 1 into g
+ select new
+ {
+ Average = g.Average(x => x.Age),
+ Min = g.Min(x => x.Age),
+ Max = g.Max(x => x.Age),
+ Count = g.Count(),
+ Sum = g.Sum(x => x.Age)
+ });
+
+ Assert.AreEqual(1, grouping.Count);
+ Assert.AreEqual(38.5, grouping.Single().Average);
+ Assert.AreEqual(35, grouping.Single().Min);
+ Assert.AreEqual(42, grouping.Single().Max);
+ Assert.AreEqual(2, grouping.Single().Count);
+ Assert.AreEqual(77, grouping.Single().Sum);
+ }
+
+ [Test]
+ public void Expression_Grouping()
+ {
+ var grouping = Enumerable.ToList(from p in Collection.Linq()
+ group p by p.Age % 2 into g
+ select new
+ {
+ IsEven = g.Key == 0,
+ Min = g.Min(x => x.Age),
+ Max = g.Max(x => x.Age),
+ Count = g.Count(),
+ Sum = g.Sum(x => x.Age)
+ });
+
+ Assert.AreEqual(2, grouping.Count);
+ Assert.AreEqual(1, grouping[0].Count);
+ Assert.AreEqual(42, grouping[0].Max);
+ Assert.AreEqual(42, grouping[0].Min);
+ Assert.AreEqual(42, grouping[0].Sum);
+ Assert.AreEqual(2, grouping[1].Count);
+ Assert.AreEqual(35, grouping[1].Max);
+ Assert.AreEqual(21, grouping[1].Min);
+ Assert.AreEqual(56, grouping[1].Sum);
+ }
+
+ [Test]
+ public void Expression_Grouping2()
+ {
+ var grouping = Enumerable.ToList(from p in Collection.Linq()
+ group p by p.FirstName[0] into g
+ select new
+ {
+ FirstLetter = g.Key,
+ Min = g.Min(x => x.Age),
+ Max = g.Max(x => x.Age)
+ });
+
+ Assert.AreEqual(2, grouping.Count);
+ Assert.AreEqual('B', grouping[0].FirstLetter);
+ Assert.AreEqual(42, grouping[0].Max);
+ Assert.AreEqual(42, grouping[0].Min);
+ Assert.AreEqual('J', grouping[1].FirstLetter);
+ Assert.AreEqual(35, grouping[1].Max);
+ Assert.AreEqual(21, grouping[1].Min);
+ }
+
+ [Test]
+ public void Complex()
+ {
+ var grouping = Enumerable.ToList(from p in Collection.Linq()
+ where p.Age > 21
+ group p by new { FirstName = p.FirstName, LastName = p.LastName } into g
+ select new
+ {
+ Name = g.Key.FirstName + " " + g.Key.LastName,
+ Min = g.Min(x => x.Age) + 100,
+ Max = g.Max(x => x.Age) + 100
+ });
+
+ Assert.AreEqual(2, grouping.Count);
+ Assert.AreEqual("Bob McBob", grouping[0].Name);
+ Assert.AreEqual(142, grouping[0].Max);
+ Assert.AreEqual(142, grouping[0].Min);
+ Assert.AreEqual("Jane McJane", grouping[1].Name);
+ Assert.AreEqual(135, grouping[1].Max);
+ Assert.AreEqual(135, grouping[1].Min);
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/IntegrationTests/Linq/MongoQueryProviderTests.cs b/source/MongoDB.Tests/IntegrationTests/Linq/MongoQueryProviderTests.cs
new file mode 100644
index 00000000..8d10e377
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/Linq/MongoQueryProviderTests.cs
@@ -0,0 +1,447 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+using MongoDB.Linq;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests.Linq
+{
+ [TestFixture]
+ public class MongoQueryProviderTests : LinqTestsBase
+ {
+ [Test]
+ public void Boolean1()
+ {
+ var people = Collection.Linq().Where(x => x.PrimaryAddress.IsInternational);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(new Document("PrimaryAddress.IsInternational", true), queryObject.Query);
+ }
+
+ [Test]
+ public void Boolean_Inverse()
+ {
+ var people = Collection.Linq().Where(x => !x.PrimaryAddress.IsInternational);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(new Document("$not", new Document("PrimaryAddress.IsInternational", true)), queryObject.Query);
+ }
+
+ [Test]
+ public void Boolean_In_Conjunction()
+ {
+ var people = Collection.Linq().Where(x => x.PrimaryAddress.IsInternational && x.Age > 21);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(new Document("PrimaryAddress.IsInternational", true).Add("Age", Op.GreaterThan(21)), queryObject.Query);
+ }
+
+ [Test]
+ public void Chained()
+ {
+ var people = Collection.Linq()
+ .Select(x => new {Name = x.FirstName + x.LastName, x.Age})
+ .Where(x => x.Age > 21)
+ .Select(x => x.Name);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(2, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("Age", Op.GreaterThan(21)), queryObject.Query);
+ }
+
+ [Test]
+ public void ConjuctionConstraint()
+ {
+ var people = Collection.Linq().Where(p => p.Age > 21 && p.Age < 42);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("Age", new Document().Merge(Op.GreaterThan(21)).Merge(Op.LessThan(42))), queryObject.Query);
+ }
+
+ [Test]
+ public void ConstraintsAgainstLocalReferenceMember()
+ {
+ var local = new {Test = new {Age = 21}};
+ var people = Collection.Linq().Where(p => p.Age > local.Test.Age);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("Age", Op.GreaterThan(local.Test.Age)), queryObject.Query);
+ }
+
+ [Test]
+ public void ConstraintsAgainstLocalVariable()
+ {
+ var age = 21;
+ var people = Collection.Linq().Where(p => p.Age > age);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("Age", Op.GreaterThan(age)), queryObject.Query);
+ }
+
+ [Test]
+ [Ignore("Something is interesting about document comparison that causes this to fail.")]
+ public void Disjunction()
+ {
+ var people = Collection.Linq().Where(x => x.Age == 21 || x.Age == 35);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("$where", new Code("((this.Age === 21) || (this.Age === 35))")), queryObject.Query);
+ }
+
+ [Test]
+ public void DocumentQuery()
+ {
+ var people = from p in DocumentCollection.Linq()
+ where p.Key("Age") > 21
+ select (string)p["FirstName"];
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(new Document("FirstName", 1), queryObject.Fields);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("Age", Op.GreaterThan(21)), queryObject.Query);
+ }
+
+ [Test]
+ public void Enum()
+ {
+ var people = Collection.Linq().Where(x => x.PrimaryAddress.AddressType == AddressType.Company);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("PrimaryAddress.AddressType", (int)AddressType.Company), queryObject.Query);
+ }
+
+ [Test]
+ public void LocalEnumerable_Contains()
+ {
+ var names = new[] {"Jack", "Bob"};
+ var people = Collection.Linq().Where(x => names.Contains(x.FirstName));
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("FirstName", Op.In("Jack", "Bob")), queryObject.Query);
+ }
+
+ [Test]
+ public void LocalList_Contains()
+ {
+ var names = new List {"Jack", "Bob"};
+ var people = Collection.Linq().Where(x => names.Contains(x.FirstName));
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("FirstName", Op.In("Jack", "Bob")), queryObject.Query);
+ }
+
+ [Test]
+ public void NestedArray_Length()
+ {
+ var people = from p in Collection.Linq()
+ where p.EmployerIds.Length == 1
+ select p;
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("EmployerIds", Op.Size(1)), queryObject.Query);
+ }
+
+ [Test]
+ public void NestedArray_indexer()
+ {
+ var people = Collection.Linq().Where(x => x.EmployerIds[0] == 1);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("EmployerIds.0", 1), queryObject.Query);
+ }
+
+ [Test]
+ public void NestedClassConstraint()
+ {
+ var people = Collection.Linq().Where(p => p.PrimaryAddress.City == "my city");
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("PrimaryAddress.City", "my city"), queryObject.Query);
+ }
+
+ [Test]
+ public void NestedCollection_Count()
+ {
+ var people = from p in Collection.Linq()
+ where p.Addresses.Count == 1
+ select p;
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("Addresses", Op.Size(1)), queryObject.Query);
+ }
+
+ [Test]
+ public void NestedList_indexer()
+ {
+ var people = Collection.Linq().Where(x => x.Addresses[1].City == "Tokyo");
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("Addresses.1.City", "Tokyo"), queryObject.Query);
+ }
+
+ [Test]
+ public void NestedQueryable_Any()
+ {
+ var people = Collection.Linq().Where(x => x.Addresses.Any(a => a.City == "London"));
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("Addresses", new Document("$elemMatch", new Document("City", "London"))), queryObject.Query);
+ }
+
+ [Test]
+ public void NestedQueryable_Contains()
+ {
+ var people = Collection.Linq().Where(x => x.EmployerIds.Contains(1));
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("EmployerIds", 1), queryObject.Query);
+ }
+
+ [Test]
+ public void Nested_Queryable_Count()
+ {
+ var people = Collection.Linq().Where(x => x.Addresses.Count() == 1);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("Addresses", Op.Size(1)), queryObject.Query);
+ }
+
+ [Test]
+ public void Nested_Queryable_ElementAt()
+ {
+ var people = Collection.Linq().Where(x => x.Addresses.ElementAt(1).City == "Tokyo");
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("Addresses.1.City", "Tokyo"), queryObject.Query);
+ }
+
+ [Test]
+ public void NotNullCheck()
+ {
+ var people = Collection.Linq().Where(x => x.MidName != null);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("MidName", Op.NotEqual(null)), queryObject.Query);
+ }
+
+ [Test]
+ public void NullCheck()
+ {
+ var people = Collection.Linq().Where(x => x.MidName == null);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("MidName", null), queryObject.Query);
+ }
+
+ [Test]
+ public void OrderBy()
+ {
+ var people = Collection.Linq().OrderBy(x => x.Age).ThenByDescending(x => x.LastName);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("Age", 1).Add("LastName", -1), queryObject.Sort);
+ }
+
+ [Test]
+ public void Projection()
+ {
+ var people = from p in Collection.Linq()
+ select new {Name = p.FirstName + p.LastName};
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(2, queryObject.Fields.Count());
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(0, queryObject.Query.Count);
+ }
+
+ [Test]
+ public void ProjectionWithConstraints()
+ {
+ var people = from p in Collection.Linq()
+ where p.Age > 21 && p.Age < 42
+ select new {Name = p.FirstName + p.LastName};
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(2, queryObject.Fields.Count());
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("Age", new Document().Merge(Op.GreaterThan(21)).Merge(Op.LessThan(42))), queryObject.Query);
+ }
+
+ [Test]
+ public void ProjectionWithLocalCreation_ChildobjectShouldNotBeNull()
+ {
+ var people = Collection.Linq()
+ .Select(p => new PersonWrapper(p, p.FirstName));
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count());
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(0, queryObject.Query.Count);
+
+ }
+
+ [Test]
+ public void Regex_IsMatch()
+ {
+ var people = from p in Collection.Linq()
+ where Regex.IsMatch(p.FirstName, "Joe")
+ select p;
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("FirstName", new MongoRegex("Joe")), queryObject.Query);
+ }
+
+ [Test]
+ public void Regex_IsMatch_CaseInsensitive()
+ {
+ var people = from p in Collection.Linq()
+ where Regex.IsMatch(p.FirstName, "Joe", RegexOptions.IgnoreCase)
+ select p;
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("FirstName", new MongoRegex("Joe", MongoRegexOption.IgnoreCase)), queryObject.Query);
+ }
+
+ [Test]
+ public void SingleEqualConstraint()
+ {
+ var people = Collection.Linq().Where(p => "Jack" == p.FirstName);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("FirstName", "Jack"), queryObject.Query);
+ }
+
+ [Test]
+ public void SkipAndTake()
+ {
+ var people = Collection.Linq().Skip(2).Take(1);
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(1, queryObject.NumberToLimit);
+ Assert.AreEqual(2, queryObject.NumberToSkip);
+ }
+
+ [Test]
+ public void String_Contains()
+ {
+ var people = from p in Collection.Linq()
+ where p.FirstName.Contains("o")
+ select p;
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("FirstName", new MongoRegex("o")), queryObject.Query);
+ }
+
+ [Test]
+ public void String_EndsWith()
+ {
+ var people = from p in Collection.Linq()
+ where p.FirstName.EndsWith("e")
+ select p;
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("FirstName", new MongoRegex("e$")), queryObject.Query);
+ }
+
+ [Test]
+ public void String_StartsWith()
+ {
+ var people = from p in Collection.Linq()
+ where p.FirstName.StartsWith("J")
+ select p;
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+ Assert.AreEqual(0, queryObject.Fields.Count);
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(new Document("FirstName", new MongoRegex("^J")), queryObject.Query);
+ }
+
+ [Test]
+ public void WithoutConstraints()
+ {
+ var people = Collection.Linq();
+
+ var queryObject = ((IMongoQueryable)people).GetQueryObject();
+
+ Assert.AreEqual(0, queryObject.NumberToLimit);
+ Assert.AreEqual(0, queryObject.NumberToSkip);
+ Assert.AreEqual(0, queryObject.Query.Count);
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/IntegrationTests/Linq/MongoQueryTests.cs b/source/MongoDB.Tests/IntegrationTests/Linq/MongoQueryTests.cs
new file mode 100644
index 00000000..94ae8908
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/Linq/MongoQueryTests.cs
@@ -0,0 +1,445 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+using MongoDB.Linq;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests.Linq
+{
+ [TestFixture]
+ public class MongoQueryTests : LinqTestsBase
+ {
+ public override void TestSetup()
+ {
+ base.TestSetup();
+
+ Collection.Delete(new {}, true);
+ Collection.Insert(
+ new Person
+ {
+ FirstName = "Bob",
+ MidName = "Bart",
+ LastName = "McBob",
+ Age = 42,
+ PrimaryAddress = new Address {City = "London", IsInternational = true, AddressType = AddressType.Company},
+ Addresses = new List
+ {
+ new Address { City = "London", IsInternational = true, AddressType = AddressType.Company },
+ new Address { City = "Tokyo", IsInternational = true, AddressType = AddressType.Private },
+ new Address { City = "Seattle", IsInternational = false, AddressType = AddressType.Private }
+ },
+ EmployerIds = new[] { 1, 2 }
+ }, true);
+
+ Collection.Insert(
+ new Person
+ {
+ FirstName = "Jane",
+ LastName = "McJane",
+ Age = 35,
+ PrimaryAddress = new Address { City = "Paris", IsInternational = false, AddressType = AddressType.Private },
+ Addresses = new List
+ {
+ new Address { City = "Paris", AddressType = AddressType.Private }
+ },
+ EmployerIds = new[] {1}
+ },
+ true);
+
+ Collection.Insert(
+ new Person
+ {
+ FirstName = "Joe",
+ LastName = "McJoe",
+ Age = 21,
+ PrimaryAddress = new Address { City = "Chicago", IsInternational = true, AddressType = AddressType.Private },
+ Addresses = new List
+ {
+ new Address { City = "Chicago", AddressType = AddressType.Private },
+ new Address { City = "London", AddressType = AddressType.Company }
+ },
+ EmployerIds = new[] {3}
+ },
+ true);
+ }
+
+ [Test]
+ public void Any()
+ {
+ var anyone = Collection.Linq().Any(x => x.Age <= 21);
+
+ Assert.IsTrue(anyone);
+ }
+
+ [Test]
+ public void Boolean()
+ {
+ var people = Enumerable.ToList(Collection.Linq().Where(x => x.PrimaryAddress.IsInternational));
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void Boolean_Inverse()
+ {
+ var people = Enumerable.ToList(Collection.Linq().Where(x => !x.PrimaryAddress.IsInternational));
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test]
+ public void Boolean_In_Conjunction()
+ {
+ var people = Enumerable.ToList(Collection.Linq().Where(x => x.PrimaryAddress.IsInternational && x.Age > 21));
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test]
+ public void Chained()
+ {
+ var people = Collection.Linq()
+ .Select(x => new { Name = x.FirstName + x.LastName, x.Age })
+ .Where(x => x.Age > 21)
+ .Select(x => x.Name).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void Complex_Addition()
+ {
+ var people = Collection.Linq().Where(x => x.Age + 23 < 50).ToList();
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test]
+ public void Complex_Disjunction()
+ {
+ var people = Collection.Linq().Where(x => x.Age == 21 || x.Age == 35).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void ConjuctionConstraint()
+ {
+ var people = Collection.Linq().Where(p => p.Age > 21 && p.Age < 42).ToList();
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test]
+ public void ConstraintsAgainstLocalReferenceMember()
+ {
+ var local = new { Test = new { Age = 21 } };
+ var people = Collection.Linq().Where(p => p.Age > local.Test.Age).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void ConstraintsAgainstLocalVariable()
+ {
+ var age = 21;
+ var people = Collection.Linq().Where(p => p.Age > age).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void Count()
+ {
+ var count = Collection.Linq().Count();
+
+ Assert.AreEqual(3, count);
+ }
+
+ [Test]
+ public void Count_with_predicate()
+ {
+ var count = Collection.Linq().Count(x => x.Age > 21);
+
+ Assert.AreEqual(2, count);
+ }
+
+ [Test]
+ public void Count_without_predicate()
+ {
+ var count = Collection.Linq().Where(x => x.Age > 21).Count();
+
+ Assert.AreEqual(2, count);
+ }
+
+ [Test]
+ public void DocumentQuery()
+ {
+ var people = (from p in DocumentCollection.Linq()
+ where p.Key("age") > 21
+ select (string)p["fn"]).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void Enum()
+ {
+ var people = Collection.Linq()
+ .Where(x => x.PrimaryAddress.AddressType == AddressType.Company)
+ .ToList();
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test]
+ public void First()
+ {
+ var person = Collection.Linq().OrderBy(x => x.Age).First();
+
+ Assert.AreEqual("Joe", person.FirstName);
+ }
+
+ [Test]
+ public void LocalEnumerable_Contains()
+ {
+ var names = new[] { "Joe", "Bob" };
+ var people = Collection.Linq().Where(x => names.Contains(x.FirstName)).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void LocalList_Contains()
+ {
+ var names = new List { "Joe", "Bob" };
+ var people = Collection.Linq().Where(x => names.Contains(x.FirstName)).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void NestedArray_Length()
+ {
+ var people = (from p in Collection.Linq()
+ where p.EmployerIds.Length == 1
+ select p).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test(Description = "This will fail < 1.4")]
+ public void NestedArray_indexer()
+ {
+ var people = Collection.Linq().Where(x => x.EmployerIds[0] == 1).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void NestedClassConstraint()
+ {
+ var people = Collection.Linq().Where(p => p.PrimaryAddress.City == "London").ToList();
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test]
+ public void NestedCollection_Count()
+ {
+ var people = (from p in Collection.Linq()
+ where p.Addresses.Count == 1
+ select p).ToList();
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test(Description = "This will fail < 1.4")]
+ public void NestedList_indexer()
+ {
+ var people = Collection.Linq().Where(x => x.Addresses[1].City == "Tokyo").ToList();
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test]
+ public void NestedQueryable_Any()
+ {
+ var people = Collection.Linq().Where(x => x.Addresses.Any(a => a.City == "London")).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void NestedQueryable_Contains()
+ {
+ var people = Collection.Linq().Where(x => x.EmployerIds.Contains(1)).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void Nested_Queryable_Count()
+ {
+ var people = Collection.Linq().Where(x => x.Addresses.Count() == 1).ToList();
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test(Description = "This will fail < 1.4")]
+ public void Nested_Queryable_ElementAt()
+ {
+ var people = Collection.Linq().Where(x => x.Addresses.ElementAt(1).City == "Tokyo").ToList();
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test]
+ public void NotNullCheck()
+ {
+ var people = Collection.Linq().Where(x => x.MidName != null).ToArray();
+
+ Assert.AreEqual(1, people.Length);
+ }
+
+ [Test]
+ public void NullCheck()
+ {
+ var people = Collection.Linq().Where(x => x.MidName == null).ToArray();
+
+ Assert.AreEqual(2, people.Length);
+ }
+
+ [Test]
+ public void NullCheckOnClassTypes()
+ {
+ var people = Collection.Linq().Where(x => x.LinkedId == null).ToArray();
+
+ Assert.AreEqual(3, people.Length);
+ }
+
+ [Test]
+ public void OrderBy()
+ {
+ var people = Collection.Linq().OrderBy(x => x.Age).ThenByDescending(x => x.LastName).ToList();
+
+ Assert.AreEqual("Joe", people[0].FirstName);
+ Assert.AreEqual("Jane", people[1].FirstName);
+ Assert.AreEqual("Bob", people[2].FirstName);
+ }
+
+ [Test]
+ public void Projection()
+ {
+ var people = (from p in Collection.Linq()
+ select new { Name = p.FirstName + p.LastName }).ToList();
+
+ Assert.AreEqual(3, people.Count);
+ }
+
+ [Test]
+ public void ProjectionWithLocalCreation_ChildobjectShouldNotBeNull()
+ {
+ var people = Collection.Linq()
+ .Select(p => new PersonWrapper(p, p.FirstName))
+ .FirstOrDefault();
+
+ Assert.IsNotNull(people);
+ Assert.IsNotNull(people.Name);
+ Assert.IsNotNull(people.Person);
+ Assert.IsNotNull(people.Person.PrimaryAddress);
+ }
+
+ [Test]
+ public void ProjectionWithConstraints()
+ {
+ var people = (from p in Collection.Linq()
+ where p.Age > 21 && p.Age < 42
+ select new { Name = p.FirstName + p.LastName }).ToList();
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test]
+ public void Regex_IsMatch()
+ {
+ var people = (from p in Collection.Linq()
+ where Regex.IsMatch(p.FirstName, "Joe")
+ select p).ToList();
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test]
+ public void Regex_IsMatch_CaseInsensitive()
+ {
+ var people = (from p in Collection.Linq()
+ where Regex.IsMatch(p.FirstName, "joe", RegexOptions.IgnoreCase)
+ select p).ToList();
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test]
+ public void Single()
+ {
+ var person = Collection.Linq().Where(x => x.Age == 21).Single();
+
+ Assert.AreEqual("Joe", person.FirstName);
+ }
+
+ [Test]
+ public void SingleEqualConstraint()
+ {
+ var people = Collection.Linq().Where(p => "Joe" == p.FirstName).ToList();
+
+ Assert.AreEqual(1, people.Count);
+ }
+
+ [Test]
+ public void SkipAndTake()
+ {
+ var people = Collection.Linq().OrderBy(x => x.Age).Skip(2).Take(1).ToList();
+
+ Assert.AreEqual("Bob", people[0].FirstName);
+ }
+
+ [Test]
+ public void String_Contains()
+ {
+ var people = (from p in Collection.Linq()
+ where p.FirstName.Contains("o")
+ select p).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void String_EndsWith()
+ {
+ var people = (from p in Collection.Linq()
+ where p.FirstName.EndsWith("e")
+ select p).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void String_StartsWith()
+ {
+ var people = (from p in Collection.Linq()
+ where p.FirstName.StartsWith("J")
+ select p).ToList();
+
+ Assert.AreEqual(2, people.Count);
+ }
+
+ [Test]
+ public void WithoutConstraints()
+ {
+ var people = Collection.Linq().ToList();
+
+ Assert.AreEqual(3, people.Count);
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/IntegrationTests/SecondServer/TestAuthentication.cs b/source/MongoDB.Tests/IntegrationTests/SecondServer/TestAuthentication.cs
new file mode 100644
index 00000000..3208cce4
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/SecondServer/TestAuthentication.cs
@@ -0,0 +1,132 @@
+using System;
+using System.Configuration;
+using MongoDB.Connections;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests.SecondServer
+{
+ ///
+ /// In case clean up fails open a Mongo shell and execute the following commands
+ /// * use admin
+ /// * db.auth("adminuser", "admin1234");
+ /// * db.system.users.find(); //should see adminuser
+ /// * db.system.users.remove({user:"adminuser"});
+ /// * db.system.users.find(); //should not see adminuser or any other.
+ /// * Tests should now run.
+ ///
+ [Ignore("Run manually since it needs a second server with --auth")]
+ [TestFixture]
+ public class TestAuthentication
+ {
+ private readonly string _connectionString;
+
+ public TestAuthentication()
+ {
+ _connectionString = ConfigurationManager.AppSettings["auth"];
+ }
+
+ const String TestDatabaseName = "testAuth";
+ const String TestUser = "testuser";
+ const String TestPass = "test1234";
+
+ const String AdminUser = "adminuser";
+ const String AdminPass = "admin1234";
+
+ [TestFixtureSetUp]
+ public void SetUp()
+ {
+ using(var mongo = new Mongo(_connectionString))
+ {
+ mongo.Connect();
+
+ var testDatabase = mongo[TestDatabaseName];
+ if(testDatabase.Metadata.FindUser(TestUser) == null)
+ testDatabase.Metadata.AddUser(TestUser, TestPass);
+
+ var adminDatabase = mongo["admin"];
+ if(adminDatabase.Metadata.FindUser(AdminUser) == null)
+ adminDatabase.Metadata.AddUser(AdminUser, AdminPass);
+ }
+ }
+
+ [Test]
+ public void TestLoginGoodPassword()
+ {
+ using(var mongo = ConnectAndAuthenticatedMongo(TestUser, TestPass))
+ TryInsertData(mongo);
+ }
+
+ [Test]
+ [ExpectedException(typeof(MongoException))]
+ public void TestLoginBadPassword()
+ {
+ using(var mongo = ConnectAndAuthenticatedMongo(TestUser, "badpassword"))
+ TryInsertData(mongo);
+ }
+
+ [Test]
+ public void TestAuthenticatedInsert(){
+ using(var mongo = ConnectAndAuthenticatedMongo(TestUser, TestPass))
+ TryInsertData(mongo);
+ }
+
+ [Test]
+ [ExpectedException(typeof(MongoOperationException))]
+ public void TestUnauthenticatedInsert(){
+ using(var mongo = new Mongo(_connectionString))
+ {
+ mongo.Connect();
+
+ TryInsertData(mongo);
+ }
+ }
+
+ [Test]
+ [ExpectedException(typeof(MongoException))]
+ public void TryUnautenticatedInsertWithoutSendingACommand()
+ {
+ using(var mongo = ConnectAndAuthenticatedMongo("noexisting", "noexisting"))
+ {
+ mongo.Connect();
+
+ var collection = mongo[TestDatabaseName]["testCollection"];
+ collection.Insert(new Document().Add("value", 84), false);
+ }
+ }
+
+ private Mongo ConnectAndAuthenticatedMongo(string username,string password)
+ {
+ var builder = new MongoConnectionStringBuilder(_connectionString)
+ {
+ Username = username,
+ Password = password
+ };
+ var mongo = new Mongo(builder.ToString());
+ mongo.Connect();
+ return mongo;
+ }
+
+ private static void TryInsertData(Mongo mongo)
+ {
+ var collection = mongo[TestDatabaseName]["testCollection"];
+ collection.Delete(new Document(),true);
+ collection.Insert(new Document().Add("value", 84),true);
+
+ var value = collection.FindOne(new Document().Add("value", 84));
+
+ Assert.AreEqual(84, value["value"]);
+ }
+
+ [TestFixtureTearDown]
+ public void TestTearDown(){
+ using(var mongo = ConnectAndAuthenticatedMongo(AdminUser, AdminPass))
+ {
+ mongo[TestDatabaseName].Metadata.RemoveUser(TestUser);
+ mongo["admin"].Metadata.RemoveUser(AdminUser);
+ }
+
+ // clean connections
+ ConnectionFactoryFactory.Shutdown();
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/IntegrationTests/SecondServer/TestPooledConnectionFactory.cs b/source/MongoDB.Tests/IntegrationTests/SecondServer/TestPooledConnectionFactory.cs
new file mode 100644
index 00000000..f0094473
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/SecondServer/TestPooledConnectionFactory.cs
@@ -0,0 +1,38 @@
+using MongoDB.Connections;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests.SecondServer
+{
+ [Ignore("Run manually since it needs a second server")]
+ [TestFixture]
+ public class TestPooledConnectionFactory
+ {
+ [TestFixtureSetUp]
+ public void SetUp()
+ {
+ ConnectionFactoryFactory.Shutdown();
+ }
+
+ [Test]
+ public void TestServerCirculationWorks()
+ {
+ var builder = new MongoConnectionStringBuilder();
+ builder.AddServer("localhost", 27017);
+ builder.AddServer("localhost", 27018);
+ using(var pool = new PooledConnectionFactory(builder.ToString()))
+ {
+ var connection1 = pool.Open();
+ var connection2 = pool.Open();
+ var connection3 = pool.Open();
+ var connection4 = pool.Open();
+ var connection5 = pool.Open();
+ Assert.AreEqual(27017, connection1.EndPoint.Port);
+ Assert.AreEqual(27018, connection2.EndPoint.Port);
+ Assert.AreEqual(27017, connection3.EndPoint.Port);
+ Assert.AreEqual(27018, connection4.EndPoint.Port);
+ Assert.AreEqual(27017, connection5.EndPoint.Port);
+ }
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/IntegrationTests/TestCollection.cs b/source/MongoDB.Tests/IntegrationTests/TestCollection.cs
new file mode 100644
index 00000000..3aa6da98
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/TestCollection.cs
@@ -0,0 +1,555 @@
+using System;
+using System.Linq;
+using MongoDB.Util;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests
+{
+ [TestFixture]
+ public class TestCollection : MongoTestBase
+ {
+ const string POUND = "\u00a3";
+
+ public override string TestCollections
+ {
+ get { return "inserts,updates,counts,counts_spec,finds,charreads,saves,find_and_modify"; }
+ }
+
+ public override void OnInit()
+ {
+ var finds = DB["finds"];
+ for(var j = 1; j < 100; j++)
+ finds.Insert(new Document {{"x", 4}, {"h", "hi"}, {"j", j}});
+ for(var j = 100; j < 105; j++)
+ finds.Insert(new Document {{"x", 4}, {"n", 1}, {"j", j}});
+ var charreads = DB["charreads"];
+ charreads.Insert(new Document {{"test", "1234" + POUND + "56"}});
+ }
+
+ private static int CountDocs(ICursor cur)
+ {
+ return cur.Documents.Count();
+ }
+
+ [Test]
+ public void TestArrayInsert()
+ {
+ var inserts = DB["inserts"];
+ var indoc1 = new Document();
+ indoc1["song"] = "The Axe";
+ indoc1["artist"] = "Tinsley Ellis";
+ indoc1["year"] = 2006;
+
+ var indoc2 = new Document();
+ indoc2["song"] = "The Axe2";
+ indoc2["artist"] = "Tinsley Ellis2";
+ indoc2["year"] = 2008;
+
+ inserts.Insert(new[] {indoc1, indoc2});
+
+ var result = inserts.FindOne(new Document().Add("song", "The Axe"));
+ Assert.IsNotNull(result);
+ Assert.AreEqual(2006, result["year"]);
+
+ result = inserts.FindOne(new Document().Add("song", "The Axe2"));
+ Assert.IsNotNull(result);
+ Assert.AreEqual(2008, result["year"]);
+ }
+
+ [Test]
+ public void TestCount()
+ {
+ var counts = DB["counts"];
+ var top = 100;
+ for(var i = 0; i < top; i++)
+ counts.Insert(new Document().Add("Last", "Cordr").Add("First", "Sam").Add("cnt", i));
+ var cnt = counts.Count();
+ Assert.AreEqual(top, cnt, "Count not the same as number of inserted records");
+ }
+
+ [Test]
+ public void TestCountInvalidCollection()
+ {
+ var counts = DB["counts_wtf"];
+ Assert.AreEqual(0, counts.Count());
+ }
+
+ [Test]
+ public void TestCountWithSpec()
+ {
+ var counts = DB["counts_spec"];
+ counts.Insert(new Document().Add("Last", "Cordr").Add("First", "Sam").Add("cnt", 1));
+ counts.Insert(new Document().Add("Last", "Cordr").Add("First", "Sam").Add("cnt", 2));
+ counts.Insert(new Document().Add("Last", "Corder").Add("First", "Sam").Add("cnt", 3));
+
+ Assert.AreEqual(2, counts.Count(new Document().Add("Last", "Cordr")));
+ Assert.AreEqual(1, counts.Count(new Document().Add("Last", "Corder")));
+ Assert.AreEqual(0, counts.Count(new Document().Add("Last", "Brown")));
+ }
+
+ [Test]
+ public void TestDelete()
+ {
+ var deletes = DB["deletes"];
+ var doc = new Document();
+ doc["y"] = 1;
+ doc["x"] = 2;
+ deletes.Insert(doc);
+
+ var selector = new Document().Add("x", 2);
+
+ var result = deletes.FindOne(selector);
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result["y"]);
+
+ deletes.Delete(selector);
+ result = deletes.FindOne(selector);
+ Assert.IsNull(result, "Shouldn't have been able to find a document that was deleted");
+ }
+
+ [Test]
+ public void TestFindAttributeLimit()
+ {
+ var query = new Document();
+ query["j"] = 10;
+ var fields = new Document();
+ fields["x"] = 1;
+
+ var c = DB["finds"].Find(query, -1, 0, fields);
+ foreach(var result in c.Documents)
+ {
+ Assert.IsNotNull(result);
+ Assert.AreEqual(4, result["x"]);
+ Assert.IsNull(result["j"]);
+ }
+ }
+
+ [Test]
+ public void TestFindGTRange()
+ {
+ var query = new Document();
+ query["j"] = new Document().Add("$gt", 20);
+
+ var c = DB["finds"].Find(query);
+ foreach(var result in c.Documents)
+ {
+ Assert.IsNotNull(result);
+ var j = result["j"];
+ Assert.IsTrue(Convert.ToDouble(j) > 20);
+ }
+ }
+
+ [Test]
+ public void TestFindNulls()
+ {
+ var query = new Document().Add("n", null);
+ var numnulls = DB["finds"].Count(query);
+ Assert.AreEqual(99, numnulls);
+ }
+
+ [Test]
+ public void TestFindOne()
+ {
+ var query = new Document();
+ query["j"] = 10;
+ var result = DB["finds"].FindOne(query);
+ Assert.IsNotNull(result);
+ Assert.AreEqual(4, result["x"]);
+ Assert.AreEqual(10, result["j"]);
+ }
+
+ [Test]
+ public void TestFindOneNotThere()
+ {
+ var query = new Document();
+ query["not_there"] = 10;
+ var result = DB["finds"].FindOne(query);
+ Assert.IsNull(result);
+ }
+
+ [Test]
+ public void TestFindOneObjectContainingUKPound()
+ {
+ var query = new Document();
+ var result = DB["charreads"].FindOne(query);
+ Assert.IsNotNull(result);
+ Assert.IsTrue(result.ContainsKey("test"));
+ Assert.AreEqual("1234£56", result["test"]);
+ }
+
+ [Test]
+ public void TestFindWhereEquivalency()
+ {
+ var col = DB["finds"];
+ var lt = new Document().Add("j", new Document().Add("$lt", 5));
+ var where = "this.j < 5";
+ var explicitWhere = new Document().Add("$where", new Code(where));
+ var func = new CodeWScope("function() { return this.j < 5; }", new Document());
+ var funcDoc = new Document().Add("$where", func);
+
+ Assert.AreEqual(4, CountDocs(col.Find(lt)), "Basic find didn't return 4 docs");
+ Assert.AreEqual(4, CountDocs(col.Find(where)), "String where didn't return 4 docs");
+ Assert.AreEqual(4, CountDocs(col.Find(explicitWhere)), "Explicit where didn't return 4 docs");
+ Assert.AreEqual(4, CountDocs(col.Find(funcDoc)), "Function where didn't return 4 docs");
+ }
+
+ [Test]
+ public void TestFindAndModifyReturnsOldDocument() {
+ IMongoCollection collection = DB["find_and_modify"];
+ Document person = new Document().Append("First", "Sally").Append("Last", "Simmons");
+ collection.Insert(person);
+
+ Document spec = new Document().Append("_id", person["_id"]);
+ Document loaded = collection.FindAndModify(new Document().Append("First", "Jane"), spec);
+
+ Assert.AreEqual("Sally", loaded["First"]);
+ }
+
+ [Test]
+ public void TestFindAndModifyReturnsNewDocument() {
+ IMongoCollection collection = DB["find_and_modify"];
+ Document person = new Document().Append("First", "Susie").Append("Last", "O'Hara");
+ collection.Insert(person);
+
+ Document spec = new Document().Append("_id", person["_id"]);
+ Document loaded = collection.FindAndModify(new Document().Append("First", "Darlene"), spec, true);
+
+ Assert.AreEqual("Darlene", loaded["First"]);
+ }
+
+ [Test]
+ public void TestFindAndModifySortsResults() {
+ IMongoCollection collection = DB["find_and_modify"];
+ Document doc1 = new Document().Append("handled", false).Append("priority", 1).Append("value", "Test 1");
+ Document doc2 = new Document().Append("handled", false).Append("priority", 2).Append("value", "Test 2");
+ collection.Insert(doc1);
+ collection.Insert(doc2);
+
+ Document update = new Document().Append("handled", true);
+ Document spec = new Document().Append("handled", false);
+ Document sort = new Document().Append("priority", -1);
+ Document loaded = collection.FindAndModify(update, spec, sort, true);
+
+ Assert.AreEqual(true, loaded["handled"]);
+ Assert.AreEqual(doc2["priority"], loaded["priority"]);
+ Assert.AreEqual(doc2["value"], loaded["value"]);
+ }
+
+ [Test]
+ public void TestFindAndModifyReturnNullForNoRecordFound() {
+ IMongoCollection collection = DB["find_and_modify"];
+ Document spec = new Document().Append("FirstName", "Noone");
+ Document loaded = collection.FindAndModify(new Document().Append("First", "Darlene"), spec, true);
+
+ Assert.IsNull(loaded, "Should return null for no document found");
+ }
+
+ [Test]
+ public void TestInsertBulkLargerThan4MBOfDocuments()
+ {
+ var b = new Binary(new byte[1024*1024*2]);
+ var inserts = DB["inserts"];
+ try
+ {
+ var docs = new Document[10];
+ //6MB+ of documents
+ for(var x = 0; x < docs.Length; x++)
+ docs[x] = new Document {{"name", "bulk"}, {"b", b}, {"x", x}};
+ inserts.Insert(docs, true);
+ var count = inserts.Count(new Document {{"name", "bulk"}});
+ Assert.AreEqual(docs.Length, count, "Wrong number of documents inserted");
+ }
+ catch(MongoException)
+ {
+ Assert.Fail("MongoException should not have been thrown.");
+ }
+ }
+
+ [Test]
+ public void TestInsertLargerThan4MBDocument()
+ {
+ var b = new Binary(new byte[1024*1024]);
+ var big = new Document {{"name", "Big Document"}, {"b1", b}, {"b2", b}, {"b3", b}, {"b4", b}};
+ var inserts = DB["inserts"];
+ var thrown = false;
+ try
+ {
+ inserts.Insert(big);
+ }
+ catch(MongoException)
+ {
+ thrown = true;
+ }
+ catch(Exception e)
+ {
+ Assert.Fail("Wrong Exception thrown " + e.GetType().Name);
+ }
+ Assert.IsTrue(thrown, "Shouldn't be able to insert large document");
+ }
+
+ [Test]
+ public void TestInsertOfArray()
+ {
+ var ogen = new OidGenerator();
+ var inserts = DB["inserts"];
+ var album = new Document();
+ album["_id"] = ogen.Generate();
+ album["artist"] = "Popa Chubby";
+ album["title"] = "Deliveries After Dark";
+ album["songs"] = new[]
+ {
+ new Document().Add("title", "Let The Music Set You Free").Add("length", "5:15").Add("_id", ogen.Generate()),
+ new Document().Add("title", "Sally Likes to Run").Add("length", "4:06").Add("_id", ogen.Generate()),
+ new Document().Add("title", "Deliveries After Dark").Add("length", "4:17").Add("_id", ogen.Generate()),
+ new Document().Add("title", "Theme From The Godfather").Add("length", "3:06").Add("_id", ogen.Generate()),
+ new Document().Add("title", "Grown Man Crying Blues").Add("length", "8:09").Add("_id", ogen.Generate()),
+ };
+ inserts.Insert(album);
+
+ var result = inserts.FindOne(new Document().Add("songs.title", "Deliveries After Dark"));
+ Assert.IsNotNull(result);
+
+ Assert.AreEqual(album.ToString(), result.ToString());
+ }
+
+ [Test]
+ public void TestManualWhere()
+ {
+ var query = new Document().Add("$where", new Code("this.j % 2 == 0"));
+ var c = DB["finds"].Find(query);
+ foreach(var result in c.Documents)
+ {
+ Assert.IsNotNull(result);
+ var j = result["j"];
+ Assert.IsTrue(Convert.ToInt32(j)%2 == 0);
+ }
+ }
+
+ [Test]
+ public void TestPoundSymbolInsert()
+ {
+ var inserts = DB["inserts"];
+ var indoc = new Document().Add("x", "1234" + POUND + "56").Add("y", 1);
+ inserts.Insert(indoc);
+
+ var result = inserts.FindOne(new Document().Add("x", "1234" + POUND + "56"));
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result["y"]);
+ }
+
+ [Test]
+ public void TestReallySimpleInsert()
+ {
+ var inserts = DB["inserts"];
+ var indoc = new Document();
+ indoc["y"] = 1;
+ indoc["x"] = 2;
+ inserts.Insert(indoc);
+
+ var result = inserts.FindOne(new Document().Add("x", 2));
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result["y"]);
+ }
+
+ [Test]
+ public void TestSave()
+ {
+ var saves = DB["saves"];
+ var count = 100;
+ for(var i = 0; i < count; i++)
+ saves.Save(new Document {{"x", i}, {"desc", "This document is number: " + i}, {"y", 1}});
+ Assert.AreEqual(count, saves.Count(new Document {{"y", 1}}));
+
+ using(var cur = saves.FindAll())
+ {
+ foreach(var d in cur.Documents)
+ {
+ d["y"] = Convert.ToInt32(d["y"]) + 1;
+ saves.Save(d);
+ }
+ }
+ Assert.AreEqual(count, saves.Count(new Document {{"y", 2}}));
+ }
+
+ [Test]
+ public void TestSaveInsertDocumentIfExists()
+ {
+ var saves = DB["updates"];
+ saves.Delete(new Document());
+
+ var document1 = new Document("name", "Alien1");
+ saves.Insert(document1);
+ var document2 = new Document("name", "Alien2");
+ saves.Insert(document2);
+
+ document1["name"] = "Sam";
+ saves.Save(document1);
+ document2["name"] = "Steve";
+ saves.Save(document2);
+
+ var array = saves.FindAll().Documents.ToArray();
+ Assert.AreEqual(2, array.Length);
+ Assert.AreEqual("Sam", array[0]["name"]);
+ Assert.AreEqual("Steve", array[1]["name"]);
+ }
+
+ [Test]
+ public void TestSaveInsertDocumentIfNotExists()
+ {
+ var saves = DB["updates"];
+ saves.Delete(new Document());
+
+ saves.Save(new Document("name", "Sam"));
+ saves.Save(new Document("name", "Steve"));
+
+ var array = saves.FindAll().Documents.ToArray();
+ Assert.AreEqual(2, array.Length);
+ Assert.AreEqual("Sam", array[0]["name"]);
+ Assert.AreEqual("Steve", array[1]["name"]);
+ }
+
+ [Test]
+ public void TestSimpleInsert()
+ {
+ var inserts = DB["inserts"];
+ var indoc = new Document();
+ indoc["song"] = "Palmdale";
+ indoc["artist"] = "Afroman";
+ indoc["year"] = 1999;
+
+ inserts.Insert(indoc);
+
+ var result = inserts.FindOne(new Document().Add("song", "Palmdale"));
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1999, result["year"]);
+ }
+
+ [Test]
+ public void TestUpdateMany()
+ {
+ var updates = DB["updates"];
+
+ updates.Insert(new Document().Add("Last", "Cordr").Add("First", "Sam"));
+ updates.Insert(new Document().Add("Last", "Cordr").Add("First", "Sam2"));
+ updates.Insert(new Document().Add("Last", "Cordr").Add("First", "Sam3"));
+
+ var selector = new Document().Add("Last", "Cordr");
+ var results = updates.Find(selector);
+ var found = false;
+ foreach(var doc in results.Documents)
+ {
+ Assert.AreEqual("Cordr", doc["Last"]);
+ found = true;
+ }
+ Assert.IsTrue(found, "Should have found docs inserted for TestUpdateMany");
+ Assert.AreEqual(3, updates.Count(selector), "Didn't find all Documents inserted for TestUpdateMany with Selector");
+
+ //Document updateData = new Document().Append("$set", new Document().Append("Last", "Corder2"));
+ var updateData = new Document().Add("Last", "Corder2");
+ updates.UpdateAll(updateData, selector);
+
+ selector["Last"] = "Corder2";
+ Assert.AreEqual(3, updates.Count(selector), "Not all Cordr documents were updated");
+
+ results = updates.Find(selector);
+ found = false;
+ foreach(var doc in results.Documents)
+ {
+ Assert.AreEqual("Corder2", doc["Last"]);
+ Assert.IsNotNull(doc["First"], "First name should not disappear");
+ found = true;
+ }
+ Assert.IsTrue(found, "Should have found docs updated for TestMany");
+ }
+
+ [Test]
+ public void TestUpdatePartial()
+ {
+ var updates = DB["updates"];
+ var coolness = 5;
+ var einstein = new Document {{"Last", "Einstien"}, {"First", "Albert"}, {"Coolness", coolness++}};
+ updates.Insert(einstein);
+ var selector = new Document {{"_id", einstein["_id"]}};
+
+ updates.Update(new Document {{"$inc", new Document {{"Coolness", 1}}}}, selector);
+ Assert.AreEqual(coolness++, Convert.ToInt32(updates.FindOne(selector)["Coolness"]), "Coolness field not incremented", true);
+
+ updates.Update(new Document
+ {
+ {"$set", new Document {{"Last", "Einstein"}}},
+ {"$inc", new Document {{"Coolness", 1}}}
+ },
+ selector,
+ true);
+ Assert.AreEqual(coolness++, Convert.ToInt32(updates.FindOne(selector)["Coolness"]), "Coolness field not incremented");
+ }
+
+ [Test]
+ public void TestUpdateUpsertExisting()
+ {
+ var updates = DB["updates"];
+ var doc = new Document();
+ doc["First"] = "Mtt";
+ doc["Last"] = "Brewer";
+
+ updates.Insert(doc);
+
+ var selector = new Document().Add("Last", "Brewer");
+ doc = updates.FindOne(selector);
+ Assert.IsNotNull(doc);
+ Assert.AreEqual("Mtt", doc["First"]);
+ Assert.IsNotNull(doc["_id"]);
+
+ doc["First"] = "Matt";
+ updates.Update(doc);
+
+ var result = updates.FindOne(selector);
+ Assert.IsNotNull(result);
+ Assert.AreEqual("Matt", result["First"]);
+ }
+
+ [Test]
+ public void TestUpdateUpsertNotExisting()
+ {
+ var updates = DB["updates"];
+ var doc = new Document();
+ doc["First"] = "Sam";
+ doc["Last"] = "CorderNE";
+
+ updates.Update(doc);
+ var selector = new Document().Add("Last", "CorderNE");
+ var result = updates.FindOne(selector);
+ Assert.IsNotNull(result);
+ Assert.AreEqual("Sam", result["First"]);
+ }
+
+ [Test]
+ public void TestWhere()
+ {
+ var c = DB["finds"].Find("this.j % 2 == 0");
+ foreach(var result in c.Documents)
+ {
+ Assert.IsNotNull(result);
+ var j = result["j"];
+ Assert.IsTrue(Convert.ToInt32(j)%2 == 0);
+ }
+ }
+
+ [Test]
+ public void TestHandlingRetrievalOfUnderscoredFieldsAfterFindAndModify()
+ {
+ var updates = DB["updates"];
+ var id = Guid.NewGuid();
+ var doc = new Document()
+ .Add("_id", id)
+ .Add("FirstName", "David")
+ .Add("LastName", "Beckham")
+ .Add("Embedded", new Document().Add("Types", 1));
+ updates.Insert(doc);
+ var find = new Document().Add("_id", id);
+ var modify = new Document().Add("LastName", "Copperfield");
+ var returned = updates.FindAndModify(modify, find, true);
+ Assert.IsInstanceOfType(typeof(Document), returned["Embedded"]);
+ }
+ }
+}
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/TestCollectionMetaData.cs b/source/MongoDB.Tests/IntegrationTests/TestCollectionMetaData.cs
similarity index 77%
rename from MongoDB.Net-Tests/TestCollectionMetaData.cs
rename to source/MongoDB.Tests/IntegrationTests/TestCollectionMetaData.cs
index 1e442e39..1f59e6a9 100644
--- a/MongoDB.Net-Tests/TestCollectionMetaData.cs
+++ b/source/MongoDB.Tests/IntegrationTests/TestCollectionMetaData.cs
@@ -1,105 +1,100 @@
-using System;
-using System.Collections.Generic;
-
-using NUnit.Framework;
-using MongoDB.Driver.Bson;
-
-namespace MongoDB.Driver
-{
- [TestFixture]
- public class TestCollectionMetaData : MongoTestBase
- {
- Database adminDb;
-
- String adminuser = "adminuser";
- String adminpass = "admin1234";
-
- public override string TestCollections {
- get {
- return "indextests,rename,renamed";
- }
- }
-
- public override void OnInit (){
- IMongoCollection its = DB["indextests"];
- its.Insert(createDoc("S","A","Anderson","OH"));
- its.Insert(createDoc("T","B","Delhi","OH"));
- its.Insert(createDoc("F","B","Cincinnati","OH"));
- its.Insert(createDoc("U","D","Newtown","OH"));
- its.Insert(createDoc("J","E","Newport","KY"));
-
- adminDb = DB.GetSisterDatabase("admin");
- //adminDb.MetaData.AddUser(adminuser, adminpass);
- }
-
- public override void OnDispose (){
- //adminDb.MetaData.RemoveUser(adminuser);
+using System;
+using System.Collections.Generic;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests
+{
+ [TestFixture]
+ public class TestCollectionMetaData : MongoTestBase
+ {
+ MongoDatabase adminDb;
+
+ public override string TestCollections {
+ get {
+ return "indextests,rename,renamed";
+ }
}
-
- [Test]
- public void TestGetOptions(){
- CollectionMetaData cmd = DB["reads"].MetaData;
- Document options = cmd.Options;
- Assert.IsNotNull(options);
- }
-
- [Test]
- public void TestGetIndexes(){
- CollectionMetaData cmd = DB["indextests"].MetaData;
- Dictionary indexes = cmd.Indexes;
-
- Assert.IsNotNull(indexes);
- Assert.IsTrue(indexes.Count > 0, "Should have been at least one index found.");
- foreach(string key in indexes.Keys){
- System.Console.WriteLine(String.Format("Key: {0} Value: {1}", key, indexes[key]));
- }
- }
-
- [Test]
- public void TestCreateIndex(){
- CollectionMetaData cmd = DB["indextests"].MetaData;
- cmd.CreateIndex("lastnames", new Document().Append("lname", IndexOrder.Ascending), false);
- Dictionary indexes = cmd.Indexes;
- Assert.IsNotNull(indexes["lastnames"]);
- }
-
- [Test]
- public void TestCreateIndexNoNames(){
- CollectionMetaData cmd = DB["indextests"].MetaData;
- cmd.CreateIndex(new Document().Append("lname", IndexOrder.Ascending).Append("fname",IndexOrder.Ascending), true);
- Dictionary indexes = cmd.Indexes;
- Assert.IsNotNull(indexes["_lname_fname_unique_"]);
- }
-
- [Test]
- public void TestDropIndex(){
- CollectionMetaData cmd = DB["indextests"].MetaData;
- cmd.CreateIndex("firstnames", new Document().Append("fname", IndexOrder.Ascending), false);
- Dictionary indexes = cmd.Indexes;
- Assert.IsNotNull(indexes["firstnames"]);
- cmd.DropIndex("firstnames");
- Assert.IsFalse(cmd.Indexes.ContainsKey("firstnames"));
- }
-
- [Test]
+
+ public override void OnInit (){
+ IMongoCollection its = DB["indextests"];
+ its.Insert(createDoc("S","A","Anderson","OH"));
+ its.Insert(createDoc("T","B","Delhi","OH"));
+ its.Insert(createDoc("F","B","Cincinnati","OH"));
+ its.Insert(createDoc("U","D","Newtown","OH"));
+ its.Insert(createDoc("J","E","Newport","KY"));
+
+ adminDb = DB.GetSisterDatabase("admin");
+ //adminDb.MetaData.AddUser(adminuser, adminpass);
+ }
+
+ public override void OnDispose (){
+ //adminDb.MetaData.RemoveUser(adminuser);
+ }
+
+ [Test]
+ public void TestGetOptions(){
+ CollectionMetadata cmd = DB["reads"].Metadata;
+ Document options = cmd.Options;
+ Assert.IsNotNull(options);
+ }
+
+ [Test]
+ public void TestGetIndexes(){
+ CollectionMetadata cmd = DB["indextests"].Metadata;
+ Dictionary indexes = cmd.Indexes;
+
+ Assert.IsNotNull(indexes);
+ Assert.IsTrue(indexes.Count > 0, "Should have been at least one index found.");
+ foreach(string key in indexes.Keys){
+ System.Console.WriteLine(String.Format("Key: {0} Value: {1}", key, indexes[key]));
+ }
+ }
+
+ [Test]
+ public void TestCreateIndex(){
+ CollectionMetadata cmd = DB["indextests"].Metadata;
+ cmd.CreateIndex("lastnames", new Document().Add("lname", IndexOrder.Ascending), false);
+ Dictionary indexes = cmd.Indexes;
+ Assert.IsNotNull(indexes["lastnames"]);
+ }
+
+ [Test]
+ public void TestCreateIndexNoNames(){
+ CollectionMetadata cmd = DB["indextests"].Metadata;
+ cmd.CreateIndex(new Document().Add("lname", IndexOrder.Ascending).Add("fname", IndexOrder.Ascending), true);
+ Dictionary indexes = cmd.Indexes;
+ Assert.IsNotNull(indexes["_lname_fname_unique_"]);
+ }
+
+ [Test]
+ public void TestDropIndex(){
+ CollectionMetadata cmd = DB["indextests"].Metadata;
+ cmd.CreateIndex("firstnames", new Document().Add("fname", IndexOrder.Ascending), false);
+ Dictionary indexes = cmd.Indexes;
+ Assert.IsNotNull(indexes["firstnames"]);
+ cmd.DropIndex("firstnames");
+ Assert.IsFalse(cmd.Indexes.ContainsKey("firstnames"));
+ }
+
+ [Test]
public void TestRename(){
- DB["rename"].Insert(new Document(){{"test", "rename"}});
+ DB["rename"].Insert(new Document(){{"test", "rename"}});
Assert.AreEqual(1, DB["rename"].Count());
- CollectionMetaData cmd = DB["rename"].MetaData;
- cmd.Rename("renamed");
- Assert.IsFalse(DB.GetCollectionNames().Contains(DB.Name + ".rename"), "Shouldn't have found collection");
- Assert.IsTrue(DB.GetCollectionNames().Contains(DB.Name + ".renamed"),"Should have found collection");
+ CollectionMetadata cmd = DB["rename"].Metadata;
+ cmd.Rename("renamed");
+ Assert.IsFalse(DB.GetCollectionNames().Contains(DB.Name + ".rename"), "Shouldn't have found collection");
+ Assert.IsTrue(DB.GetCollectionNames().Contains(DB.Name + ".renamed"),"Should have found collection");
Assert.AreEqual(1, DB["renamed"].Count());
- }
-
- protected Document createDoc(string fname, string lname, string city, string state){
- Document doc = new Document();
- doc["fname"] = fname;
- doc["lname"] = lname;
- doc["city"] = city;
- doc["state"] = state;
- return doc;
- }
-
- }
-}
+ }
+
+ protected Document createDoc(string fname, string lname, string city, string state){
+ Document doc = new Document();
+ doc["fname"] = fname;
+ doc["lname"] = lname;
+ doc["city"] = city;
+ doc["state"] = state;
+ return doc;
+ }
+
+ }
+}
diff --git a/MongoDB.Net-Tests/TestCollectionSafeMode.cs b/source/MongoDB.Tests/IntegrationTests/TestCollectionSafeMode.cs
similarity index 93%
rename from MongoDB.Net-Tests/TestCollectionSafeMode.cs
rename to source/MongoDB.Tests/IntegrationTests/TestCollectionSafeMode.cs
index b0da9044..de19bf33 100644
--- a/MongoDB.Net-Tests/TestCollectionSafeMode.cs
+++ b/source/MongoDB.Tests/IntegrationTests/TestCollectionSafeMode.cs
@@ -1,9 +1,7 @@
-using System;
-
-using NUnit.Framework;
-
-
-namespace MongoDB.Driver
+using System;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests
{
[TestFixture]
public class TestCollectionSafeMode : MongoTestBase
@@ -13,11 +11,9 @@ public override string TestCollections {
return "safeinsert, safeupdate, safedelete, safemupdate";
}
}
-
-
[Test]
- public void TestBadInsert(){
+ public void TestBadInsert(){
IMongoCollection col = InitCollection("safeinsert");
bool thrown = false;
try{
@@ -31,7 +27,7 @@ public void TestBadInsert(){
}
[Test]
- public void TestBadUpdate(){
+ public void TestBadUpdate(){
IMongoCollection col = InitCollection("safeupdate");
bool thrown = false;
try{
@@ -48,7 +44,7 @@ public void TestBadUpdate(){
}
[Test]
- public void TestMultiUpdate(){
+ public void TestMultiUpdate(){
IMongoCollection col = InitCollection("safemupdate");
Document newy = new Document(){{"y", 2}};
col.UpdateAll(newy, new Document(){{"y",1}},true);
@@ -66,11 +62,12 @@ public void TestMultiUpdate(){
Assert.Fail(String.Format("Wrong exception thrown: {0}", e.GetType().Name));
}
Assert.IsTrue(thrown, "Exception not thrown.");
- }
-
- protected IMongoCollection InitCollection(string name){
+ }
+
+ protected IMongoCollection InitCollection(string name)
+ {
IMongoCollection col = DB[name];
- col.MetaData.CreateIndex(new Document{{"x", IndexOrder.Ascending}}, true);
+ col.Metadata.CreateIndex(new Document{{"x", IndexOrder.Ascending}}, true);
for(int x = 0; x < 5; x++){
col.Insert(new Document{{"x", x}, {"y", 1}});
}
diff --git a/source/MongoDB.Tests/IntegrationTests/TestCollection_1.cs b/source/MongoDB.Tests/IntegrationTests/TestCollection_1.cs
new file mode 100644
index 00000000..3df6b1d3
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/TestCollection_1.cs
@@ -0,0 +1,412 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using MongoDB.Attributes;
+using MongoDB.Util;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests
+{
+ [TestFixture]
+ public class TestCollection_1 : MongoTestBase
+ {
+ private const string POUND = "\u00a3";
+
+ private class CountsEntity
+ {
+ public Oid Id { get; set; }
+
+ public string Last { get; set; }
+
+ public string First { get; set; }
+
+ [MongoAlias("cnt")]
+ public int Coolness { get; set; }
+ }
+
+ private class FindsEntity
+ {
+ public int x { get; set; }
+
+ [MongoAlias("h")]
+ public string Text { get; set; }
+
+ [MongoAlias("j")]
+ public int Index { get; set; }
+
+ public int n { get; set; }
+ }
+
+ private class CharReadsEntity
+ {
+ public string test { get; set; }
+ }
+
+ private class InsertsEntity
+ {
+ [MongoAlias("song")]
+ public string Song { get; set; }
+
+ [MongoAlias("artist")]
+ public string Artist { get; set; }
+
+ [MongoAlias("year")]
+ public int Year { get; set; }
+ }
+
+ private class Album
+ {
+ [MongoAlias("artist")]
+ public string Artist { get; set; }
+
+ [MongoAlias("title")]
+ public string Title { get; set; }
+
+ [MongoAlias("songs")]
+ public List Songs { get; set; }
+ }
+
+ private class Song
+ {
+ [MongoAlias("title")]
+ public string Title { get; set; }
+
+ [MongoAlias("length")]
+ public string Length { get; set; }
+ }
+
+ private class AlbumCase
+ {
+ public AlbumCase(){
+ Album = new Album();
+ }
+
+ public Album Album { get; set; }
+ }
+
+ private class DeletesEntity
+ {
+ public int x { get; set; }
+ public int y { get; set; }
+ }
+
+ public override string TestCollections{
+ get { return "inserts,updates,counts,counts_spec,finds,charreads,saves"; }
+ }
+
+ public override void OnInit(){
+ var finds = DB["finds"];
+ for(var j = 1; j < 100; j++)
+ finds.Insert(new Document {{"x", 4}, {"h", "hi"}, {"j", j}});
+ for(var j = 100; j < 105; j++)
+ finds.Insert(new Document {{"x", 4}, {"n", 1}, {"j", j}});
+ var charreads = DB["charreads"];
+ charreads.Insert(new Document {{"test", "1234" + POUND + "56"}});
+ }
+
+ [Test]
+ public void TestArrayInsert(){
+ var inserts = DB.GetCollection("inserts");
+ var indoc1 = new {Song = "The Axe", Artist = "Tinsley Ellis", Year = 2006};
+ var indoc2 = new {Song = "The Axe2", Artist = "Tinsley Ellis2", Year = 2008};
+
+ inserts.Insert(new[] {indoc1, indoc2});
+
+ var result = inserts.FindOne(new Document().Add("Song", "The Axe"));
+ Assert.IsNotNull(result);
+ Assert.AreEqual(2006, result.Year);
+
+ result = inserts.FindOne(new Document().Add("Song", "The Axe2"));
+ Assert.IsNotNull(result);
+ Assert.AreEqual(2008, result.Year);
+ }
+
+ [Test]
+ public void TestCanInsertNullPropertys(){
+ var inserts = DB.GetCollection("inserts");
+
+ inserts.Insert(new CharReadsEntity());
+ }
+
+ [Test]
+ public void TestCount(){
+ var counts = DB.GetCollection("counts");
+ var top = 100;
+ for(var i = 0; i < top; i++)
+ counts.Insert(new CountsEntity {Last = "Cordr", First = "Sam", Coolness = i});
+ var cnt = counts.Count();
+ Assert.AreEqual(top, cnt, "Count not the same as number of inserted records");
+ }
+
+ [Test]
+ public void TestCountInvalidCollection(){
+ var counts = DB.GetCollection("counts_wtf");
+ Assert.AreEqual(0, counts.Count());
+ }
+
+ [Test]
+ public void TestCountWithSpec(){
+ var counts = DB.GetCollection("counts_spec");
+ counts.Insert(new CountsEntity {Last = "Cordr", First = "Sam", Coolness = 1});
+ counts.Insert(new CountsEntity {Last = "Cordr", First = "Sam", Coolness = 2});
+ counts.Insert(new CountsEntity {Last = "Corder", First = "Sam", Coolness = 3});
+
+ Assert.AreEqual(2, counts.Count(new {Last = "Cordr"}));
+ Assert.AreEqual(1, counts.Count(new {Last = "Corder"}));
+ Assert.AreEqual(0, counts.Count(new {Last = "Brown"}));
+ }
+
+ [Test]
+ public void TestDelete(){
+ var deletes = DB.GetCollection("deletes");
+ deletes.Insert(new {x = 2, y = 1});
+
+ var selector = new {x = 2};
+
+ var result = deletes.FindOne(selector);
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.y);
+
+ deletes.Delete(selector);
+ result = deletes.FindOne(selector);
+ Assert.IsNull(result, "Shouldn't have been able to find a document that was deleted");
+ }
+
+ [Test]
+ public void TestFindAttributeLimit(){
+ var query = new {Index = 10};
+ var fields = new {x = 1};
+ var c = DB.GetCollection("finds").Find(query, -1, 0, fields);
+ foreach(var result in c.Documents)
+ {
+ Assert.IsNotNull(result);
+ Assert.AreEqual(4, result.x);
+ Assert.AreEqual(0, result.Index);
+ }
+ }
+
+ [Test]
+ public void TestFindGTRange(){
+ var query = new {Index = Op.GreaterThan(20)};
+ var c = DB.GetCollection("finds").Find(query);
+ foreach(var result in c.Documents)
+ {
+ Assert.IsNotNull(result);
+ Assert.Greater(result.Index, 20);
+ }
+ }
+
+ [Test]
+ public void TestFindNulls(){
+ var query = new {Text = (string)null};
+ var numnulls = DB.GetCollection("finds").Count(query);
+ Assert.AreEqual(5, numnulls);
+ }
+
+ [Test]
+ public void TestFindOne(){
+ var query = new {Index = 10};
+ var result = DB.GetCollection("finds").FindOne(query);
+ Assert.IsNotNull(result);
+ Assert.AreEqual(4, result.x);
+ Assert.AreEqual(10, result.Index);
+ }
+
+ [Test]
+ public void TestFindOneNotThere(){
+ var query = new {not_there = 10};
+ var result = DB.GetCollection("finds").FindOne(query);
+ Assert.IsNull(result);
+ }
+
+ [Test]
+ public void TestFindOneObjectContainingUKPound(){
+ var query = new Document();
+ var result = DB.GetCollection("charreads").FindOne(query);
+ Assert.IsNotNull(result);
+ Assert.AreEqual("1234£56", result.test);
+ }
+
+ [Test]
+ public void TestFindWhereEquivalency(){
+ var col = DB.GetCollection("finds");
+ var lt = new {Index = Op.LessThan(5)};
+ var where = "this.j < 5";
+ var explicitWhere = new Document().Add("$where", new Code(where));
+ var func = new CodeWScope("function() { return this.j < 5; }", new Document());
+ var funcDoc = new Document().Add("$where", func);
+
+ Assert.AreEqual(4, col.Find(lt).Documents.Count(), "Basic find didn't return 4 docs");
+ Assert.AreEqual(4, col.Find(where).Documents.Count(), "String where didn't return 4 docs");
+ Assert.AreEqual(4, col.Find(explicitWhere).Documents.Count(), "Explicit where didn't return 4 docs");
+ Assert.AreEqual(4, col.Find(funcDoc).Documents.Count(), "Function where didn't return 4 docs");
+ }
+
+ [Test]
+ public void TestInsertBulkLargerThan4MBOfDocuments(){
+ var b = new Binary(new byte[1024*1024*2]);
+ var inserts = DB.GetCollection("inserts");
+ try
+ {
+ //6MB+ of documents
+ var docs = from i in Enumerable.Range(1, 10)
+ select new {Song = "Bulk", bin = b, Year = i};
+
+ inserts.Insert(docs, true);
+ var count = inserts.Count(new Document("Song", "Bulk"));
+ Assert.AreEqual(docs.Count(), count, "Wrong number of documents inserted");
+ }
+ catch(MongoException)
+ {
+ Assert.Fail("MongoException should not have been thrown.");
+ }
+ }
+
+ [Test]
+ public void TestInsertOfArray(){
+ var ogen = new OidGenerator();
+ var inserts = DB.GetCollection("inserts");
+ var album = new Album {Title = "Deliveries After Dark", Artist = "Popa Chubby"};
+ album.Songs = new List
+ {
+ new Song {Title = "Let The Music Set You Free", Length = "5:15"},
+ new Song {Title = "Sally Likes to Run", Length = "4:06"},
+ new Song {Title = "Deliveries After Dark", Length = "4:17"},
+ new Song {Title = "Theme From The Godfather", Length = "3:06"},
+ new Song {Title = "Grown Man Crying Blues", Length = "8:09"}
+ };
+ inserts.Insert(album);
+
+ var result = inserts.FindOne(new Document().Add("Songs.Title", "Deliveries After Dark"));
+ Assert.IsNotNull(result);
+
+ Assert.AreEqual(album.Songs.Count, result.Songs.Count);
+ }
+
+ [Test]
+ public void TestSimpleInsert(){
+ var inserts = DB.GetCollection("inserts");
+ var indoc = new InsertsEntity {Artist = "Afroman", Song = "Palmdale", Year = 1999};
+ inserts.Insert(indoc);
+
+ var result = inserts.FindOne(new {Song = "Palmdale"});
+ Assert.IsNotNull(result);
+ Assert.AreEqual(indoc.Year, result.Year);
+ }
+
+ [Test]
+ public void TestUpdateMany(){
+ var updates = DB.GetCollection("updates");
+
+ updates.Insert(new CountsEntity {Last = "Cordr", First = "Sam"});
+ updates.Insert(new CountsEntity {Last = "Cordr", First = "Sam2"});
+ updates.Insert(new CountsEntity {Last = "Cordr", First = "Sam3"});
+
+ var selector = new {Last = "Cordr"};
+ var results = updates.Find(selector);
+ Assert.AreEqual(3, results.Documents.Count(), "Didn't find all Documents inserted for TestUpdateMany with Selector");
+
+ var updateData = new {Last = "Cordr2"};
+ updates.UpdateAll(updateData, selector);
+
+ selector = new {Last = "Cordr2"};
+ results = updates.Find(selector);
+ var count = 0;
+ foreach(var doc in results.Documents)
+ {
+ count++;
+ Assert.AreEqual("Cordr2", doc.Last);
+ Assert.IsNotNull(doc.First, "First name should not disappear");
+ }
+
+ Assert.AreEqual(3, count, "Didn't find all documents for updated.");
+ }
+
+ [Test]
+ public void TestUpdatePartial(){
+ var updates = DB.GetCollection("updates");
+ var coolness = 5;
+ var einstein = new CountsEntity {Last = "Einstein", First = "Albret", Coolness = coolness++};
+ updates.Insert(einstein);
+ var selector = new {Last = "Einstein"};
+
+ updates.Update(new Document {{"$inc", new Document("cnt", 1)}}, selector);
+ Assert.AreEqual(coolness++, Convert.ToInt32(updates.FindOne(selector).Coolness), "Coolness field not incremented", true);
+
+ updates.Update(new Document
+ {
+ {"$set", new {First = "Albert"}},
+ {"$inc", new Document {{"cnt", 1}}}
+ },
+ selector,
+ true);
+ Assert.AreEqual(coolness++, Convert.ToInt32(updates.FindOne(selector).Coolness), "Coolness field not incremented");
+ }
+
+ [Test]
+ public void TestUpdateUpsertExisting(){
+ var updates = DB.GetCollection("updates");
+ var doc = new CountsEntity {First = "Mtt", Last = "Brewer"};
+
+ updates.Insert(doc);
+
+ var selector = new {Last = "Brewer"};
+ doc = updates.FindOne(selector);
+ Assert.IsNotNull(doc);
+ Assert.AreEqual("Mtt", doc.First);
+ Assert.IsNotNull(doc.Id);
+
+ doc.First = "Matt";
+ updates.Update(doc);
+
+ var result = updates.FindOne(selector);
+ Assert.IsNotNull(result);
+ Assert.AreEqual("Matt", result.First);
+ }
+
+ [Test]
+ public void TestUpdateUpsertNotExisting(){
+ var updates = DB.GetCollection("updates");
+ var doc = new CountsEntity {First = "Sam", Last = "CorderNE"};
+
+ updates.Update(doc);
+ var result = updates.FindOne(new {Last = "CorderNE"});
+ Assert.IsNotNull(result);
+ Assert.AreEqual("Sam", result.First);
+ }
+
+ [Test]
+ public void CanSaveNewDocumentsWithoutId(){
+ var saves = DB.GetCollection("saves");
+ saves.Save(new Document("WithoutId", 1.0));
+
+ var result = saves.FindOne(new Document("WithoutId",1.0));
+ Assert.IsNotNull(result);
+ }
+
+ [Test]
+ public void CanSaveNewDocumentWithId(){
+ var saves = DB.GetCollection("saves");
+ saves.Save(new Document("WithId", 1.0).Add("_id", 5));
+
+ var result = saves.FindOne(new Document("_id", 5));
+ Assert.IsNotNull(result);
+ Assert.AreEqual(result.Id,5);
+ }
+
+ [Test]
+ public void SaveUpdatesExistsingDocument(){
+ var saves = DB.GetCollection("saves");
+ var updated = new Document("Existing", 1.0);
+ saves.Insert(updated);
+
+ updated["Existing"] = 2.0;
+
+ saves.Save(updated);
+
+ var result = saves.FindOne(new Document("_id", updated.Id));
+ Assert.IsNotNull(result);
+ Assert.AreEqual(result["Existing"], 2.0);
+ }
+ }
+}
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/TestConcurrency.cs b/source/MongoDB.Tests/IntegrationTests/TestConcurrency.cs
similarity index 96%
rename from MongoDB.Net-Tests/TestConcurrency.cs
rename to source/MongoDB.Tests/IntegrationTests/TestConcurrency.cs
index f18f9fcd..dce37946 100644
--- a/MongoDB.Net-Tests/TestConcurrency.cs
+++ b/source/MongoDB.Tests/IntegrationTests/TestConcurrency.cs
@@ -1,10 +1,9 @@
-using System;
-using System.Collections.Generic;
-using System.Threading;
-
-using NUnit.Framework;
-
-namespace MongoDB.Driver
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests
{
[TestFixture()]
@@ -21,8 +20,8 @@ public override string TestCollections {
}
}
- public override void OnInit (){
- Collection col = (Collection)DB["threadsmallreads"];
+ public override void OnInit (){
+ var col = (IMongoCollection)DB["threadsmallreads"];
for(int j = 0; j < 4; j++){
col.Insert(new Document(){{"x", 4},{"j", j}});
}
@@ -32,8 +31,8 @@ public override void OnInit (){
//[Test]
public void TestMultiThreadedWrites (){
Mongo db = new Mongo();
- db.Connect();
-
+ db.Connect();
+
IMongoCollection col = DB["threadinserts"];
List identifiers = new List{"A", "B", "C", "D"};
@@ -89,8 +88,8 @@ public void TestMultiThreadedReads(){
[Test]
public void TestMultiThreadedReadsAndWrites(){
Mongo db = new Mongo();
- db.Connect();
-
+ db.Connect();
+
IMongoCollection col = DB["threadreadinserts"];
List identifiers = new List{"A", "B", "C", "D"};
@@ -146,8 +145,8 @@ protected void RunAndWait(List threads){
public class Inserter{
public int Iterations{get; set;}
public int Count{get;set;}
- public String Identifier{get; set;}
- public IMongoCollection Collection{get; set;}
+ public String Identifier{get; set;}
+ public IMongoCollection Collection { get; set; }
public void DoInserts(){
for(int x = 0; x < this.Iterations; x++){
@@ -164,13 +163,14 @@ public void DoInserts(){
public class Reader{
public int Iterations{get; set;}
- public int Count{get;set;}
- public IMongoCollection Collection{get; set;}
+ public int Count{get;set;}
+ public IMongoCollection Collection { get; set; }
public void DoReads(){
for(int x = 0; x < this.Iterations; x++){
- try{
- using(ICursor c = this.Collection.FindAll()){
+ try{
+ using(ICursor c = this.Collection.FindAll())
+ {
//Just read one and do nothing with the Document.
foreach(Document d in c.Documents){
d["works"] = true;
diff --git a/source/MongoDB.Tests/IntegrationTests/TestCursor.cs b/source/MongoDB.Tests/IntegrationTests/TestCursor.cs
new file mode 100644
index 00000000..9aa7f993
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/TestCursor.cs
@@ -0,0 +1,150 @@
+using System;
+using System.Linq;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests
+{
+ [TestFixture]
+ public class TestCursor : MongoTestBase
+ {
+ public override string TestCollections
+ {
+ get { return "sorts,hintindex,smallreads,reads"; }
+ }
+
+ public override void OnInit()
+ {
+ //smallreads
+ var smallreads = DB["smallreads"];
+ for(var j = 1; j < 5; j++)
+ smallreads.Insert(new Document {{"x", 4}, {"j", j}});
+ smallreads.Insert(new Document {{"x", 4}, {"j", 5}, {"n", 1}});
+
+ var reads = DB["reads"];
+ for(var j = 1; j < 10000; j++)
+ reads.Insert(new Document {{"x", 4}, {"h", "hi"}, {"j", j}});
+ }
+
+ [Test]
+ public void TestCanLimit()
+ {
+ var c = DB["reads"].FindAll().Limit(5);
+
+ Assert.IsNotNull(c, "Cursor shouldn't be null");
+ var reads = c.Documents.Count();
+ Assert.IsTrue(reads > 0, "No documents were returned.");
+ Assert.AreEqual(5, reads);
+ }
+
+ [Test]
+ public void TestCanReadAndKillCursor()
+ {
+ var c = (Cursor)DB["reads"].FindAll();
+
+ Assert.IsNotNull(c, "Cursor shouldn't be null");
+ c.Documents.Any();
+ c.Dispose();
+ Assert.AreEqual(0, c.Id);
+ }
+
+ [Test]
+ public void TestCanReadMore()
+ {
+ var c = (Cursor)DB["reads"].FindAll();
+
+ Assert.IsNotNull(c, "Cursor shouldn't be null");
+ var reads = 0;
+ var idchanges = 0;
+ long id = 0;
+ foreach(var doc in c.Documents)
+ {
+ reads++;
+ if(c.Id != id)
+ {
+ idchanges++;
+ id = c.Id;
+ }
+ }
+ Assert.IsTrue(reads > 0, "No documents were returned.");
+ Assert.IsTrue(idchanges > 0, String.Format("ReadMore message never sent. {0} changes seen", idchanges));
+ Assert.AreEqual(9999, reads, "Not all documents returned.");
+ Console.Out.Write(String.Format("{0} records read", reads));
+ }
+
+ [Test]
+ public void TestCanReuseCursor()
+ {
+ var c = (Cursor)DB["reads"].FindAll();
+
+ Assert.IsNotNull(c, "Cursor shouldn't be null");
+
+ var firstCount = c.Documents.Count();
+ var secondCount = c.Documents.Count();
+
+ Assert.AreEqual(firstCount,secondCount);
+ }
+
+ [Test]
+ public void TestCanReadSmall()
+ {
+ var c = DB["smallreads"].FindAll();
+
+ Assert.IsNotNull(c, "Cursor shouldn't be null");
+ var reads = c.Documents.Count();
+ Assert.IsTrue(reads > 0, "No documents were returned.");
+ Assert.AreEqual(5, reads, "More than 5 documents in the small reads dataset");
+ }
+
+ [Test]
+ public void TestExplain()
+ {
+ var exp = DB["reads"].FindAll().Limit(5).Skip(5).Sort("x").Explain();
+ Assert.IsTrue(exp.ContainsKey("cursor"));
+ Assert.IsTrue(exp.ContainsKey("n"));
+ Assert.IsTrue(exp.ContainsKey("nscanned"));
+ }
+
+ [Test]
+ public void TestHint()
+ {
+ var reads = DB["reads"];
+ var hint = new Document().Add("x", IndexOrder.Ascending);
+
+ var exp = reads.FindAll().Hint(hint).Explain();
+ Assert.IsTrue(exp.ContainsKey("$err"), "No error found");
+
+ reads.Metadata.CreateIndex("hintindex", hint, false);
+ exp = reads.FindAll().Hint(hint).Explain();
+
+ Assert.IsTrue(exp.ContainsKey("cursor"));
+ Assert.IsTrue(exp.ContainsKey("n"));
+ Assert.IsTrue(exp.ContainsKey("nscanned"));
+ }
+
+ [Test]
+ public void TestSort()
+ {
+ var sorts = DB["sorts"];
+ var randoms = new[] {4, 6, 8, 9, 1, 3, 2, 5, 7, 0};
+ foreach(var x in randoms)
+ sorts.Insert(new Document().Add("x", randoms[x]));
+ Assert.AreEqual(randoms.Length, sorts.Count());
+
+ var exp = 0;
+ foreach(var doc in sorts.FindAll().Sort("x", IndexOrder.Ascending).Documents)
+ {
+ Assert.AreEqual(exp, Convert.ToInt32(doc["x"]));
+ exp++;
+ }
+ Assert.AreEqual(randoms.Length, exp);
+
+ exp = 9;
+ foreach(var doc in sorts.FindAll().Sort("x", IndexOrder.Descending).Documents)
+ {
+ Assert.AreEqual(exp, Convert.ToInt32(doc["x"]));
+ exp--;
+ }
+ Assert.AreEqual(-1, exp);
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/IntegrationTests/TestDatabase.cs b/source/MongoDB.Tests/IntegrationTests/TestDatabase.cs
new file mode 100644
index 00000000..68d5dd1b
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/TestDatabase.cs
@@ -0,0 +1,138 @@
+using System;
+using System.Collections.Generic;
+using NUnit.Framework;
+using System.Configuration;
+
+namespace MongoDB.IntegrationTests
+{
+ [TestFixture]
+ public class TestDatabase : MongoTestBase
+ {
+ public override string TestCollections{
+ get { return "refs,noerror,errcol,preverror"; }
+ }
+
+ [Test]
+ public void TestEvalNoScope(){
+ var result = DB.Eval("function(){return 3;}");
+ Assert.AreEqual(3, result["retval"]);
+ }
+
+ [Test]
+ public void TestEvalWithScope(){
+ var val = 3;
+ var scope = new Document().Add("x", val);
+ var result = DB.Eval("function(){return x;}", scope);
+ Assert.AreEqual(val, result["retval"]);
+ }
+
+ [Test]
+ public void TestEvalWithScopeAsFunctionParameters(){
+ var x = 3;
+ var y = 4;
+ var func = "adder = function(a, b){return a + b;}; return adder(x,y)";
+ var scope = new Document().Add("x", x).Add("y", y);
+ var result = DB.Eval(func, scope);
+ Console.Out.WriteLine(result.ToString());
+ Assert.AreEqual(x + y, result["retval"]);
+ }
+
+ [Test]
+ public void TestFollowNonReference(){
+ var id = new Oid("BAD067c30a57000000008ecb");
+ var rf = new DBRef("refs", id);
+
+ var target = DB.FollowReference(rf);
+ Assert.IsNull(target, "FollowReference returned wasn't null");
+ }
+
+ [Test]
+ public void TestFollowReference(){
+ var refs = DB["refs"];
+ var id = new Oid("4a7067c30a57000000008ecb");
+ var msg = "this has an oid key";
+ var doc = new Document {{"_id", id}, {"msg", msg}};
+ refs.Insert(doc);
+
+ var rf = new DBRef("refs", id);
+
+ var target = DB.FollowReference(rf);
+ Assert.IsNotNull(target, "FollowReference returned null");
+ Assert.IsTrue(target.ContainsKey("msg"));
+ Assert.AreEqual(msg, target["msg"]);
+ }
+
+ [Test]
+ public void TestGetCollectionNames(){
+ var names = DB.GetCollectionNames();
+ Assert.IsNotNull(names, "No collection names returned");
+ Assert.IsTrue(names.Count > 0);
+ Assert.IsTrue(names.Contains("tests.inserts"));
+ }
+
+ [Test]
+ public void TestGetLastError(){
+ var errcol = DB["errcol"];
+ errcol.Metadata.CreateIndex(new Document {{"x", IndexOrder.Ascending}}, true);
+ var dup = new Document {{"x", 1}, {"y", 2}};
+ errcol.Insert(dup);
+ var error = DB.GetLastError();
+ Assert.AreEqual(null, error["err"]);
+
+ errcol.Insert(dup);
+ error = DB.GetLastError();
+
+ Assert.IsFalse(null == error["err"]);
+ }
+
+ [Test]
+ public void TestGetLastErrorNoError(){
+ DB["noerror"].Insert(new Document {{"a", 1}, {"b", 2}});
+ var error = DB.GetLastError();
+ Assert.AreEqual(null, error["err"]);
+ }
+
+ [Test]
+ public void TestGetPrevError(){
+ var col = DB["preverror"];
+ col.Metadata.CreateIndex(new Document {{"x", IndexOrder.Ascending}}, true);
+ var docs = new List();
+ for(var x = 0; x < 10; x++)
+ docs.Add(new Document {{"x", x}, {"y", 2}});
+ docs.Add(new Document {{"x", 1}, {"y", 4}}); //the dupe
+ DB.ResetError();
+ Assert.AreEqual(null, DB.GetLastError()["err"]);
+
+ col.Insert(docs);
+ var error = DB.GetLastError();
+
+ Assert.IsFalse(null == error["err"]);
+ }
+
+ [Test]
+ public void TestReferenceNonOid(){
+ var refs = DB["refs"];
+
+ var doc = new Document().Add("_id", 123).Add("msg", "this has a non oid key");
+ refs.Insert(doc);
+
+ var rf = new DBRef("refs", 123);
+
+ var recv = DB.FollowReference(rf);
+
+ Assert.IsNotNull(recv);
+ Assert.IsTrue(recv.ContainsKey("msg"));
+ Assert.AreEqual(recv["_id"], (long)123);
+ }
+
+ [Test]
+ public void TestCanCreateFromConnectionString(){
+ var builder = new MongoConnectionStringBuilder(ConfigurationManager.AppSettings["tests"]) {Database = "tests"};
+ /*
+ using(var database = new MongoDatabase(builder.ToString()))
+ {
+
+ }*/
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/IntegrationTests/TestDatabaseJavascript.cs b/source/MongoDB.Tests/IntegrationTests/TestDatabaseJavascript.cs
new file mode 100644
index 00000000..9555a14c
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/TestDatabaseJavascript.cs
@@ -0,0 +1,209 @@
+using System;
+using System.Linq;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests
+{
+ [TestFixture]
+ public class TestDatabaseJavascript : MongoTestBase
+ {
+ private DatabaseJavascript _javascript;
+
+ public override string TestCollections
+ {
+ get { return "jsreads"; }
+ }
+
+ public override void OnInit()
+ {
+ DB["system.js"].Delete(new Document());
+ _javascript = DB.Javascript;
+
+ var jsreads = DB["jsreads"];
+ for(var j = 1; j < 10; j++)
+ jsreads.Insert(new Document {{"j", j}});
+ }
+
+ protected void AddFunction(string name)
+ {
+ var func = new Code("function(x,y){return x + y;}");
+ DB["system.js"].Insert(new Document().Add("_id", name).Add("value", func));
+ }
+
+ [Test]
+ public void TestCanAddAFunctionDoc()
+ {
+ const string name = "fadddoc";
+ var func = new Code("function(x, y){return x + y;}");
+ var doc = new Document().Add("_id", name).Add("value", func);
+ _javascript.Add(doc);
+ Assert.IsNotNull(_javascript[name]);
+ }
+
+ [Test]
+ public void TestCanAddAFunctionStrCode()
+ {
+ const string name = "faddsc";
+ var func = new Code("function(x, y){return x + y;}");
+ _javascript.Add(name, func);
+ Assert.IsNotNull(_javascript[name]);
+ }
+
+ [Test]
+ public void TestCanAddAFunctionStrStr()
+ {
+ const string name = "faddss";
+ var func = "function(x, y){return x + y;}";
+ _javascript.Add(name, func);
+ Assert.IsNotNull(_javascript[name]);
+ }
+
+ [Test]
+ public void TestCanAddFunctionByAssignment()
+ {
+ const string name = "fassignadd";
+ var func = new Code("function(x,y){return x + y;}");
+ var doc = new Document().Add("_id", name).Add("value", func);
+ _javascript[name] = doc;
+ Assert.IsNotNull(_javascript[name]);
+ }
+
+ [Test]
+ public void TestCanGetAFunction()
+ {
+ const string name = "fget";
+ AddFunction(name);
+ Assert.IsNotNull(_javascript[name]);
+ Assert.IsNotNull(_javascript.GetFunction(name));
+ }
+
+ [Test]
+ public void TestCanGetDatabaseJSObject()
+ {
+ Assert.IsNotNull(DB.Javascript);
+ }
+
+ [Test]
+ public void TestCanListFunctions()
+ {
+ const string name = "flist";
+ AddFunction(name);
+ var list = _javascript.GetFunctionNames();
+ Assert.IsTrue(list.Count > 0);
+
+ var found = false;
+ foreach(var l in list)
+ if(l == name)
+ found = true;
+ Assert.IsTrue(found, "Didn't find the function that was inserted.");
+ }
+
+ [Test]
+ public void TestCannotAddAFunctionTwice()
+ {
+ const string name = "faddtwice";
+ var func = new Code("function(x,y){return x + y;}");
+ _javascript.Add(name, func);
+ var thrown = false;
+ try
+ {
+ _javascript.Add(name, func);
+ }
+ catch(ArgumentException)
+ {
+ thrown = true;
+ }
+ Assert.IsTrue(thrown, "Shouldn't be able to add a function twice");
+ }
+
+ [Test]
+ public void TestClear()
+ {
+ AddFunction("clear");
+ Assert.IsTrue(_javascript.Count > 0);
+ _javascript.Clear();
+ Assert.IsTrue(_javascript.Count == 0);
+ }
+
+ [Test]
+ public void TestContains()
+ {
+ const string name = "fcontains";
+ AddFunction(name);
+ Assert.IsTrue(_javascript.Contains(name));
+ Assert.IsFalse(_javascript.Contains("none"));
+ Assert.IsTrue(_javascript.Contains(new Document().Add("_id", name).Add("value", new Code("dfs"))));
+ }
+
+ [Test]
+ public void TestCopyTo()
+ {
+ const int count = 5;
+ var functions = new Document[count];
+ var funcCode = new Code("function(x,y){return x+y;}");
+
+ for(var i = 0; i < count; i++)
+ {
+ var name = string.Format("_{0}fcopyTo", i);
+ _javascript[name] = new Document("_id", name).Add("value", funcCode);
+ }
+
+ _javascript.CopyTo(functions, 1);
+
+ Assert.IsNull(functions[0]);
+ Assert.IsNotNull(functions[1]);
+ Assert.IsNotNull(functions[4]);
+
+ Assert.AreEqual("_1fcopyTo", functions[1]["_id"]);
+ Assert.IsTrue(((string)functions[1]["_id"]).StartsWith("_1")); //as long as no other _ named functions get in.
+ }
+
+ [Test]
+ public void TestExec()
+ {
+ _javascript.Add("lt4", new Code("function(doc){return doc.j < 4;}"));
+ var cnt = DB["reads"].Find("lt4(this)").Documents.Count();
+ Assert.AreEqual(3, cnt);
+ }
+
+ [Test]
+ public void TestExecWithScope()
+ {
+ _javascript.Add("lt", new Code("function(doc){ return doc.j < limit;}"));
+ var scope = new Document().Add("limit", 5);
+ var query = new Document().Add("$where", new CodeWScope("lt(this)", scope));
+ var cnt = DB["jsreads"].Find(query).Documents.Count();
+ Assert.AreEqual(4, cnt);
+ }
+
+ [Test]
+ public void TestForEach()
+ {
+ var name = "foreach";
+ AddFunction(name);
+ var found = _javascript.Any(doc => name.Equals(doc["_id"]));
+ Assert.IsTrue(found, "Added function wasn't found during foreach");
+ }
+
+ [Test]
+ public void TestRemoveByDoc()
+ {
+ const string name = "fremoved";
+ var func = new Document().Add("_id", name);
+ AddFunction(name);
+ Assert.IsTrue(_javascript.Contains(name));
+ _javascript.Remove(func);
+ Assert.IsFalse(_javascript.Contains(name));
+ }
+
+ [Test]
+ public void TestRemoveByName()
+ {
+ const string name = "fremoven";
+ AddFunction(name);
+ Assert.IsTrue(_javascript.Contains(name));
+ _javascript.Remove(name);
+ Assert.IsFalse(_javascript.Contains(name));
+ }
+ }
+}
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/TestDatabaseMetaData.cs b/source/MongoDB.Tests/IntegrationTests/TestDatabaseMetaData.cs
similarity index 76%
rename from MongoDB.Net-Tests/TestDatabaseMetaData.cs
rename to source/MongoDB.Tests/IntegrationTests/TestDatabaseMetaData.cs
index 853f89b7..c977ccdf 100644
--- a/MongoDB.Net-Tests/TestDatabaseMetaData.cs
+++ b/source/MongoDB.Tests/IntegrationTests/TestDatabaseMetaData.cs
@@ -1,9 +1,8 @@
-using System;
-using System.Collections.Generic;
-
-using NUnit.Framework;
-
-namespace MongoDB.Driver
+using System;
+using System.Collections.Generic;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests
{
[TestFixture]
public class TestDatabaseMetaData : MongoTestBase
@@ -15,13 +14,13 @@ public override string TestCollections {
}
public override void OnInit () {
- //Add any new collections ones to work on.
- DB["$cmd"].FindOne(new Document().Append("create","todrop"));
+ //Add any new collections ones to work on.
+ DB["$cmd"].FindOne(new Document().Add("create", "todrop"));
}
[Test]
public void TestCreateCollectionNoOptions(){
- DB.MetaData.CreateCollection("creatednoopts");
+ DB.Metadata.CreateCollection("creatednoopts");
List names = DB.GetCollectionNames();
Assert.IsTrue(names.Contains("tests.creatednoopts"));
@@ -29,9 +28,9 @@ public void TestCreateCollectionNoOptions(){
}
[Test]
- public void TestCreateCollectionWithOptions(){
- Document options = new Document().Append("capped",true).Append("size",10000);
- DB.MetaData.CreateCollection("createdcapped",options);
+ public void TestCreateCollectionWithOptions(){
+ Document options = new Document().Add("capped", true).Add("size", 10000);
+ DB.Metadata.CreateCollection("createdcapped",options);
List names = DB.GetCollectionNames();
Assert.IsTrue(names.Contains("tests.createdcapped"));
@@ -39,9 +38,9 @@ public void TestCreateCollectionWithOptions(){
}
[Test]
- public void TestCreateCollectionWithInvalidOptions(){
- Document options = new Document().Append("invalidoption",true);
- DB.MetaData.CreateCollection("createdinvalid",options);
+ public void TestCreateCollectionWithInvalidOptions(){
+ Document options = new Document().Add("invalidoption", true);
+ DB.Metadata.CreateCollection("createdinvalid",options);
List names = DB.GetCollectionNames();
Assert.IsTrue(names.Contains("tests.createdinvalid"));
@@ -50,7 +49,7 @@ public void TestCreateCollectionWithInvalidOptions(){
[Test]
public void TestDropCollection(){
- bool dropped = DB.MetaData.DropCollection("todrop");
+ bool dropped = DB.Metadata.DropCollection("todrop");
Assert.IsTrue(dropped,"Dropped was false");
@@ -63,7 +62,7 @@ public void TestDropCollection(){
public void TestDropInvalidCollection(){
bool thrown = false;
try{
- DB.MetaData.DropCollection("todrop_notexists");
+ DB.Metadata.DropCollection("todrop_notexists");
}catch(MongoCommandException){
thrown = true;
}
diff --git a/source/MongoDB.Tests/IntegrationTests/TestMapReduce.cs b/source/MongoDB.Tests/IntegrationTests/TestMapReduce.cs
new file mode 100644
index 00000000..139a5937
--- /dev/null
+++ b/source/MongoDB.Tests/IntegrationTests/TestMapReduce.cs
@@ -0,0 +1,126 @@
+using System;
+using NUnit.Framework;
+
+namespace MongoDB.IntegrationTests
+{
+ [TestFixture]
+ public class TestMapReduce : MongoTestBase
+ {
+ private IMongoCollection _collection;
+
+ private const string MapFunc = "function(){\n" +
+ " this.tags.forEach(\n" +
+ " function(z){\n" +
+ " emit( z , { count : 1 } );\n" +
+ " });\n" +
+ "};";
+
+ private const string ReduceFunc = "function( key , values ){\n" +
+ " var total = 0;\n" +
+ " for ( var i=0; i
+
+
+ Debug
+ AnyCPU
+ 9.0.30729
+ 2.0
+ {C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}
+ Library
+ MongoDB.Tests
+
+
+ 3.5
+
+
+ false
+ v3.5
+ MongoDB.Driver.Tests
+ C:\Documents and Settings\scorder\Application Data\ICSharpCode/SharpDevelop3.0\Settings.SourceAnalysis
+ False
+ False
+ false
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ true
+ v3.5
+ MongoDB
+ C:\Documents and Settings\scorder\Application Data\ICSharpCode/SharpDevelop3.0\Settings.SourceAnalysis
+ False
+ False
+ false
+ true
+ ..\..\StrongName.snk
+
+
+ true
+ full
+ false
+ bin\Debug
+ TRACE;DEBUG
+ prompt
+ 4
+ 618, 1718
+ AllRules.ruleset
+
+
+ none
+ false
+ bin\Release
+ prompt
+ 4
+ AllRules.ruleset
+
+
+ False
+
+
+ False
+ Auto
+ 4194304
+ AnyCPU
+ 4096
+
+
+
+ False
+ ..\..\redist\nunit.framework.dll
+
+
+
+
+ 3.5
+
+
+
+ 3.5
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ False
+ .NET Framework 3.5 SP1 Client Profile
+ false
+
+
+ False
+
+
+ false
+
+
+ False
+
+
+ false
+
+
+ False
+
+
+ false
+
+
+ False
+ .NET Framework 3.5 SP1
+ false
+
+
+
+
+ {B125BBA6-BFFD-44FA-9254-9B1754CD8AF3}
+ MongoDB
+
+
+
+
+
+ Always
+
+
+
+
+ StrongName.snk
+
+
+ true
+ MongoDB.Driver.Tests.dll.config
+ PreserveNewest
+
+
+ PreserveNewest
+
+
+ PreserveNewest
+
+
+
+
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/MongoTestBase.cs b/source/MongoDB.Tests/MongoTestBase.cs
old mode 100755
new mode 100644
similarity index 75%
rename from MongoDB.Net-Tests/MongoTestBase.cs
rename to source/MongoDB.Tests/MongoTestBase.cs
index f0bdf3e2..209dd834
--- a/MongoDB.Net-Tests/MongoTestBase.cs
+++ b/source/MongoDB.Tests/MongoTestBase.cs
@@ -1,26 +1,25 @@
using System;
using System.Configuration;
-
using NUnit.Framework;
+using MongoDB.Configuration;
-namespace MongoDB.Driver
+namespace MongoDB
{
-
public abstract class MongoTestBase
{
public Mongo Mongo{get;set;}
- public Database DB{
+
+ public IMongoDatabase DB{
get{
return this.Mongo["tests"];
}
}
-
+
///
/// Comma separated list of collections to clean at startup.
///
public abstract string TestCollections{get;}
-
///
/// Override to add custom initialization code.
///
@@ -31,15 +30,12 @@ public virtual void OnInit(){}
///
public virtual void OnDispose(){}
-
///
/// Sets up the test environment. You can either override this OnInit to add custom initialization.
///
[TestFixtureSetUp]
public virtual void Init(){
- string connstr = ConfigurationManager.AppSettings["tests"];
- if(String.IsNullOrEmpty(connstr)) throw new ArgumentNullException("Connection string not found.");
- this.Mongo = new Mongo(connstr);
+ this.Mongo = new Mongo(GetConfiguration().BuildConfiguration());
this.Mongo.Connect();
CleanDB();
OnInit();
@@ -58,5 +54,12 @@ protected void CleanDB(){
//Console.WriteLine("Dropping " + col);
}
}
+
+ protected virtual MongoConfigurationBuilder GetConfiguration()
+ {
+ var builder = new MongoConfigurationBuilder();
+ builder.ReadConnectionStringFromAppSettings("tests");
+ return builder;
+ }
}
}
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/test-data/tests.binary.txt b/source/MongoDB.Tests/Test-Data/tests.binary.txt
similarity index 100%
rename from MongoDB.Net-Tests/test-data/tests.binary.txt
rename to source/MongoDB.Tests/Test-Data/tests.binary.txt
diff --git a/MongoDB.Net-Tests/test-data/tests.charreads.txt b/source/MongoDB.Tests/Test-Data/tests.charreads.txt
similarity index 100%
rename from MongoDB.Net-Tests/test-data/tests.charreads.txt
rename to source/MongoDB.Tests/Test-Data/tests.charreads.txt
diff --git a/MongoDB.Net-Tests/test-data/tests.reads.txt b/source/MongoDB.Tests/Test-Data/tests.reads.txt
similarity index 100%
rename from MongoDB.Net-Tests/test-data/tests.reads.txt
rename to source/MongoDB.Tests/Test-Data/tests.reads.txt
diff --git a/MongoDB.Net-Tests/test-data/tests.smallreads.txt b/source/MongoDB.Tests/Test-Data/tests.smallreads.txt
similarity index 100%
rename from MongoDB.Net-Tests/test-data/tests.smallreads.txt
rename to source/MongoDB.Tests/Test-Data/tests.smallreads.txt
diff --git a/source/MongoDB.Tests/UnitTests/Bson/BsonTestBase.cs b/source/MongoDB.Tests/UnitTests/Bson/BsonTestBase.cs
new file mode 100644
index 00000000..f2ad495e
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/Bson/BsonTestBase.cs
@@ -0,0 +1,62 @@
+using System;
+using System.IO;
+using MongoDB.Bson;
+
+namespace MongoDB.UnitTests.Bson
+{
+ public abstract class BsonTestBase
+ {
+ protected string Serialize(Document document)
+ {
+ return Serialize(document, new BsonWriterSettings());
+ }
+
+ protected string Serialize(Document document, BsonWriterSettings settings)
+ {
+ using(var mem = new MemoryStream())
+ {
+ var writer = new BsonWriter(mem, settings);
+ writer.WriteObject(document);
+ writer.Flush();
+ return Convert.ToBase64String(mem.ToArray());
+ }
+ }
+
+ protected Document Deserialize(string base64){
+ return Deserialize(base64, new BsonReaderSettings());
+ }
+
+ protected Document Deserialize(string base64, BsonReaderSettings settings)
+ {
+ using(var mem = new MemoryStream(Convert.FromBase64String(base64)))
+ {
+ var reader = new BsonReader(mem, settings);
+ return (Document)reader.ReadObject();
+ }
+ }
+
+
+ protected byte[] HexToBytes(string hex)
+ {
+ //TODO externalize somewhere.
+ if (hex.Length % 2 == 1)
+ {
+ Console.WriteLine("uneven number of hex pairs.");
+ hex = "0" + hex;
+ }
+ var numberChars = hex.Length;
+ var bytes = new byte[numberChars / 2];
+ for (var i = 0; i < numberChars; i += 2)
+ try
+ {
+ bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
+ }
+ catch
+ {
+ //failed to convert these 2 chars, they may contain illegal charracters
+ bytes[i / 2] = 0;
+ }
+ return bytes;
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/UnitTests/Bson/TestBsonBinary.cs b/source/MongoDB.Tests/UnitTests/Bson/TestBsonBinary.cs
new file mode 100644
index 00000000..515fa9df
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/Bson/TestBsonBinary.cs
@@ -0,0 +1,60 @@
+using System;
+using System.IO;
+using MongoDB.Bson;
+using NUnit.Framework;
+
+namespace MongoDB.UnitTests.Bson
+{
+ [TestFixture]
+ public class TestBsonBinary
+ {
+ protected static byte[] DecodeHex(string val){
+ var numberChars = val.Length;
+
+ var bytes = new byte[numberChars/2];
+ for(var i = 0; i < numberChars; i += 2)
+ try{
+ bytes[i/2] = Convert.ToByte(val.Substring(i, 2), 16);
+ }
+ catch{
+ //failed to convert these 2 chars, they may contain illegal charracters
+ bytes[i/2] = 0;
+ }
+ return bytes;
+ }
+
+ [Test]
+ public void TestBinaryRead(){
+ const string hex = "28000000075f6964004b1971811d8b0f00c0000000056461746100070000000203000000e188b400";
+
+ var data = DecodeHex(hex);
+ var inmem = new MemoryStream(data);
+ var inreader = new BsonReader(inmem,new BsonDocumentBuilder());
+ var indoc = inreader.Read();
+
+ var outmem = new MemoryStream();
+ var outwriter = new BsonWriter(outmem, new BsonDocumentDescriptor());
+ outwriter.WriteObject(indoc);
+ var outdata = outmem.ToArray();
+ var outhex = BitConverter.ToString(outdata);
+ outhex = outhex.Replace("-", "");
+
+ Assert.AreEqual(hex, outhex.ToLower());
+ }
+
+ [Test]
+ public void TestRoundTrip(){
+ var idoc = new Document{{"b", new Binary(new[]{(byte)1, (byte)2})}};
+
+ var stream = new MemoryStream();
+ var writer = new BsonWriter(stream, new BsonDocumentDescriptor());
+ writer.WriteObject(idoc);
+
+ stream.Seek(0, SeekOrigin.Begin);
+ var reader = new BsonReader(stream,new BsonDocumentBuilder());
+ var odoc = reader.Read();
+
+ Assert.AreEqual(idoc.ToString(), odoc.ToString());
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/UnitTests/Bson/TestBsonReader.cs b/source/MongoDB.Tests/UnitTests/Bson/TestBsonReader.cs
new file mode 100644
index 00000000..92a6d83e
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/Bson/TestBsonReader.cs
@@ -0,0 +1,287 @@
+using System;
+using System.IO;
+using System.Text;
+using MongoDB.Bson;
+using MongoDB.Util;
+using NUnit.Framework;
+
+namespace MongoDB.UnitTests.Bson
+{
+ [TestFixture]
+ public class TestBsonReader : BsonTestBase
+ {
+ private char pound = '\u00a3';
+ private char euro = '\u20ac';
+
+ private string WriteAndReadString(string val){
+ var buf = Encoding.UTF8.GetBytes(val + '\0');
+
+ var ms = new MemoryStream(buf);
+ var reader = new BsonReader(ms, new BsonDocumentBuilder());
+ return reader.ReadString();
+ }
+
+ private string WriteAndReadLenString(string val){
+ var ms = new MemoryStream();
+ var bs = new BsonWriter(ms, new BsonDocumentDescriptor());
+ var w = new BinaryWriter(ms);
+ var byteCount = bs.CalculateSize(val, false);
+ w.Write(byteCount);
+ bs.Write(val, false);
+ ms.Seek(0, SeekOrigin.Begin);
+ var reader = new BsonReader(ms, new BsonDocumentBuilder());
+ return reader.ReadLengthString();
+ }
+
+ [Test]
+ public void TestReadDocWithDocs(){
+ // Document doc = new Document().Append("a", new Document().Append("b", new Document().Append("c",new Document())));
+ // Console.WriteLine(ConvertDocToHex(doc));
+ var buf = HexToBytes("1D000000036100150000000362000D0000000363000500000000000000");
+ var ms = new MemoryStream(buf);
+ var reader = new BsonReader(ms, new BsonDocumentBuilder());
+
+ var doc = (Document)reader.ReadObject();
+ Assert.IsNotNull(doc, "Document was null");
+ Assert.AreEqual(buf.Length, reader.Position);
+ Assert.IsTrue(doc.ContainsKey("a"));
+ }
+
+ [Test]
+ public void TestReadEmptyDocument(){
+ var buf = HexToBytes("0500000000");
+ var ms = new MemoryStream(buf);
+ var reader = new BsonReader(ms, new BsonDocumentBuilder());
+
+ var doc = (Document)reader.ReadObject();
+
+ Assert.IsNotNull(doc);
+ }
+
+ [Test]
+ public void TestReadLenString(){
+ const string expected = "test";
+ Assert.AreEqual(expected, WriteAndReadLenString(expected));
+ }
+
+ [Test]
+ public void TestReadLenStringLong(){
+ var sb = new StringBuilder();
+ sb.Append('t', 150);
+ var expected = sb.ToString();
+ Assert.AreEqual(expected, WriteAndReadLenString(expected));
+ }
+
+ [Test]
+ public void TestReadLenStringShortTripleByte(){
+ var sb = new StringBuilder();
+ //sb.Append('1',127); //first char of euro at the end of the boundry.
+ //sb.Append(euro, 5);
+ //sb.Append('1',128);
+ sb.Append(euro);
+
+ var expected = sb.ToString();
+ Assert.AreEqual(expected, WriteAndReadLenString(expected));
+ }
+
+ [Test]
+ public void TestReadLenStringTripleByteCharBufferBoundry0(){
+ var sb = new StringBuilder();
+ sb.Append('1', 127); //first char of euro at the end of the boundry.
+ sb.Append(euro, 5);
+ sb.Append('1', 128);
+ sb.Append(euro);
+
+ var expected = sb.ToString();
+ Assert.AreEqual(expected, WriteAndReadLenString(expected));
+ }
+
+ [Test]
+ public void TestReadLenStringTripleByteCharBufferBoundry1(){
+ var sb = new StringBuilder();
+ sb.Append('1', 126);
+ sb.Append(euro, 5); //middle char of euro at the end of the boundry.
+ sb.Append('1', 128);
+ sb.Append(euro);
+
+ var expected = sb.ToString();
+ Assert.AreEqual(expected, WriteAndReadLenString(expected));
+ }
+
+ [Test]
+ public void TestReadLenStringTripleByteCharBufferBoundry2(){
+ var sb = new StringBuilder();
+ sb.Append('1', 125);
+ sb.Append(euro, 5); //last char of the eruo at the end of the boundry.
+ sb.Append('1', 128);
+ sb.Append(euro);
+
+ var expected = sb.ToString();
+ Assert.AreEqual(expected, WriteAndReadLenString(expected));
+ }
+
+ [Test]
+ public void TestReadLenStringTripleByteCharOne(){
+ var sb = new StringBuilder();
+ sb.Append(euro, 1); //Just one triple byte char in the string.
+
+ var expected = sb.ToString();
+ Assert.AreEqual(expected, WriteAndReadLenString(expected));
+ }
+
+ [Test]
+ public void TestReadLenStringValue(){
+ const string expected = "test";
+
+ Assert.AreEqual(expected, WriteAndReadLenString(expected));
+ }
+
+ [Test]
+ public void TestReadMultiElementDocument(){
+ var buf = HexToBytes("2D000000075F6964004A753AD8FAC16EA58B290351016100000000000000F03F02620005000000746573740000");
+ var ms = new MemoryStream(buf);
+ var reader = new BsonReader(ms, new BsonDocumentBuilder());
+
+ var doc = (Document)reader.ReadObject();
+
+ Assert.IsNotNull(doc, "Document was null");
+ Assert.IsTrue(doc.ContainsKey("_id"));
+ Assert.IsTrue(doc.ContainsKey("a"));
+ Assert.IsTrue(doc.ContainsKey("b"));
+ Assert.AreEqual("4a753ad8fac16ea58b290351", (doc["_id"]).ToString());
+ Assert.AreEqual(1, Convert.ToInt32(doc["a"]));
+ Assert.AreEqual("test", doc["b"]);
+ }
+
+ [Test]
+ public void TestReadSimpleDocument(){
+ var buf = HexToBytes("1400000002746573740005000000746573740000");
+ var ms = new MemoryStream(buf);
+ var reader = new BsonReader(ms, new BsonDocumentBuilder());
+
+ var doc = reader.Read();
+
+ Assert.IsNotNull(doc, "Document was null");
+ Assert.IsTrue(doc.ContainsKey("test"));
+ Assert.AreEqual("test", doc["test"]);
+ }
+
+ [Test]
+ public void TestReadString(){
+ var buf = HexToBytes("7465737400");
+ var ms = new MemoryStream(buf);
+ var reader = new BsonReader(ms, new BsonDocumentBuilder());
+
+ var s = reader.ReadString();
+ Assert.AreEqual("test", s);
+ Assert.AreEqual(4, Encoding.UTF8.GetByteCount(s));
+ }
+
+ [Test]
+ public void TestReadBigDocument(){
+ MemoryStream ms = new MemoryStream();
+ var writer = new BsonWriter(ms, new BsonDocumentDescriptor());
+
+ Document expected = new Document();
+ expected.Append("str", "test")
+ .Append("int", 45)
+ .Append("long", (long)46)
+ .Append("num", 4.5)
+ .Append("date",DateTime.Today)
+ .Append("_id", new OidGenerator().Generate())
+ .Append("code", new Code("return 1;"))
+ .Append("subdoc", new Document().Append("a",1).Append("b",2))
+ .Append("array", new String[]{"a","b","c","d"})
+ .Append("codewscope", new CodeWScope("return 2;", new Document().Append("c",1)))
+ .Append("binary", new Binary(new byte[]{0,1,2,3}))
+ .Append("regex", new MongoRegex("[A-Z]"))
+ .Append("minkey", MongoMinKey.Value)
+ .Append("maxkey", MongoMaxKey.Value)
+ .Append("symbol", new MongoSymbol("symbol"))
+ ;
+ writer.WriteObject(expected);
+ writer.Flush();
+ ms.Seek(0,SeekOrigin.Begin);
+
+ BsonReader reader = new BsonReader(ms, new BsonDocumentBuilder());
+ Document doc = reader.Read();
+
+ Assert.IsNotNull(doc);
+ }
+
+ [Test]
+ public void TestReadStringBreakDblByteCharOverBuffer(){
+ var sb = new StringBuilder();
+ sb.Append('1', 127);
+ sb.Append(pound); //will break the pound symbol over the buffer boundry.
+ //sb.Append("1");
+
+ var expected = sb.ToString();
+ Assert.AreEqual(expected, WriteAndReadString(expected));
+ }
+
+ [Test]
+ public void TestReadStringDblByteCharOnEndOfBufferBoundry(){
+ var sb = new StringBuilder();
+ sb.Append(pound, 66); //puts a pound symbol at the end of the buffer boundry but not broken.
+ var expected = sb.ToString();
+ Assert.AreEqual(expected, WriteAndReadString(expected));
+ }
+
+ [Test]
+ public void TestReadStringLong(){
+ var sb = new StringBuilder();
+ sb.Append('t', 256);
+ var expected = sb.ToString();
+ Assert.AreEqual(expected, WriteAndReadString(expected));
+ }
+
+ [Test]
+ public void TestReadStringTripleByteCharBufferBoundry(){
+ var sb = new StringBuilder();
+ sb.Append("12");
+ sb.Append(euro, 66); //will break the euro symbol over the buffer boundry.
+
+ var expected = sb.ToString();
+
+ Assert.AreEqual(expected, WriteAndReadString(expected));
+ }
+
+ [Test]
+ public void TestReadStringWithUkPound(){
+ const string expected = "1234£56";
+ Assert.AreEqual(expected, WriteAndReadString(expected));
+ }
+
+ [Test]
+ public void TestReadUtcTimeByDefault(){
+ var document = Deserialize("EwAAAAl0aW1lAADJU+klAQAAAA==");
+
+ var dateTime = new DateTime(2010, 1, 1, 10, 0, 0, DateTimeKind.Utc);
+
+ Assert.AreEqual(dateTime, document["time"]);
+ }
+
+ [Test]
+ public void TestReadUtcTimeToLocalTime(){
+ var settings = new BsonReaderSettings {ReadLocalTime = true};
+
+ var document = Deserialize("EwAAAAl0aW1lAADJU+klAQAAAA==", settings);
+
+ var localtzoffset =TimeZoneInfo.Local.BaseUtcOffset.Hours - 1; //gmt offset the local date was saved in along with the local offset.
+
+ var dateTime = new DateTime(2010, 1, 1, 11, 0, 0, DateTimeKind.Local).AddHours(localtzoffset);
+ Assert.AreEqual(dateTime, document["time"]);
+ }
+
+ [Test]
+ public void TestCanReadNagativeDates()
+ {
+ const string bson = "EwAAAAlkYXRlAIBFaoO2////AA==";
+
+ var document = Deserialize(bson);
+
+ Assert.AreEqual(new DateTime(1960,1,1).ToUniversalTime(),document["date"]);
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/UnitTests/Bson/TestBsonWriter.cs b/source/MongoDB.Tests/UnitTests/Bson/TestBsonWriter.cs
new file mode 100644
index 00000000..b32a6163
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/Bson/TestBsonWriter.cs
@@ -0,0 +1,258 @@
+using System;
+using System.IO;
+using System.Text;
+using System.Text.RegularExpressions;
+using MongoDB.Bson;
+using NUnit.Framework;
+
+namespace MongoDB.UnitTests.Bson
+{
+ [TestFixture]
+ public class TestBsonWriter : BsonTestBase
+ {
+ private char euro = '\u20ac';
+
+ private string WriteStringAndGetHex(string val)
+ {
+ var ms = new MemoryStream();
+ var writer = new BsonWriter(ms, new BsonDocumentDescriptor());
+ writer.Write(val, false);
+ return BitConverter.ToString(ms.ToArray());
+ }
+
+ [Test]
+ public void TestCalculateSizeOfComplexDoc()
+ {
+ var doc = new Document();
+ doc.Add("a", "a");
+ doc.Add("b", 1);
+ var sub = new Document().Add("c_1", 1).Add("c_2", DateTime.Now);
+ doc.Add("c", sub);
+ var ms = new MemoryStream();
+ var writer = new BsonWriter(ms, new BsonDocumentDescriptor());
+
+ Assert.AreEqual(51, writer.CalculateSizeObject(doc));
+ }
+
+ [Test]
+ public void TestCalculateSizeOfEmptyDoc()
+ {
+ var doc = new Document();
+ var ms = new MemoryStream();
+ var writer = new BsonWriter(ms, new BsonDocumentDescriptor());
+
+ Assert.AreEqual(5, writer.CalculateSizeObject(doc));
+ }
+
+ [Test]
+ public void TestCalculateSizeOfSimpleDoc()
+ {
+ var doc = new Document {{"a", "a"}, {"b", 1}};
+
+ var ms = new MemoryStream();
+ var writer = new BsonWriter(ms, new BsonDocumentDescriptor());
+ //BsonDocument bdoc = BsonConvert.From(doc);
+
+ Assert.AreEqual(21, writer.CalculateSizeObject(doc));
+ }
+
+ [Test]
+ public void TestLocalDateTimeIsWrittenAsUtcTime()
+ {
+ var localtzoffset = TimeZoneInfo.Local.BaseUtcOffset.Hours;
+
+ var dateTime = new DateTime(2010, 1, 1, 11, 0, 0, DateTimeKind.Local);
+ var utcTime = new DateTime(2010, 1, 1, 11 - localtzoffset, 0, 0, DateTimeKind.Utc);
+
+ var base64 = Serialize(new Document("time", dateTime));
+ var expected = Serialize(new Document("time", utcTime));
+
+ Assert.AreEqual(expected, base64);
+ }
+
+ [Test]
+ public void TestNullsDontThrowExceptions()
+ {
+ var ms = new MemoryStream();
+ var writer = new BsonWriter(ms, new BsonDocumentDescriptor());
+ var doc = new Document().Add("n", null);
+ try
+ {
+ writer.WriteObject(doc);
+ }
+ catch(NullReferenceException)
+ {
+ Assert.Fail("Null Reference Exception was thrown on trying to serialize a null value");
+ }
+ }
+
+ [Test]
+ public void TestWriteArrayDoc()
+ {
+ const string expected = "2000000002300002000000610002310002000000620002320002000000630000";
+ var ms = new MemoryStream();
+ var writer = new BsonWriter(ms, new BsonDocumentDescriptor());
+
+ var str = new[] {"a", "b", "c"};
+ writer.WriteValue(BsonType.Array, str);
+
+ var hexdump = BitConverter.ToString(ms.ToArray());
+ hexdump = hexdump.Replace("-", "");
+ Assert.AreEqual(expected, hexdump);
+ }
+
+ [Test]
+ public void TestWriteDocument()
+ {
+ var ms = new MemoryStream();
+ var writer = new BsonWriter(ms, new BsonDocumentDescriptor());
+ const string expected = "1400000002746573740005000000746573740000";
+ var doc = new Document().Add("test", "test");
+
+ writer.WriteObject(doc);
+
+ var hexdump = BitConverter.ToString(ms.ToArray());
+ hexdump = hexdump.Replace("-", "");
+
+ Assert.AreEqual(expected, hexdump);
+ }
+
+ [Test]
+ public void TestWriteMultibyteString()
+ {
+ var val = new StringBuilder().Append(euro, 3).ToString();
+ var expected = BitConverter.ToString(Encoding.UTF8.GetBytes(val + '\0'));
+ Assert.AreEqual(expected, WriteStringAndGetHex(val));
+ }
+
+ [Test]
+ public void TestWriteMultibyteStringLong()
+ {
+ var val = new StringBuilder().Append("ww").Append(euro, 180).ToString();
+ var expected = BitConverter.ToString(Encoding.UTF8.GetBytes(val + '\0'));
+ Assert.AreEqual(expected, WriteStringAndGetHex(val));
+ }
+
+ [Test]
+ public void TestWriteSingle()
+ {
+ var expected = "000000E0FFFFEF47";
+ var ms = new MemoryStream();
+ var writer = new BsonWriter(ms, new BsonDocumentDescriptor());
+ var val = Single.MaxValue;
+
+ writer.WriteValue(BsonType.Number, val);
+
+ var hexdump = BitConverter.ToString(ms.ToArray());
+ hexdump = hexdump.Replace("-", "");
+ Assert.AreEqual(expected, hexdump);
+ }
+
+ [Test]
+ public void TestWriteString()
+ {
+ var ms = new MemoryStream();
+ var writer = new BsonWriter(ms, new BsonDocumentDescriptor());
+ const string expected = "54-65-73-74-73-2E-69-6E-73-65-72-74-73-00";
+ writer.Write("Tests.inserts", false);
+
+ var hexdump = BitConverter.ToString(ms.ToArray());
+
+ Assert.AreEqual(expected, hexdump);
+ }
+
+ [Test]
+ public void TestWriteSymbol()
+ {
+ var expected = "0700000073796D626F6C00";
+
+ var ms = new MemoryStream();
+ var writer = new BsonWriter(ms, new BsonDocumentDescriptor());
+ MongoSymbol val = "symbol";
+ Assert.IsTrue(String.IsInterned(val) != null);
+ writer.WriteValue(BsonType.Symbol, val);
+ var hexdump = BitConverter.ToString(ms.ToArray()).Replace("-", "");
+
+ Assert.AreEqual(expected, hexdump);
+ }
+
+ [Test]
+ public void TestWriteUtcTimeByDefault()
+ {
+ var dateTime = new DateTime(2010, 1, 1, 10, 0, 0, DateTimeKind.Utc);
+
+ var base64 = Serialize(new Document("time", dateTime));
+
+ Assert.AreEqual("EwAAAAl0aW1lAADJU+klAQAAAA==", base64);
+ }
+
+ [Test]
+ [ExpectedException(typeof(ArgumentException), UserMessage = "Shouldn't be able to write large document")]
+ public void TestWritingTooLargeDocument()
+ {
+ var ms = new MemoryStream();
+ var writer = new BsonWriter(ms, new BsonDocumentDescriptor());
+ var b = new Binary(new byte[BsonInfo.MaxDocumentSize]);
+ var big = new Document().Add("x", b);
+
+ writer.WriteObject(big);
+ }
+
+ [Test]
+ public void TestWriteBytesAsBinary()
+ {
+ var bson = Serialize(new Document("bytes", new byte[] {10, 12}));
+
+ Assert.AreEqual("FwAAAAVieXRlcwAGAAAAAgIAAAAKDAA=",bson);
+ }
+
+ [Test]
+ public void TestWriteTimeSpanAsLong()
+ {
+ var span = TimeSpan.FromSeconds(123456);
+
+ var bson = Serialize(new Document("span", span));
+
+ Assert.AreEqual("EwAAABJzcGFuAACggnEfAQAAAA==",bson);
+ }
+
+ [Test]
+ public void TestWriteUriAsString()
+ {
+ var uri = new Uri("http://www.microsoft.com");
+
+ var bson = Serialize(new Document("uri", uri));
+
+ Assert.AreEqual("KAAAAAJ1cmkAGgAAAGh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS8AAA==",bson);
+ }
+
+ [Test]
+ public void TestWriteMongoRegex()
+ {
+ var regex = new MongoRegex("expression",
+ MongoRegexOption.IgnoreCase | MongoRegexOption.IgnorePatternWhitespace | MongoRegexOption.Multiline);
+
+ var bson = Serialize(new Document("regex", regex));
+
+ Assert.AreEqual("GwAAAAtyZWdleABleHByZXNzaW9uAGltZwAA",bson);
+ }
+
+ [Test]
+ public void TestWriteNetRegex()
+ {
+ var regex = new Regex("expression", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+
+ var bson = Serialize(new Document("regex", regex));
+
+ Assert.AreEqual("GwAAAAtyZWdleABleHByZXNzaW9uAGltZwAA", bson);
+ }
+
+ [Test]
+ public void TestCanWriteNagativeDates()
+ {
+ var bson = Serialize(new Document("date", new DateTime(1960, 1, 1)));
+
+ Assert.AreEqual("EwAAAAlkYXRlAIBFaoO2////AA==",bson);
+ }
+ }
+}
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/Bson/TestRoundTrips.cs b/source/MongoDB.Tests/UnitTests/Bson/TestRoundTrips.cs
similarity index 90%
rename from MongoDB.Net-Tests/Bson/TestRoundTrips.cs
rename to source/MongoDB.Tests/UnitTests/Bson/TestRoundTrips.cs
index 3461271b..9226e437 100644
--- a/MongoDB.Net-Tests/Bson/TestRoundTrips.cs
+++ b/source/MongoDB.Tests/UnitTests/Bson/TestRoundTrips.cs
@@ -1,13 +1,11 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Text;
-
-using MongoDB.Driver.Bson;
-
-using NUnit.Framework;
-
-namespace MongoDB.Driver.Bson
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using MongoDB.Bson;
+using NUnit.Framework;
+
+namespace MongoDB.UnitTests.Bson
{
[TestFixture]
public class TestRoundTrips
@@ -31,12 +29,12 @@ public void TestMultibyteUnicode(){
[Test]
public void TestDBRef(){
- Document source = new Document();
- source.Append("x",1).Append("ref",new DBRef("refs","ref1"));
+ Document source = new Document();
+ source.Add("x", 1).Add("ref", new DBRef("refs", "ref1"));
- Document copy = WriteAndRead(source);
-
- Assert.IsTrue(copy.Contains("ref"));
+ Document copy = WriteAndRead(source);
+
+ Assert.IsTrue(copy.ContainsKey("ref"));
Assert.IsTrue(copy["ref"].GetType() == typeof(DBRef));
DBRef sref = (DBRef)source["ref"];
@@ -50,8 +48,8 @@ public void TestDBRef(){
public void TestDateLocal(){
DateTime now = DateTime.Now;
- Document source = new Document();
- source.Append("d",now);
+ Document source = new Document();
+ source.Add("d", now);
Document copy = WriteAndRead(source);
@@ -66,8 +64,8 @@ public void TestDateLocal(){
public void TestDateUTC(){
DateTime now = DateTime.UtcNow;
- Document source = new Document();
- source.Append("d",now);
+ Document source = new Document();
+ source.Add("d", now);
Document copy = WriteAndRead(source);
DateTime then = (DateTime)copy["d"];
@@ -81,7 +79,7 @@ public void TestGUID(){
Guid expected = Guid.NewGuid();
Document source = new Document();
- source.Append("uuid", expected);
+ source.Add("uuid", expected);
Guid read = (Guid)(WriteAndRead(source)["uuid"]);
@@ -147,14 +145,14 @@ public void TestEmptyArray(){
}
protected Document WriteAndRead(Document source){
- MemoryStream ms = new MemoryStream();
- BsonWriter writer = new BsonWriter(ms);
+ MemoryStream ms = new MemoryStream();
+ BsonWriter writer = new BsonWriter(ms, new BsonDocumentDescriptor());
- writer.Write(source);
+ writer.WriteObject(source);
writer.Flush();
ms.Seek(0, SeekOrigin.Begin);
- BsonReader reader = new BsonReader(ms);
+ BsonReader reader = new BsonReader(ms,new BsonDocumentBuilder());
return reader.Read();
}
}
diff --git a/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationBuilderTests.cs b/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationBuilderTests.cs
new file mode 100644
index 00000000..f0391bea
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationBuilderTests.cs
@@ -0,0 +1,46 @@
+using System;
+using MongoDB.Configuration;
+using NUnit.Framework;
+
+namespace MongoDB.UnitTests.Configuration
+{
+ [TestFixture]
+ public class MongoConfigurationBuilderTests
+ {
+ private class Person
+ {
+ public Guid Id { get; set; }
+
+ public int Age { get; set; }
+
+ public string Name { get; set; }
+ }
+
+ [Test]
+ public void Test()
+ {
+ var configure = new MongoConfigurationBuilder();
+
+ configure.ConnectionString(cs =>
+ {
+ cs.Pooled = true;
+ });
+
+ configure.Mapping(mapping =>
+ {
+ mapping.DefaultProfile(p =>
+ {
+ p.AliasesAreCamelCased();
+ p.CollectionNamesAreCamelCasedAndPlural();
+ });
+
+ mapping.Map(m =>
+ {
+ m.CollectionName("people");
+ m.Member(x => x.Age).Alias("age");
+ m.Member(x => x.Name).Alias("name").DefaultValue("something").Ignore();
+ });
+ });
+ }
+ }
+}
diff --git a/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationSectionTests.1.config b/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationSectionTests.1.config
new file mode 100644
index 00000000..e61fc3bb
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationSectionTests.1.config
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationSectionTests.2.config b/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationSectionTests.2.config
new file mode 100644
index 00000000..6de8c6b9
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationSectionTests.2.config
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationSectionTests.cs b/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationSectionTests.cs
new file mode 100644
index 00000000..fe0fe2ca
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationSectionTests.cs
@@ -0,0 +1,88 @@
+using System.Configuration;
+using System.IO;
+using System.Reflection;
+using System.Text;
+using MongoDB.Configuration;
+using NUnit.Framework;
+
+namespace MongoDB.UnitTests.Configuration
+{
+ [TestFixture]
+ public class MongoConfigurationSectionTests
+ {
+ private MongoConfigurationSection ReadFromFile(int index)
+ {
+ var name = string.Format("{0}.{1}.config", GetType().FullName, index);
+ var assembly = Assembly.GetExecutingAssembly();
+ var tmpFile = new FileInfo(Path.GetTempFileName());
+ try
+ {
+ using(var stream = assembly.GetManifestResourceStream(name))
+ using(var reader = new StreamReader(stream, Encoding.Default, false))
+ File.WriteAllText(tmpFile.FullName, reader.ReadToEnd(),Encoding.Default);
+
+ var map = new ExeConfigurationFileMap { ExeConfigFilename = tmpFile.FullName };
+ var exeConfiguration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
+ return exeConfiguration.GetSection(MongoConfigurationSection.DefaultSectionName) as MongoConfigurationSection;
+ }
+ finally
+ {
+ if(tmpFile.Exists)
+ tmpFile.Delete();
+ }
+ }
+
+ [Test]
+ public void CanReadFromTestsConfig()
+ {
+ var section = MongoConfigurationSection.GetSection();
+ Assert.IsNotNull(section);
+ Assert.AreEqual("Server=localhost:27017", section.Connections["default"].ConnectionString);
+ Assert.AreEqual("Server=localhost:27018", section.Connections["local21018"].ConnectionString);
+ }
+
+ [Test]
+ public void CanReadWithNonDefaultSectionName()
+ {
+ var section = MongoConfigurationSection.GetSection("mongoNonDefaultName");
+ Assert.IsNotNull(section);
+ Assert.AreEqual("Server=localhost:27018", section.Connections["local21018"].ConnectionString);
+ }
+
+ [Test]
+ public void CanCreateConfigurationFromSection()
+ {
+ var section = MongoConfigurationSection.GetSection();
+ var config = section.CreateConfiguration();
+ Assert.IsNotNull(config);
+ Assert.AreEqual("Server=localhost:27017", config.ConnectionString);
+ }
+
+ [Test]
+ public void CanUpdateConfigurationFromSection()
+ {
+ var section = ReadFromFile(1);
+ var config = new MongoConfiguration();
+ Assert.IsEmpty(config.ConnectionString);
+ section.UpdateConfiguration(config);
+ Assert.AreEqual("Server=localhost:27017", config.ConnectionString);
+ }
+
+ [Test]
+ public void CanReadLocalTimeFromConfig()
+ {
+ var section = ReadFromFile(2);
+ Assert.IsNotNull(section);
+ Assert.AreEqual(false,section.ReadLocalTime);
+ }
+
+ [Test]
+ public void CanUpdateConfigurationFromReadLocalTime()
+ {
+ var section = ReadFromFile(2);
+ Assert.IsNotNull(section);
+ var config = section.CreateConfiguration();
+ Assert.AreEqual(false, config.ReadLocalTime);
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationTests.cs b/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationTests.cs
new file mode 100644
index 00000000..eef4372a
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/Configuration/MongoConfigurationTests.cs
@@ -0,0 +1,61 @@
+using System;
+using MongoDB.Configuration;
+using NUnit.Framework;
+
+namespace MongoDB.UnitTests.Configuration
+{
+ [TestFixture]
+ public class MongoConfigurationTests
+ {
+ [Test]
+ public void IsModifiableByDefault()
+ {
+ var config = new MongoConfiguration();
+ Assert.IsTrue(config.IsModifiable);
+ }
+
+ [Test]
+ public void IsNotModifiableAfterValidate()
+ {
+ var config = new MongoConfiguration();
+ config.ValidateAndSeal();
+ Assert.IsFalse(config.IsModifiable);
+ }
+
+ [Test]
+ [ExpectedException(typeof(InvalidOperationException))]
+ public void CanNotChangeConnectionStringAfterValidate()
+ {
+ var config = new MongoConfiguration();
+ config.ValidateAndSeal();
+ config.ConnectionString = "";
+ }
+
+ [Test]
+ [ExpectedException(typeof(InvalidOperationException))]
+ public void CanNotChangeMappingStoreAfterValidate()
+ {
+ var config = new MongoConfiguration();
+ config.ValidateAndSeal();
+ config.MappingStore = null;
+ }
+
+ [Test]
+ [ExpectedException(typeof(InvalidOperationException))]
+ public void CanNotChangeReadLocalTimeAfterValidate()
+ {
+ var config = new MongoConfiguration();
+ config.ValidateAndSeal();
+ config.ReadLocalTime = true;
+ }
+
+ [Test]
+ [ExpectedException(typeof(InvalidOperationException))]
+ public void CanNotChangeSerializationFactoryAfterValidate()
+ {
+ var config = new MongoConfiguration();
+ config.ValidateAndSeal();
+ config.SerializationFactory = null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/MongoDB.Net-Tests/IO/TestMsgMessage.cs b/source/MongoDB.Tests/UnitTests/IO/TestMsgMessage.cs
similarity index 93%
rename from MongoDB.Net-Tests/IO/TestMsgMessage.cs
rename to source/MongoDB.Tests/UnitTests/IO/TestMsgMessage.cs
index ea2c755d..ce6c6740 100644
--- a/MongoDB.Net-Tests/IO/TestMsgMessage.cs
+++ b/source/MongoDB.Tests/UnitTests/IO/TestMsgMessage.cs
@@ -1,10 +1,9 @@
-
-using System;
+using System;
using System.IO;
-using MongoDB.Driver.Protocol;
-using NUnit.Framework;
-
-namespace MongoDB.Driver.IO
+using MongoDB.Protocol;
+using NUnit.Framework;
+
+namespace MongoDB.UnitTests.IO
{
[TestFixture()]
public class TestMsgMessage
diff --git a/source/MongoDB.Tests/UnitTests/IO/TestQueryMessage.cs b/source/MongoDB.Tests/UnitTests/IO/TestQueryMessage.cs
new file mode 100644
index 00000000..89407b50
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/IO/TestQueryMessage.cs
@@ -0,0 +1,54 @@
+using System;
+using System.IO;
+using MongoDB.Bson;
+using MongoDB.Protocol;
+using NUnit.Framework;
+
+namespace MongoDB.UnitTests.IO
+{
+ [TestFixture]
+ public class TestQueryMessage
+ {
+ [Test]
+ public void TestAllBytesWritten()
+ {
+ var query = new Document {{"col1", 1}};
+
+ var msg = new QueryMessage(new BsonWriterSettings(), query, "TestDB.TestCol");
+ var buffer = new MemoryStream();
+ msg.Write(buffer);
+
+ var output = buffer.ToArray();
+ var hexdump = BitConverter.ToString(output);
+ //Console.WriteLine("Dump: " + hexdump);
+
+ Assert.IsTrue(output.Length > 0);
+ Assert.AreEqual("3A-00-00-00-00-00-00-00-00-00-00-00-D4-07-00-00-00-00-00-00-54-65-73-74-44-42-2E-54-65-73-74-43-6F-6C-00-00-00-00-00-00-00-00-00-0F-00-00-00-10-63-6F-6C-31-00-01-00-00-00-00",
+ hexdump);
+ }
+
+ [Test]
+ public void TestWriteMessageTwice()
+ {
+ const string expectedHex = "3A-00-00-00-00-00-00-00-00-00-00-00-D4-07-00-00-00-00-00-00-54-65-73-74-44-42-2E-54-65-73-74-43-6F-6C-00-00-00-00-00-00-00-00-00-0F-00-00-00-10-63-6F-6C-31-00-01-00-00-00-00";
+ var query = new Document();
+ query.Add("col1", 1);
+
+ var msg = new QueryMessage(new BsonWriterSettings(), query, "TestDB.TestCol");
+ var buffer = new MemoryStream();
+ msg.Write(buffer);
+
+ var output = buffer.ToArray();
+ var hexdump = BitConverter.ToString(output);
+
+ var buffer2 = new MemoryStream();
+ msg.Write(buffer2);
+
+ var output2 = buffer.ToArray();
+ var hexdump2 = BitConverter.ToString(output2);
+
+ Assert.AreEqual(expectedHex, hexdump);
+ Assert.AreEqual(hexdump, hexdump2);
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/MongoDB.Tests/UnitTests/Serialization/Builders/DocumentPropertyTests.cs b/source/MongoDB.Tests/UnitTests/Serialization/Builders/DocumentPropertyTests.cs
new file mode 100644
index 00000000..f1f69df6
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/Serialization/Builders/DocumentPropertyTests.cs
@@ -0,0 +1,24 @@
+using NUnit.Framework;
+
+namespace MongoDB.UnitTests.Serialization.Builders
+{
+ [TestFixture]
+ public class DocumentPropertyTests : SerializationTestBase
+ {
+ public class DocumentProperty
+ {
+ public Document A { get; set; }
+ }
+
+ [Test]
+ public void CanDeserializeADocumentProperty()
+ {
+ //{ A: { B: "b" } }
+ const string bson = "FgAAAANBAA4AAAACQgACAAAAYgAAAA==";
+ var documentProperty = Deserialize(bson);
+ Assert.IsNotNull(documentProperty);
+ Assert.IsNotNull(documentProperty.A);
+ Assert.AreEqual("b", documentProperty.A["B"]);
+ }
+ }
+}
diff --git a/source/MongoDB.Tests/UnitTests/Serialization/Builders/EmbeddedClassPropertyTests.cs b/source/MongoDB.Tests/UnitTests/Serialization/Builders/EmbeddedClassPropertyTests.cs
new file mode 100644
index 00000000..5a140189
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/Serialization/Builders/EmbeddedClassPropertyTests.cs
@@ -0,0 +1,33 @@
+using NUnit.Framework;
+
+namespace MongoDB.UnitTests.Serialization.Builders
+{
+ [TestFixture]
+ public class EmbeddedClassPropertyTests : SerializationTestBase
+ {
+ public class SimpleObject
+ {
+ public string A { get; set; }
+ public string B { get; set; }
+ public SimpleObjectC C { get; set; }
+ }
+
+ public class SimpleObjectC
+ {
+ public string D { get; set; }
+ }
+
+ [Test]
+ public void CanDeserializeASimpleObject()
+ {
+ //{ A: "a", B: "b", C: { D: "d" } }
+ const string bson = "KAAAAAJBAAIAAABhAAJCAAIAAABiAANDAA4AAAACRAACAAAAZAAAAA==";
+ var simpleObject = Deserialize(bson);
+ Assert.IsNotNull(simpleObject);
+ Assert.AreEqual("a", simpleObject.A);
+ Assert.AreEqual("b", simpleObject.B);
+ Assert.IsNotNull(simpleObject.C);
+ Assert.AreEqual("d", simpleObject.C.D);
+ }
+ }
+}
diff --git a/source/MongoDB.Tests/UnitTests/Serialization/Builders/EnumerablePropertyTests.cs b/source/MongoDB.Tests/UnitTests/Serialization/Builders/EnumerablePropertyTests.cs
new file mode 100644
index 00000000..2d7aaf9d
--- /dev/null
+++ b/source/MongoDB.Tests/UnitTests/Serialization/Builders/EnumerablePropertyTests.cs
@@ -0,0 +1,68 @@
+using System.Collections;
+using System.Collections.Generic;
+using NUnit.Framework;
+
+namespace MongoDB.UnitTests.Serialization.Builders
+{
+ [TestFixture]
+ public class EnumerablePropertyTests : SerializationTestBase
+ {
+ public class Enumerable
+ {
+ public IEnumerable A { get; set; }
+ }
+
+ [Test]
+ public void CanDeserializeAnSimpleArrayAsIEnumerable()
+ {
+ //{ A: [1, 2] }
+ const string bson = "GwAAAARBABMAAAAQMAABAAAAEDEAAgAAAAAA";
+ var simpleArray = Deserialize(bson);
+ Assert.IsNotNull(simpleArray);
+ Assert.IsNotNull(simpleArray.A);
+ var list = new List