diff --git a/.gitignore b/.gitignore index e7e1652..dc4496d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,398 @@ -*ReSharper* -*resharper* +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser *.suo -*.cache -obj -bin -*.csproj.user -* Thumbs.db -*.cache -*.log *.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit *.gpState -TestResults -[Bb]inaries \ No newline at end of file + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml \ No newline at end of file diff --git a/.vs/EventSourcingCQRS/DesignTimeBuild/.dtbcache.v2 b/.vs/EventSourcingCQRS/DesignTimeBuild/.dtbcache.v2 new file mode 100644 index 0000000..53ef363 Binary files /dev/null and b/.vs/EventSourcingCQRS/DesignTimeBuild/.dtbcache.v2 differ diff --git a/.vs/EventSourcingCQRS/FileContentIndex/read.lock b/.vs/EventSourcingCQRS/FileContentIndex/read.lock new file mode 100644 index 0000000..e69de29 diff --git a/.vs/EventSourcingCQRS/v17/.futdcache.v2 b/.vs/EventSourcingCQRS/v17/.futdcache.v2 new file mode 100644 index 0000000..e211dd6 Binary files /dev/null and b/.vs/EventSourcingCQRS/v17/.futdcache.v2 differ diff --git a/.vs/EventSourcingCQRS/v17/.wsuo b/.vs/EventSourcingCQRS/v17/.wsuo new file mode 100644 index 0000000..34690fe Binary files /dev/null and b/.vs/EventSourcingCQRS/v17/.wsuo differ diff --git a/.vs/EventSourcingCQRS/v17/HierarchyCache.v1.txt b/.vs/EventSourcingCQRS/v17/HierarchyCache.v1.txt new file mode 100644 index 0000000..ec8e573 Binary files /dev/null and b/.vs/EventSourcingCQRS/v17/HierarchyCache.v1.txt differ diff --git a/.vs/EventSourcingCQRS/v17/workspaceFileList.bin b/.vs/EventSourcingCQRS/v17/workspaceFileList.bin new file mode 100644 index 0000000..58f6b80 Binary files /dev/null and b/.vs/EventSourcingCQRS/v17/workspaceFileList.bin differ diff --git a/.vs/ProjectEvaluation/eventsourcingcqrs.metadata.v5.2 b/.vs/ProjectEvaluation/eventsourcingcqrs.metadata.v5.2 new file mode 100644 index 0000000..083ae19 Binary files /dev/null and b/.vs/ProjectEvaluation/eventsourcingcqrs.metadata.v5.2 differ diff --git a/.vs/ProjectEvaluation/eventsourcingcqrs.projects.v5.1 b/.vs/ProjectEvaluation/eventsourcingcqrs.projects.v5.1 new file mode 100644 index 0000000..0c05f4a Binary files /dev/null and b/.vs/ProjectEvaluation/eventsourcingcqrs.projects.v5.1 differ diff --git a/.vs/ProjectEvaluation/eventsourcingcqrs.projects.v5.2 b/.vs/ProjectEvaluation/eventsourcingcqrs.projects.v5.2 new file mode 100644 index 0000000..d1bd809 Binary files /dev/null and b/.vs/ProjectEvaluation/eventsourcingcqrs.projects.v5.2 differ diff --git a/.vs/ProjectSettings.json b/.vs/ProjectSettings.json new file mode 100644 index 0000000..f8b4888 --- /dev/null +++ b/.vs/ProjectSettings.json @@ -0,0 +1,3 @@ +{ + "CurrentProjectSetting": null +} \ No newline at end of file diff --git a/.vs/VSWorkspaceState.json b/.vs/VSWorkspaceState.json new file mode 100644 index 0000000..3c7772e --- /dev/null +++ b/.vs/VSWorkspaceState.json @@ -0,0 +1,7 @@ +{ + "ExpandedNodes": [ + "" + ], + "SelectedNode": "\\SqlServerEventStore.sln", + "PreviewInSolutionExplorer": false +} \ No newline at end of file diff --git a/.vs/slnx.sqlite b/.vs/slnx.sqlite new file mode 100644 index 0000000..0199efb Binary files /dev/null and b/.vs/slnx.sqlite differ diff --git a/EventSourcingCQRS.sln b/EventSourcingCQRS.sln new file mode 100644 index 0000000..bb1c26c --- /dev/null +++ b/EventSourcingCQRS.sln @@ -0,0 +1,72 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.3.32825.248 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{EF3C709C-758C-451D-8B6C-4222D1BE8EDF}" + ProjectSection(SolutionItems) = preProject + PublishNuget.ps1 = PublishNuget.ps1 + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "EventStores", "EventStores", "{77CC485D-D260-45FC-A161-3DDF3A571C41}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventSourcingCQRS", "src\EventSourcingCQRS\EventSourcingCQRS.csproj", "{B3DE1DEF-D1B1-4F24-8C4B-776F6ED8A5BB}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventSourcingCQRS.EventStore.MongoDb", "src\EventSourcingCQRS.EventStore.MongoDb\EventSourcingCQRS.EventStore.MongoDb.csproj", "{B7131E9D-B08D-4C30-BE6B-A8AA5D7C597C}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventSourcingCQRS.EventStore.SqlServer", "src\EventSourcingCQRS.EventStore.SqlServer\EventSourcingCQRS.EventStore.SqlServer.csproj", "{BEEBFC8E-91EC-4E24-8223-395C2302C1B3}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventSourcingCQRS.EventStore.AzureTableStorage", "src\EventSourcingCQRS.EventStore.AzureTableStorage\EventSourcingCQRS.EventStore.AzureTableStorage.csproj", "{2F366796-98F0-482B-A5E2-080CF0C12E9D}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventSourcingCQRS.EventStore.CosmosDb", "src\EventSourcingCQRS.EventStore.CosmosDb\EventSourcingCQRS.EventStore.CosmosDb.csproj", "{BB2CDCB3-8F06-46B4-920A-681F9A6BC5B5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventSourcingCQRS.EventStore.CosmosDb.UnitTests", "src\EventSourcingCQRS.EventStore.CosmosDb.UnitTests\EventSourcingCQRS.EventStore.CosmosDb.UnitTests.csproj", "{A3F2842F-3188-474D-8553-9FDD53D31AA8}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B3DE1DEF-D1B1-4F24-8C4B-776F6ED8A5BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B3DE1DEF-D1B1-4F24-8C4B-776F6ED8A5BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B3DE1DEF-D1B1-4F24-8C4B-776F6ED8A5BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B3DE1DEF-D1B1-4F24-8C4B-776F6ED8A5BB}.Release|Any CPU.Build.0 = Release|Any CPU + {B7131E9D-B08D-4C30-BE6B-A8AA5D7C597C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B7131E9D-B08D-4C30-BE6B-A8AA5D7C597C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B7131E9D-B08D-4C30-BE6B-A8AA5D7C597C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B7131E9D-B08D-4C30-BE6B-A8AA5D7C597C}.Release|Any CPU.Build.0 = Release|Any CPU + {BEEBFC8E-91EC-4E24-8223-395C2302C1B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BEEBFC8E-91EC-4E24-8223-395C2302C1B3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BEEBFC8E-91EC-4E24-8223-395C2302C1B3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BEEBFC8E-91EC-4E24-8223-395C2302C1B3}.Release|Any CPU.Build.0 = Release|Any CPU + {2F366796-98F0-482B-A5E2-080CF0C12E9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2F366796-98F0-482B-A5E2-080CF0C12E9D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2F366796-98F0-482B-A5E2-080CF0C12E9D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2F366796-98F0-482B-A5E2-080CF0C12E9D}.Release|Any CPU.Build.0 = Release|Any CPU + {BB2CDCB3-8F06-46B4-920A-681F9A6BC5B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BB2CDCB3-8F06-46B4-920A-681F9A6BC5B5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BB2CDCB3-8F06-46B4-920A-681F9A6BC5B5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BB2CDCB3-8F06-46B4-920A-681F9A6BC5B5}.Release|Any CPU.Build.0 = Release|Any CPU + {A3F2842F-3188-474D-8553-9FDD53D31AA8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A3F2842F-3188-474D-8553-9FDD53D31AA8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A3F2842F-3188-474D-8553-9FDD53D31AA8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A3F2842F-3188-474D-8553-9FDD53D31AA8}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {B7131E9D-B08D-4C30-BE6B-A8AA5D7C597C} = {77CC485D-D260-45FC-A161-3DDF3A571C41} + {BEEBFC8E-91EC-4E24-8223-395C2302C1B3} = {77CC485D-D260-45FC-A161-3DDF3A571C41} + {2F366796-98F0-482B-A5E2-080CF0C12E9D} = {77CC485D-D260-45FC-A161-3DDF3A571C41} + {BB2CDCB3-8F06-46B4-920A-681F9A6BC5B5} = {77CC485D-D260-45FC-A161-3DDF3A571C41} + {A3F2842F-3188-474D-8553-9FDD53D31AA8} = {77CC485D-D260-45FC-A161-3DDF3A571C41} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {32C2010F-C26A-4E98-A269-71CB9EFEAE7A} + EndGlobalSection + GlobalSection(TestCaseManagementSettings) = postSolution + CategoryFile = Simple CQRS.vsmdi + EndGlobalSection +EndGlobal diff --git a/PublishNuget.ps1 b/PublishNuget.ps1 new file mode 100644 index 0000000..213e71a --- /dev/null +++ b/PublishNuget.ps1 @@ -0,0 +1,26 @@ +&dotnet build + +$folderPath = "C:\Repos\EventSourcingCQRS\src\EventSourcingCQRS\bin\Debug" +$latestFile = Get-ChildItem $folderPath | Sort-Object LastWriteTime -Descending | Select-Object -First 1 +Write-Host "The most recently changed file is: $($latestFile.Name)" +.\nuget.exe add ($latestFile.FullName) -source \\z8\NugetPackages + +$folderPath = "C:\Repos\EventSourcingCQRS\src\EventSourcingCQRS.EventStore.MongoDb\bin\Debug" +$latestFile = Get-ChildItem $folderPath | Sort-Object LastWriteTime -Descending | Select-Object -First 1 +Write-Host "The most recently changed file is: $($latestFile.Name)" +.\nuget.exe add ($latestFile.FullName) -source \\z8\NugetPackages + +$folderPath = "C:\Repos\EventSourcingCQRS\src\EventSourcingCQRS.EventStore.SqlServer\bin\Debug" +$latestFile = Get-ChildItem $folderPath | Sort-Object LastWriteTime -Descending | Select-Object -First 1 +Write-Host "The most recently changed file is: $($latestFile.Name)" +.\nuget.exe add ($latestFile.FullName) -source \\z8\NugetPackages + +$folderPath = "C:\Repos\EventSourcingCQRS\src\EventSourcingCQRS.EventStore.AzureTableStorage\bin\Debug" +$latestFile = Get-ChildItem $folderPath | Sort-Object LastWriteTime -Descending | Select-Object -First 1 +Write-Host "The most recently changed file is: $($latestFile.Name)" +.\nuget.exe add ($latestFile.FullName) -source \\z8\NugetPackages + +$folderPath = "C:\Repos\EventSourcingCQRS\src\EventSourcingCQRS.EventStore.CosmosDb\bin\Debug" +$latestFile = Get-ChildItem $folderPath | Sort-Object LastWriteTime -Descending | Select-Object -First 1 +Write-Host "The most recently changed file is: $($latestFile.Name)" +.\nuget.exe add ($latestFile.FullName) -source \\z8\NugetPackages/ \ No newline at end of file diff --git a/__PublishNuget.cmd b/__PublishNuget.cmd new file mode 100644 index 0000000..10b9f58 --- /dev/null +++ b/__PublishNuget.cmd @@ -0,0 +1 @@ +nuget add C:\Repos\EventSourcingCQRS\src\EventSourcingCQRS\bin\Debug\EventSourcingCQRS.Beta.2022.12.14.2249.nupkg -source \\z8\NugetPackages \ No newline at end of file diff --git a/lib/AutoMoq.dll b/lib/AutoMoq.dll deleted file mode 100644 index 7d292a8..0000000 Binary files a/lib/AutoMoq.dll and /dev/null differ diff --git a/lib/Machine.Specifications.dll b/lib/Machine.Specifications.dll deleted file mode 100644 index cb4436d..0000000 Binary files a/lib/Machine.Specifications.dll and /dev/null differ diff --git a/lib/Machine.Specifications.dll.VisualState.xml b/lib/Machine.Specifications.dll.VisualState.xml deleted file mode 100644 index 6e02ffb..0000000 --- a/lib/Machine.Specifications.dll.VisualState.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - [0-1000]C:\_Application\AGCEVENTREG\lib\Machine.Specifications\Machine.Specifications.dll - [0-1000]C:\_Application\AGCEVENTREG\lib\Machine.Specifications\Machine.Specifications.dll - false - - \ No newline at end of file diff --git a/lib/Microsoft.Practices.ServiceLocation.dll b/lib/Microsoft.Practices.ServiceLocation.dll deleted file mode 100644 index 3f88954..0000000 Binary files a/lib/Microsoft.Practices.ServiceLocation.dll and /dev/null differ diff --git a/lib/Microsoft.Practices.Unity.dll b/lib/Microsoft.Practices.Unity.dll deleted file mode 100644 index 84f1870..0000000 Binary files a/lib/Microsoft.Practices.Unity.dll and /dev/null differ diff --git a/lib/MongoDB.GridFS.dll b/lib/MongoDB.GridFS.dll deleted file mode 100644 index 24e24fa..0000000 Binary files a/lib/MongoDB.GridFS.dll and /dev/null differ diff --git a/lib/MongoDB.dll b/lib/MongoDB.dll deleted file mode 100644 index 23c4756..0000000 Binary files a/lib/MongoDB.dll and /dev/null differ diff --git a/lib/NServiceBus.Core.dll b/lib/NServiceBus.Core.dll deleted file mode 100644 index 2ce6532..0000000 Binary files a/lib/NServiceBus.Core.dll and /dev/null differ diff --git a/lib/NServiceBus.Host.exe b/lib/NServiceBus.Host.exe deleted file mode 100644 index e68a44d..0000000 Binary files a/lib/NServiceBus.Host.exe and /dev/null differ diff --git a/lib/NServiceBus.dll b/lib/NServiceBus.dll deleted file mode 100644 index b6c4fe0..0000000 Binary files a/lib/NServiceBus.dll and /dev/null differ diff --git a/lib/Rhino.ServiceBus.dll b/lib/Rhino.ServiceBus.dll deleted file mode 100644 index 1823f64..0000000 Binary files a/lib/Rhino.ServiceBus.dll and /dev/null differ diff --git a/lib/ServiceStack.Text.dll b/lib/ServiceStack.Text.dll deleted file mode 100644 index 13d0fd7..0000000 Binary files a/lib/ServiceStack.Text.dll and /dev/null differ diff --git a/lib/Should.dll b/lib/Should.dll deleted file mode 100644 index 2d9589e..0000000 Binary files a/lib/Should.dll and /dev/null differ diff --git a/lib/Simple.Data.Ado.dll b/lib/Simple.Data.Ado.dll deleted file mode 100644 index 10dc863..0000000 Binary files a/lib/Simple.Data.Ado.dll and /dev/null differ diff --git a/lib/Simple.Data.SqlServer.dll b/lib/Simple.Data.SqlServer.dll deleted file mode 100644 index 5120142..0000000 Binary files a/lib/Simple.Data.SqlServer.dll and /dev/null differ diff --git a/lib/Simple.Data.dll b/lib/Simple.Data.dll deleted file mode 100644 index 2f2ac4f..0000000 Binary files a/lib/Simple.Data.dll and /dev/null differ diff --git a/lib/TechTalk.SpecFlow.dll b/lib/TechTalk.SpecFlow.dll deleted file mode 100644 index ddf53af..0000000 Binary files a/lib/TechTalk.SpecFlow.dll and /dev/null differ diff --git a/lib/log4net.dll b/lib/log4net.dll deleted file mode 100644 index ffc57e1..0000000 Binary files a/lib/log4net.dll and /dev/null differ diff --git a/lib/nunit.framework.dll b/lib/nunit.framework.dll deleted file mode 100644 index 96e31f9..0000000 Binary files a/lib/nunit.framework.dll and /dev/null differ diff --git a/nuget.exe b/nuget.exe new file mode 100644 index 0000000..212f26c Binary files /dev/null and b/nuget.exe differ diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Commands/CreateCustomerCommand.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Commands/CreateCustomerCommand.cs deleted file mode 100644 index 9ca4bd1..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Commands/CreateCustomerCommand.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using SimpleCqrs.Commanding; - -namespace Sample.JesseHouse.Commands -{ - [Serializable] - public class CreateCustomerCommand : ICommand - { - public Guid CustomerId { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - } -} \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Commands/Properties/AssemblyInfo.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Commands/Properties/AssemblyInfo.cs deleted file mode 100644 index 1435f62..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Commands/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("Sample.JesseHouse.Commands")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("Sample.JesseHouse.Commands")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[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("b1df9d80-6827-4545-9bf0-fc51f5a72c95")] - -// 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/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Commands/Sample.JesseHouse.Commands.csproj b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Commands/Sample.JesseHouse.Commands.csproj deleted file mode 100644 index cf65471..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Commands/Sample.JesseHouse.Commands.csproj +++ /dev/null @@ -1,53 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {A5BB06A5-78F4-4F61-91D4-ADED1A4670F1} - Library - Properties - Sample.JesseHouse.Commands - Sample.JesseHouse.Commands - v4.0 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\lib\SimpleCqrs.dll - - - - - - - - - - - - \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Domain/Customer.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Domain/Customer.cs deleted file mode 100644 index 121991b..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Domain/Customer.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using Sample.JesseHouse.Events; -using SimpleCqrs.Domain; - -namespace Sample.JesseHouse.Domain -{ - public class Customer : AggregateRoot - { - public Customer(Guid customerId) - { - Apply(new CustomerHasBeenCreatedEvent{CustomerId = customerId}); - } - - public void SetName(string firstName, string lastName) - { - Apply(new CustomerNameHasChangedEvent{FirstName = firstName, LastName = lastName}); - } - - protected void OnCustomerHasBeenCreated(CustomerHasBeenCreatedEvent domainEvent) - { - Id = domainEvent.CustomerId; - } - } -} \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Domain/Properties/AssemblyInfo.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Domain/Properties/AssemblyInfo.cs deleted file mode 100644 index fda63e4..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Domain/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("Sample.JesseHouse.Domain")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("Sample.JesseHouse.Domain")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[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("aad92fd9-208c-4e04-9f47-03b5a266b0b4")] - -// 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/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Domain/Sample.JesseHouse.Domain.csproj b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Domain/Sample.JesseHouse.Domain.csproj deleted file mode 100644 index 2ab1177..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Domain/Sample.JesseHouse.Domain.csproj +++ /dev/null @@ -1,59 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {C28D8A9E-EE20-4E73-9BD9-6227DADDBA76} - Library - Properties - Sample.JesseHouse.Domain - Sample.JesseHouse.Domain - v4.0 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\lib\SimpleCqrs.dll - - - - - - - - - - - - {FB617064-BEF2-4DD8-BF12-B1B4589F2FE2} - Sample.JesseHouse.Events - - - - - \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Events/CustomerHasBeenCreatedEvent.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Events/CustomerHasBeenCreatedEvent.cs deleted file mode 100644 index 3cf4661..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Events/CustomerHasBeenCreatedEvent.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using SimpleCqrs.Eventing; - -namespace Sample.JesseHouse.Events -{ - [Serializable] - public class CustomerHasBeenCreatedEvent : DomainEvent - { - public Guid CustomerId - { - get { return AggregateRootId; } - set { AggregateRootId = value; } - } - } -} \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Events/CustomerNameHasChangedEvent.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Events/CustomerNameHasChangedEvent.cs deleted file mode 100644 index d5d47a8..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Events/CustomerNameHasChangedEvent.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using SimpleCqrs.Eventing; - -namespace Sample.JesseHouse.Events -{ - [Serializable] - public class CustomerNameHasChangedEvent : DomainEvent - { - public Guid CustomerId - { - get { return AggregateRootId; } - set { AggregateRootId = value; } - } - - public string FirstName { get; set; } - public string LastName { get; set; } - } -} \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Events/Properties/AssemblyInfo.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Events/Properties/AssemblyInfo.cs deleted file mode 100644 index 4ece735..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Events/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("Sample.JesseHouse.Events")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("Sample.JesseHouse.Events")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[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("3aa220f3-415e-49ee-bd10-c8ec651786a8")] - -// 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/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Events/Sample.JesseHouse.Events.csproj b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Events/Sample.JesseHouse.Events.csproj deleted file mode 100644 index 8259468..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Events/Sample.JesseHouse.Events.csproj +++ /dev/null @@ -1,54 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {FB617064-BEF2-4DD8-BF12-B1B4589F2FE2} - Library - Properties - Sample.JesseHouse.Events - Sample.JesseHouse.Events - v4.0 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\lib\SimpleCqrs.dll - - - - - - - - - - - - - \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/App.config b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/App.config deleted file mode 100644 index a49eddd..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/App.config +++ /dev/null @@ -1,15 +0,0 @@ - - - -
-
- - - - - diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/CreateCustomerCommandHandler.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/CreateCustomerCommandHandler.cs deleted file mode 100644 index de53956..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/CreateCustomerCommandHandler.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Sample.JesseHouse.Commands; -using Sample.JesseHouse.Domain; -using SimpleCqrs.Commanding; -using SimpleCqrs.Domain; - -namespace Sample.JesseHouse.Processing -{ - public class CreateCustomerCommandHandler : CommandHandler - { - private readonly IDomainRepository domainRepository; - - public CreateCustomerCommandHandler(IDomainRepository domainRepository) - { - this.domainRepository = domainRepository; - } - - public override void Handle(CreateCustomerCommand command) - { - var customer = new Customer(command.CustomerId); - customer.SetName(command.FirstName, command.LastName); - - domainRepository.Save(customer); - } - } -} \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/EndpointConfiguration.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/EndpointConfiguration.cs deleted file mode 100644 index 89e41df..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/EndpointConfiguration.cs +++ /dev/null @@ -1,22 +0,0 @@ -using NServiceBus; -using SimpleCqrs; -using SimpleCqrs.NServiceBus; -using SimpleCqrs.Unity; - -namespace Sample.JesseHouse.Processing -{ - public class EndpointConfiguration : IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization - { - public void Init() - { - Configure.With() - .DefaultBuilder() - .BinarySerializer() - .SimpleCqrs(new SimpleCqrsRuntime()) - .UseLocalCommandBus() // Tell SimpleCqrs to dispatch command locally (in this application) - .UseNsbEventBus(); // Tell SimpleCqrs to use NServiceBus to publish domain events - - // TODO: Go to Sample.JesseHouse.ViewModel project's EndpointConfiguration class - } - } -} \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/Properties/AssemblyInfo.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/Properties/AssemblyInfo.cs deleted file mode 100644 index 10ab039..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/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("Sample.JesseHouse.Processing")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("Sample.JesseHouse.Processing")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[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("b1ede741-8067-4f73-be7a-3ba45b740a5e")] - -// 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/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/Sample.JesseHouse.Processing.csproj b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/Sample.JesseHouse.Processing.csproj deleted file mode 100644 index a724b47..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.Processing/Sample.JesseHouse.Processing.csproj +++ /dev/null @@ -1,101 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {D230A023-FAA1-4858-ACC9-86F800A6EFB7} - Library - Properties - Sample.JesseHouse.Processing - Sample.JesseHouse.Processing - v4.0 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\lib\log4net.dll - - - False - ..\lib\Microsoft.Practices.ServiceLocation.dll - - - False - ..\lib\Microsoft.Practices.Unity.dll - - - ..\lib\NServiceBus.dll - - - ..\lib\NServiceBus.Core.dll - - - ..\lib\NServiceBus.Host.exe - - - ..\lib\SimpleCqrs.dll - - - ..\lib\SimpleCqrs.NServiceBus.dll - - - ..\lib\SimpleCqrs.Unity.dll - - - - - - - - - - - - - - - - - - - - {C28D8A9E-EE20-4E73-9BD9-6227DADDBA76} - Sample.JesseHouse.Domain - - - {FB617064-BEF2-4DD8-BF12-B1B4589F2FE2} - Sample.JesseHouse.Events - - - {A5BB06A5-78F4-4F61-91D4-ADED1A4670F1} - Sample.JesseHouse.Commands - - - - - \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/App.config b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/App.config deleted file mode 100644 index ecb4c44..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/App.config +++ /dev/null @@ -1,24 +0,0 @@ - - - - -
-
-
- - - - - - - - - - - - - \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/CustomerDenormalizer.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/CustomerDenormalizer.cs deleted file mode 100644 index b467477..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/CustomerDenormalizer.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using Sample.JesseHouse.Events; -using SimpleCqrs.Eventing; - -namespace Sample.JesseHouse.ViewModel -{ - public class CustomerDenormalizer : - IHandleDomainEvents, - IHandleDomainEvents - { - public void Handle(CustomerHasBeenCreatedEvent domainEvent) - { - Console.WriteLine("New customer created with ID: {0}", domainEvent.CustomerId); - } - - public void Handle(CustomerNameHasChangedEvent domainEvent) - { - Console.WriteLine("Customer with ID: {0} name has changed. New name is {1} {2}", domainEvent.CustomerId, domainEvent.FirstName, domainEvent.LastName); - } - } -} \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/EndpointConfiguration.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/EndpointConfiguration.cs deleted file mode 100644 index b9b9103..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/EndpointConfiguration.cs +++ /dev/null @@ -1,22 +0,0 @@ -using NServiceBus; -using SimpleCqrs; -using SimpleCqrs.NServiceBus; -using SimpleCqrs.Unity; - -namespace Sample.JesseHouse.ViewModel -{ - public class EndpointConfiguration : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization - { - public void Init() - { - Configure.With() - .DefaultBuilder() - .BinarySerializer() - .SimpleCqrs(new SimpleCqrsRuntime()) - .SubscribeForDomainEvents(); // Tells SimpleCqrs to subscribe for domain events - - // The DomainEventBusConfig element in the Web.config tell SimpleCqrs which domain events to listen for and the queue - // to listen for them from. - } - } -} \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/Properties/AssemblyInfo.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/Properties/AssemblyInfo.cs deleted file mode 100644 index 3c929e3..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/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("Sample.JesseHouse.ViewModel")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("Sample.JesseHouse.ViewModel")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[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("bb29a61d-433c-4be4-93a8-74cb5a2bb45b")] - -// 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/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/Sample.JesseHouse.ViewModel.csproj b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/Sample.JesseHouse.ViewModel.csproj deleted file mode 100644 index 2811745..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.ViewModel/Sample.JesseHouse.ViewModel.csproj +++ /dev/null @@ -1,78 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {8DCAB6CE-680D-4BCB-B17F-8AE1487F1AE0} - Library - Properties - Sample.JesseHouse.ViewModel - Sample.JesseHouse.ViewModel - v4.0 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\lib\log4net.dll - - - ..\lib\NServiceBus.Core.dll - - - ..\lib\NServiceBus.Host.exe - - - ..\lib\SimpleCqrs.dll - - - ..\lib\SimpleCqrs.NServiceBus.dll - - - ..\lib\SimpleCqrs.Unity.dll - - - - - - - - - - - - - - - - {FB617064-BEF2-4DD8-BF12-B1B4589F2FE2} - Sample.JesseHouse.Events - - - - - \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.sln b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.sln deleted file mode 100644 index 2a1e056..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse.sln +++ /dev/null @@ -1,50 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.JesseHouse.Web", "Sample.JesseHouse\Sample.JesseHouse.Web.csproj", "{CEECD0F3-51E3-494D-8F69-3307638D5BCA}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.JesseHouse.Commands", "Sample.JesseHouse.Commands\Sample.JesseHouse.Commands.csproj", "{A5BB06A5-78F4-4F61-91D4-ADED1A4670F1}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.JesseHouse.Processing", "Sample.JesseHouse.Processing\Sample.JesseHouse.Processing.csproj", "{D230A023-FAA1-4858-ACC9-86F800A6EFB7}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.JesseHouse.Events", "Sample.JesseHouse.Events\Sample.JesseHouse.Events.csproj", "{FB617064-BEF2-4DD8-BF12-B1B4589F2FE2}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.JesseHouse.ViewModel", "Sample.JesseHouse.ViewModel\Sample.JesseHouse.ViewModel.csproj", "{8DCAB6CE-680D-4BCB-B17F-8AE1487F1AE0}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.JesseHouse.Domain", "Sample.JesseHouse.Domain\Sample.JesseHouse.Domain.csproj", "{C28D8A9E-EE20-4E73-9BD9-6227DADDBA76}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {CEECD0F3-51E3-494D-8F69-3307638D5BCA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CEECD0F3-51E3-494D-8F69-3307638D5BCA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CEECD0F3-51E3-494D-8F69-3307638D5BCA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CEECD0F3-51E3-494D-8F69-3307638D5BCA}.Release|Any CPU.Build.0 = Release|Any CPU - {A5BB06A5-78F4-4F61-91D4-ADED1A4670F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A5BB06A5-78F4-4F61-91D4-ADED1A4670F1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A5BB06A5-78F4-4F61-91D4-ADED1A4670F1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A5BB06A5-78F4-4F61-91D4-ADED1A4670F1}.Release|Any CPU.Build.0 = Release|Any CPU - {D230A023-FAA1-4858-ACC9-86F800A6EFB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D230A023-FAA1-4858-ACC9-86F800A6EFB7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D230A023-FAA1-4858-ACC9-86F800A6EFB7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D230A023-FAA1-4858-ACC9-86F800A6EFB7}.Release|Any CPU.Build.0 = Release|Any CPU - {FB617064-BEF2-4DD8-BF12-B1B4589F2FE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FB617064-BEF2-4DD8-BF12-B1B4589F2FE2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FB617064-BEF2-4DD8-BF12-B1B4589F2FE2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FB617064-BEF2-4DD8-BF12-B1B4589F2FE2}.Release|Any CPU.Build.0 = Release|Any CPU - {8DCAB6CE-680D-4BCB-B17F-8AE1487F1AE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8DCAB6CE-680D-4BCB-B17F-8AE1487F1AE0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8DCAB6CE-680D-4BCB-B17F-8AE1487F1AE0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8DCAB6CE-680D-4BCB-B17F-8AE1487F1AE0}.Release|Any CPU.Build.0 = Release|Any CPU - {C28D8A9E-EE20-4E73-9BD9-6227DADDBA76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C28D8A9E-EE20-4E73-9BD9-6227DADDBA76}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C28D8A9E-EE20-4E73-9BD9-6227DADDBA76}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C28D8A9E-EE20-4E73-9BD9-6227DADDBA76}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/App_Data/Sample.JesseHouse.sdf b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/App_Data/Sample.JesseHouse.sdf deleted file mode 100644 index 1012a08..0000000 Binary files a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/App_Data/Sample.JesseHouse.sdf and /dev/null differ diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Content/Site.css b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Content/Site.css deleted file mode 100644 index 6f3f7ee..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Content/Site.css +++ /dev/null @@ -1,344 +0,0 @@ -/*---------------------------------------------------------- -The base color for this template is #5c87b2. If you'd like -to use a different color start by replacing all instances of -#5c87b2 with your new color. -----------------------------------------------------------*/ -body -{ - background-color: #5c87b2; - font-size: .75em; - font-family: Verdana, Helvetica, Sans-Serif; - margin: 0; - padding: 0; - color: #696969; -} - -a:link -{ - color: #034af3; - text-decoration: underline; -} -a:visited -{ - color: #505abc; -} -a:hover -{ - color: #1d60ff; - text-decoration: none; -} -a:active -{ - color: #12eb87; -} - -p, ul -{ - margin-bottom: 20px; - line-height: 1.6em; -} - -/* HEADINGS -----------------------------------------------------------*/ -h1, h2, h3, h4, h5, h6 -{ - font-size: 1.5em; - color: #000; - font-family: Arial, Helvetica, sans-serif; -} - -h1 -{ - font-size: 2em; - padding-bottom: 0; - margin-bottom: 0; -} -h2 -{ - padding: 0 0 10px 0; -} -h3 -{ - font-size: 1.2em; -} -h4 -{ - font-size: 1.1em; -} -h5, h6 -{ - font-size: 1em; -} - -/* this rule styles

tags that are the -first child of the left and right table columns */ -.rightColumn > h1, .rightColumn > h2, .leftColumn > h1, .leftColumn > h2 -{ - margin-top: 0; -} - -/* PRIMARY LAYOUT ELEMENTS -----------------------------------------------------------*/ - -/* you can specify a greater or lesser percentage for the -page width. Or, you can specify an exact pixel width. */ -.page -{ - width: 90%; - margin-left: auto; - margin-right: auto; -} - -#header -{ - position: relative; - margin-bottom: 0px; - color: #000; - padding: 0; -} - -#header h1 -{ - font-weight: bold; - padding: 5px 0; - margin: 0; - color: #fff; - border: none; - line-height: 2em; - font-family: Arial, Helvetica, sans-serif; - font-size: 32px !important; -} - -#main -{ - padding: 30px 30px 15px 30px; - background-color: #fff; - margin-bottom: 30px; - _height: 1px; /* only IE6 applies CSS properties starting with an underscore */ -} - -#footer -{ - color: #999; - padding: 10px 0; - text-align: center; - line-height: normal; - margin: 0; - font-size: .9em; -} - -/* TAB MENU -----------------------------------------------------------*/ -ul#menu -{ - border-bottom: 1px #5C87B2 solid; - padding: 0 0 2px; - position: relative; - margin: 0; - text-align: right; -} - -ul#menu li -{ - display: inline; - list-style: none; -} - -ul#menu li#greeting -{ - padding: 10px 20px; - font-weight: bold; - text-decoration: none; - line-height: 2.8em; - color: #fff; -} - -ul#menu li a -{ - padding: 10px 20px; - font-weight: bold; - text-decoration: none; - line-height: 2.8em; - background-color: #e8eef4; - color: #034af3; -} - -ul#menu li a:hover -{ - background-color: #fff; - text-decoration: none; -} - -ul#menu li a:active -{ - background-color: #a6e2a6; - text-decoration: none; -} - -ul#menu li.selected a -{ - background-color: #fff; - color: #000; -} - -/* FORM LAYOUT ELEMENTS -----------------------------------------------------------*/ - -fieldset -{ - margin: 1em 0; - padding: 1em; - border: 1px solid #CCC; -} - -fieldset p -{ - margin: 2px 12px 10px 10px; -} - -legend -{ - font-size: 1.1em; - font-weight: 600; - padding: 2px 4px 8px 4px; -} - -input[type="text"] -{ - width: 200px; - border: 1px solid #CCC; -} - -input[type="password"] -{ - width: 200px; - border: 1px solid #CCC; -} - -/* TABLE -----------------------------------------------------------*/ - -table -{ - border: solid 1px #e8eef4; - border-collapse: collapse; -} - -table td -{ - padding: 5px; - border: solid 1px #e8eef4; -} - -table th -{ - padding: 6px 5px; - text-align: left; - background-color: #e8eef4; - border: solid 1px #e8eef4; -} - -/* MISC -----------------------------------------------------------*/ -.clear -{ - clear: both; -} - -.error -{ - color:Red; -} - -#menucontainer -{ - margin-top:40px; -} - -div#title -{ - display:block; - float:left; - text-align:left; -} - -#logindisplay -{ - font-size:1.1em; - display:block; - text-align:right; - margin:10px; - color:White; -} - -#logindisplay a:link -{ - color: white; - text-decoration: underline; -} - -#logindisplay a:visited -{ - color: white; - text-decoration: underline; -} - -#logindisplay a:hover -{ - color: white; - text-decoration: none; -} - -/* Styles for validation helpers ------------------------------------------------------------*/ -.field-validation-error -{ - color: #ff0000; -} - -.field-validation-valid -{ - display: none; -} - -.input-validation-error -{ - border: 1px solid #ff0000; - background-color: #ffeeee; -} - -.validation-summary-errors -{ - font-weight: bold; - color: #ff0000; -} - -.validation-summary-valid -{ - display: none; -} - -/* Styles for editor and display helpers -----------------------------------------------------------*/ -.display-label, -.editor-label, -.display-field, -.editor-field -{ - margin: 0.5em 0; -} - -.text-box -{ - width: 30em; -} - -.text-box.multi-line -{ - height: 6.5em; -} - -.tri-state -{ - width: 6em; -} diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Controllers/CustomerController.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Controllers/CustomerController.cs deleted file mode 100644 index 29b69e5..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Controllers/CustomerController.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Web.Mvc; -using Sample.JesseHouse.Commands; -using Sample.JesseHouse.Models; -using SimpleCqrs.Commanding; - -namespace Sample.JesseHouse.Controllers -{ - public class CustomerController : Controller - { - private readonly ICommandBus commandBus; - - public CustomerController() - { - // Again I would use MvcTurbine and have ICommandBus injected into this constructor, - // but for now just resolve out of the service locator - commandBus = MvcApplication.Runtime.ServiceLocator.Resolve(); - } - - public ActionResult Index() - { - return View(); - } - - [HttpPost] - public ActionResult Index(CustomerInputModel customerInputModel) - { - // Normal stuff here, create a command and send it on the command bus - // TODO: Go to the Sample.JesseHouse.Processing project's EndpointConfiguration class next - var createCustomerCommand = new CreateCustomerCommand(); - createCustomerCommand.CustomerId = Guid.NewGuid(); - createCustomerCommand.FirstName = customerInputModel.FirstName; - createCustomerCommand.LastName = customerInputModel.LastName; - - commandBus.Send(createCustomerCommand); - - return RedirectToAction("Index"); - } - } -} \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Global.asax b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Global.asax deleted file mode 100644 index a685dee..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Global.asax +++ /dev/null @@ -1 +0,0 @@ -<%@ Application Codebehind="Global.asax.cs" Inherits="Sample.JesseHouse.MvcApplication" Language="C#" %> diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Global.asax.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Global.asax.cs deleted file mode 100644 index fa511dd..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Global.asax.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; -using NServiceBus; -using SimpleCqrs; -using SimpleCqrs.NServiceBus; -using SimpleCqrs.Unity; - -namespace Sample.JesseHouse -{ - public class MvcApplication : HttpApplication - { - public static SimpleCqrsRuntime Runtime; - - public static void RegisterRoutes(RouteCollection routes) - { - routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); - - routes.MapRoute( - "Default", // Route name - "{controller}/{action}/{id}", // URL with parameters - new {controller = "Customer", action = "Index", id = UrlParameter.Optional} // Parameter defaults - ); - } - - protected void Application_Start() - { - AreaRegistration.RegisterAllAreas(); - - RegisterRoutes(RouteTable.Routes); - - Runtime = new SimpleCqrsRuntime(); - - Configure.WithWeb() - .DefaultBuilder() - .BinarySerializer() // Must use binary serializer for types that are not known to NServiceBus (domain events, command bus) - .SimpleCqrs(Runtime) - .UseNsbCommandBus() // Tells SimpleCqrs to create a NsbCommandBus instance, which sends commands over NServiceBus - .MsmqTransport() - .UnicastBus() - .CreateBus() - .Start(); - - // The command bus is created for you. (Its an instance of NsbCommandBus) - // The CommandBusConfig in the Web.config tells the NsbCommandBus where to send the commands, - // the Commands element is a type name or an assembly name and the Endpoint element specifies where to send the type or types in the assembly - // you can get it out of the service locator using the line below - // I use MvcTurbine for website, so I would register the command bus in the MvcTurbine's - // service locator - - // var commandBus = Runtime.ServiceLocator.Resolve(); - - // TODO : Go to CustomerController next - } - } -} \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Models/CustomerInputModel.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Models/CustomerInputModel.cs deleted file mode 100644 index 917a915..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Models/CustomerInputModel.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Sample.JesseHouse.Models -{ - public class CustomerInputModel - { - public string FirstName { get; set; } - public string LastName { get; set; } - } -} \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Properties/AssemblyInfo.cs b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Properties/AssemblyInfo.cs deleted file mode 100644 index cea218b..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +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("Sample.JesseHouse")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("Sample.JesseHouse")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[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("c8ba83c1-bea7-40a3-bfa9-a337e3320ec8")] - -// 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 Revision and Build Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Sample.JesseHouse.Web.csproj b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Sample.JesseHouse.Web.csproj deleted file mode 100644 index 1532e67..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Sample.JesseHouse.Web.csproj +++ /dev/null @@ -1,173 +0,0 @@ - - - - Debug - AnyCPU - - - 2.0 - {CEECD0F3-51E3-494D-8F69-3307638D5BCA} - {F85E285D-A4E0-4152-9332-AB1D724D3325};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - Sample.JesseHouse - Sample.JesseHouse - v4.0 - false - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - - - - ..\lib\log4net.dll - - - - False - ..\lib\Microsoft.Practices.ServiceLocation.dll - - - False - ..\lib\Microsoft.Practices.Unity.dll - - - ..\lib\NServiceBus.dll - - - ..\lib\NServiceBus.Core.dll - - - ..\lib\SimpleCqrs.dll - - - ..\lib\SimpleCqrs.NServiceBus.dll - - - ..\lib\SimpleCqrs.Unity.dll - - - - - - - - - - - - - 3.5 - - - 3.5 - - - 3.5 - - - - 3.5 - - - - 3.5 - - - - - - - - - - - - Global.asax - - - - - - - Always - - - - - - Web.config - - - Web.config - - - - - - - - - - - - - - - - - - - - - - - - - {A5BB06A5-78F4-4F61-91D4-ADED1A4670F1} - Sample.JesseHouse.Commands - - - - - - - - - - - - - False - True - 49738 - / - - - False - False - - - False - - - - - \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftAjax.debug.js b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftAjax.debug.js deleted file mode 100644 index 51d7b06..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftAjax.debug.js +++ /dev/null @@ -1,7117 +0,0 @@ -// Name: MicrosoftAjax.debug.js -// Assembly: System.Web.Extensions -// Version: 4.0.0.0 -// FileVersion: 4.0.20526.0 -//----------------------------------------------------------------------- -// Copyright (C) Microsoft Corporation. All rights reserved. -//----------------------------------------------------------------------- -// MicrosoftAjax.js -// Microsoft AJAX Framework. - -Function.__typeName = 'Function'; -Function.__class = true; -Function.createCallback = function Function$createCallback(method, context) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "method", type: Function}, - {name: "context", mayBeNull: true} - ]); - if (e) throw e; - return function() { - var l = arguments.length; - if (l > 0) { - var args = []; - for (var i = 0; i < l; i++) { - args[i] = arguments[i]; - } - args[l] = context; - return method.apply(this, args); - } - return method.call(this, context); - } -} -Function.createDelegate = function Function$createDelegate(instance, method) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "instance", mayBeNull: true}, - {name: "method", type: Function} - ]); - if (e) throw e; - return function() { - return method.apply(instance, arguments); - } -} -Function.emptyFunction = Function.emptyMethod = function Function$emptyMethod() { - /// -} -Function.validateParameters = function Function$validateParameters(parameters, expectedParameters, validateParameterCount) { - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "parameters"}, - {name: "expectedParameters"}, - {name: "validateParameterCount", type: Boolean, optional: true} - ]); - if (e) throw e; - return Function._validateParams(parameters, expectedParameters, validateParameterCount); -} -Function._validateParams = function Function$_validateParams(params, expectedParams, validateParameterCount) { - var e, expectedLength = expectedParams.length; - validateParameterCount = validateParameterCount || (typeof(validateParameterCount) === "undefined"); - e = Function._validateParameterCount(params, expectedParams, validateParameterCount); - if (e) { - e.popStackFrame(); - return e; - } - for (var i = 0, l = params.length; i < l; i++) { - var expectedParam = expectedParams[Math.min(i, expectedLength - 1)], - paramName = expectedParam.name; - if (expectedParam.parameterArray) { - paramName += "[" + (i - expectedLength + 1) + "]"; - } - else if (!validateParameterCount && (i >= expectedLength)) { - break; - } - e = Function._validateParameter(params[i], expectedParam, paramName); - if (e) { - e.popStackFrame(); - return e; - } - } - return null; -} -Function._validateParameterCount = function Function$_validateParameterCount(params, expectedParams, validateParameterCount) { - var i, error, - expectedLen = expectedParams.length, - actualLen = params.length; - if (actualLen < expectedLen) { - var minParams = expectedLen; - for (i = 0; i < expectedLen; i++) { - var param = expectedParams[i]; - if (param.optional || param.parameterArray) { - minParams--; - } - } - if (actualLen < minParams) { - error = true; - } - } - else if (validateParameterCount && (actualLen > expectedLen)) { - error = true; - for (i = 0; i < expectedLen; i++) { - if (expectedParams[i].parameterArray) { - error = false; - break; - } - } - } - if (error) { - var e = Error.parameterCount(); - e.popStackFrame(); - return e; - } - return null; -} -Function._validateParameter = function Function$_validateParameter(param, expectedParam, paramName) { - var e, - expectedType = expectedParam.type, - expectedInteger = !!expectedParam.integer, - expectedDomElement = !!expectedParam.domElement, - mayBeNull = !!expectedParam.mayBeNull; - e = Function._validateParameterType(param, expectedType, expectedInteger, expectedDomElement, mayBeNull, paramName); - if (e) { - e.popStackFrame(); - return e; - } - var expectedElementType = expectedParam.elementType, - elementMayBeNull = !!expectedParam.elementMayBeNull; - if (expectedType === Array && typeof(param) !== "undefined" && param !== null && - (expectedElementType || !elementMayBeNull)) { - var expectedElementInteger = !!expectedParam.elementInteger, - expectedElementDomElement = !!expectedParam.elementDomElement; - for (var i=0; i < param.length; i++) { - var elem = param[i]; - e = Function._validateParameterType(elem, expectedElementType, - expectedElementInteger, expectedElementDomElement, elementMayBeNull, - paramName + "[" + i + "]"); - if (e) { - e.popStackFrame(); - return e; - } - } - } - return null; -} -Function._validateParameterType = function Function$_validateParameterType(param, expectedType, expectedInteger, expectedDomElement, mayBeNull, paramName) { - var e, i; - if (typeof(param) === "undefined") { - if (mayBeNull) { - return null; - } - else { - e = Error.argumentUndefined(paramName); - e.popStackFrame(); - return e; - } - } - if (param === null) { - if (mayBeNull) { - return null; - } - else { - e = Error.argumentNull(paramName); - e.popStackFrame(); - return e; - } - } - if (expectedType && expectedType.__enum) { - if (typeof(param) !== 'number') { - e = Error.argumentType(paramName, Object.getType(param), expectedType); - e.popStackFrame(); - return e; - } - if ((param % 1) === 0) { - var values = expectedType.prototype; - if (!expectedType.__flags || (param === 0)) { - for (i in values) { - if (values[i] === param) return null; - } - } - else { - var v = param; - for (i in values) { - var vali = values[i]; - if (vali === 0) continue; - if ((vali & param) === vali) { - v -= vali; - } - if (v === 0) return null; - } - } - } - e = Error.argumentOutOfRange(paramName, param, String.format(Sys.Res.enumInvalidValue, param, expectedType.getName())); - e.popStackFrame(); - return e; - } - if (expectedDomElement && (!Sys._isDomElement(param) || (param.nodeType === 3))) { - e = Error.argument(paramName, Sys.Res.argumentDomElement); - e.popStackFrame(); - return e; - } - if (expectedType && !Sys._isInstanceOfType(expectedType, param)) { - e = Error.argumentType(paramName, Object.getType(param), expectedType); - e.popStackFrame(); - return e; - } - if (expectedType === Number && expectedInteger) { - if ((param % 1) !== 0) { - e = Error.argumentOutOfRange(paramName, param, Sys.Res.argumentInteger); - e.popStackFrame(); - return e; - } - } - return null; -} - -Error.__typeName = 'Error'; -Error.__class = true; -Error.create = function Error$create(message, errorInfo) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "message", type: String, mayBeNull: true, optional: true}, - {name: "errorInfo", mayBeNull: true, optional: true} - ]); - if (e) throw e; - var err = new Error(message); - err.message = message; - if (errorInfo) { - for (var v in errorInfo) { - err[v] = errorInfo[v]; - } - } - err.popStackFrame(); - return err; -} -Error.argument = function Error$argument(paramName, message) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "paramName", type: String, mayBeNull: true, optional: true}, - {name: "message", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - var displayMessage = "Sys.ArgumentException: " + (message ? message : Sys.Res.argument); - if (paramName) { - displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); - } - var err = Error.create(displayMessage, { name: "Sys.ArgumentException", paramName: paramName }); - err.popStackFrame(); - return err; -} -Error.argumentNull = function Error$argumentNull(paramName, message) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "paramName", type: String, mayBeNull: true, optional: true}, - {name: "message", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - var displayMessage = "Sys.ArgumentNullException: " + (message ? message : Sys.Res.argumentNull); - if (paramName) { - displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); - } - var err = Error.create(displayMessage, { name: "Sys.ArgumentNullException", paramName: paramName }); - err.popStackFrame(); - return err; -} -Error.argumentOutOfRange = function Error$argumentOutOfRange(paramName, actualValue, message) { - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "paramName", type: String, mayBeNull: true, optional: true}, - {name: "actualValue", mayBeNull: true, optional: true}, - {name: "message", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - var displayMessage = "Sys.ArgumentOutOfRangeException: " + (message ? message : Sys.Res.argumentOutOfRange); - if (paramName) { - displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); - } - if (typeof(actualValue) !== "undefined" && actualValue !== null) { - displayMessage += "\n" + String.format(Sys.Res.actualValue, actualValue); - } - var err = Error.create(displayMessage, { - name: "Sys.ArgumentOutOfRangeException", - paramName: paramName, - actualValue: actualValue - }); - err.popStackFrame(); - return err; -} -Error.argumentType = function Error$argumentType(paramName, actualType, expectedType, message) { - /// - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "paramName", type: String, mayBeNull: true, optional: true}, - {name: "actualType", type: Type, mayBeNull: true, optional: true}, - {name: "expectedType", type: Type, mayBeNull: true, optional: true}, - {name: "message", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - var displayMessage = "Sys.ArgumentTypeException: "; - if (message) { - displayMessage += message; - } - else if (actualType && expectedType) { - displayMessage += - String.format(Sys.Res.argumentTypeWithTypes, actualType.getName(), expectedType.getName()); - } - else { - displayMessage += Sys.Res.argumentType; - } - if (paramName) { - displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); - } - var err = Error.create(displayMessage, { - name: "Sys.ArgumentTypeException", - paramName: paramName, - actualType: actualType, - expectedType: expectedType - }); - err.popStackFrame(); - return err; -} -Error.argumentUndefined = function Error$argumentUndefined(paramName, message) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "paramName", type: String, mayBeNull: true, optional: true}, - {name: "message", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - var displayMessage = "Sys.ArgumentUndefinedException: " + (message ? message : Sys.Res.argumentUndefined); - if (paramName) { - displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); - } - var err = Error.create(displayMessage, { name: "Sys.ArgumentUndefinedException", paramName: paramName }); - err.popStackFrame(); - return err; -} -Error.format = function Error$format(message) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "message", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - var displayMessage = "Sys.FormatException: " + (message ? message : Sys.Res.format); - var err = Error.create(displayMessage, {name: 'Sys.FormatException'}); - err.popStackFrame(); - return err; -} -Error.invalidOperation = function Error$invalidOperation(message) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "message", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - var displayMessage = "Sys.InvalidOperationException: " + (message ? message : Sys.Res.invalidOperation); - var err = Error.create(displayMessage, {name: 'Sys.InvalidOperationException'}); - err.popStackFrame(); - return err; -} -Error.notImplemented = function Error$notImplemented(message) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "message", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - var displayMessage = "Sys.NotImplementedException: " + (message ? message : Sys.Res.notImplemented); - var err = Error.create(displayMessage, {name: 'Sys.NotImplementedException'}); - err.popStackFrame(); - return err; -} -Error.parameterCount = function Error$parameterCount(message) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "message", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - var displayMessage = "Sys.ParameterCountException: " + (message ? message : Sys.Res.parameterCount); - var err = Error.create(displayMessage, {name: 'Sys.ParameterCountException'}); - err.popStackFrame(); - return err; -} -Error.prototype.popStackFrame = function Error$popStackFrame() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (typeof(this.stack) === "undefined" || this.stack === null || - typeof(this.fileName) === "undefined" || this.fileName === null || - typeof(this.lineNumber) === "undefined" || this.lineNumber === null) { - return; - } - var stackFrames = this.stack.split("\n"); - var currentFrame = stackFrames[0]; - var pattern = this.fileName + ":" + this.lineNumber; - while(typeof(currentFrame) !== "undefined" && - currentFrame !== null && - currentFrame.indexOf(pattern) === -1) { - stackFrames.shift(); - currentFrame = stackFrames[0]; - } - var nextFrame = stackFrames[1]; - if (typeof(nextFrame) === "undefined" || nextFrame === null) { - return; - } - var nextFrameParts = nextFrame.match(/@(.*):(\d+)$/); - if (typeof(nextFrameParts) === "undefined" || nextFrameParts === null) { - return; - } - this.fileName = nextFrameParts[1]; - this.lineNumber = parseInt(nextFrameParts[2]); - stackFrames.shift(); - this.stack = stackFrames.join("\n"); -} - -Object.__typeName = 'Object'; -Object.__class = true; -Object.getType = function Object$getType(instance) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "instance"} - ]); - if (e) throw e; - var ctor = instance.constructor; - if (!ctor || (typeof(ctor) !== "function") || !ctor.__typeName || (ctor.__typeName === 'Object')) { - return Object; - } - return ctor; -} -Object.getTypeName = function Object$getTypeName(instance) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "instance"} - ]); - if (e) throw e; - return Object.getType(instance).getName(); -} - -String.__typeName = 'String'; -String.__class = true; -String.prototype.endsWith = function String$endsWith(suffix) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "suffix", type: String} - ]); - if (e) throw e; - return (this.substr(this.length - suffix.length) === suffix); -} -String.prototype.startsWith = function String$startsWith(prefix) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "prefix", type: String} - ]); - if (e) throw e; - return (this.substr(0, prefix.length) === prefix); -} -String.prototype.trim = function String$trim() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this.replace(/^\s+|\s+$/g, ''); -} -String.prototype.trimEnd = function String$trimEnd() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this.replace(/\s+$/, ''); -} -String.prototype.trimStart = function String$trimStart() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this.replace(/^\s+/, ''); -} -String.format = function String$format(format, args) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "format", type: String}, - {name: "args", mayBeNull: true, parameterArray: true} - ]); - if (e) throw e; - return String._toFormattedString(false, arguments); -} -String._toFormattedString = function String$_toFormattedString(useLocale, args) { - var result = ''; - var format = args[0]; - for (var i=0;;) { - var open = format.indexOf('{', i); - var close = format.indexOf('}', i); - if ((open < 0) && (close < 0)) { - result += format.slice(i); - break; - } - if ((close > 0) && ((close < open) || (open < 0))) { - if (format.charAt(close + 1) !== '}') { - throw Error.argument('format', Sys.Res.stringFormatBraceMismatch); - } - result += format.slice(i, close + 1); - i = close + 2; - continue; - } - result += format.slice(i, open); - i = open + 1; - if (format.charAt(i) === '{') { - result += '{'; - i++; - continue; - } - if (close < 0) throw Error.argument('format', Sys.Res.stringFormatBraceMismatch); - var brace = format.substring(i, close); - var colonIndex = brace.indexOf(':'); - var argNumber = parseInt((colonIndex < 0)? brace : brace.substring(0, colonIndex), 10) + 1; - if (isNaN(argNumber)) throw Error.argument('format', Sys.Res.stringFormatInvalid); - var argFormat = (colonIndex < 0)? '' : brace.substring(colonIndex + 1); - var arg = args[argNumber]; - if (typeof(arg) === "undefined" || arg === null) { - arg = ''; - } - if (arg.toFormattedString) { - result += arg.toFormattedString(argFormat); - } - else if (useLocale && arg.localeFormat) { - result += arg.localeFormat(argFormat); - } - else if (arg.format) { - result += arg.format(argFormat); - } - else - result += arg.toString(); - i = close + 1; - } - return result; -} - -Boolean.__typeName = 'Boolean'; -Boolean.__class = true; -Boolean.parse = function Boolean$parse(value) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "value", type: String} - ], false); - if (e) throw e; - var v = value.trim().toLowerCase(); - if (v === 'false') return false; - if (v === 'true') return true; - throw Error.argumentOutOfRange('value', value, Sys.Res.boolTrueOrFalse); -} - -Date.__typeName = 'Date'; -Date.__class = true; - -Number.__typeName = 'Number'; -Number.__class = true; - -RegExp.__typeName = 'RegExp'; -RegExp.__class = true; - -if (!window) this.window = this; -window.Type = Function; -Type.__fullyQualifiedIdentifierRegExp = new RegExp("^[^.0-9 \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]([^ \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]*[^. \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\])?$", "i"); -Type.__identifierRegExp = new RegExp("^[^.0-9 \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\][^. \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]*$", "i"); -Type.prototype.callBaseMethod = function Type$callBaseMethod(instance, name, baseArguments) { - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "instance"}, - {name: "name", type: String}, - {name: "baseArguments", type: Array, mayBeNull: true, optional: true, elementMayBeNull: true} - ]); - if (e) throw e; - var baseMethod = Sys._getBaseMethod(this, instance, name); - if (!baseMethod) throw Error.invalidOperation(String.format(Sys.Res.methodNotFound, name)); - if (!baseArguments) { - return baseMethod.apply(instance); - } - else { - return baseMethod.apply(instance, baseArguments); - } -} -Type.prototype.getBaseMethod = function Type$getBaseMethod(instance, name) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "instance"}, - {name: "name", type: String} - ]); - if (e) throw e; - return Sys._getBaseMethod(this, instance, name); -} -Type.prototype.getBaseType = function Type$getBaseType() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return (typeof(this.__baseType) === "undefined") ? null : this.__baseType; -} -Type.prototype.getInterfaces = function Type$getInterfaces() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - var result = []; - var type = this; - while(type) { - var interfaces = type.__interfaces; - if (interfaces) { - for (var i = 0, l = interfaces.length; i < l; i++) { - var interfaceType = interfaces[i]; - if (!Array.contains(result, interfaceType)) { - result[result.length] = interfaceType; - } - } - } - type = type.__baseType; - } - return result; -} -Type.prototype.getName = function Type$getName() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return (typeof(this.__typeName) === "undefined") ? "" : this.__typeName; -} -Type.prototype.implementsInterface = function Type$implementsInterface(interfaceType) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "interfaceType", type: Type} - ]); - if (e) throw e; - this.resolveInheritance(); - var interfaceName = interfaceType.getName(); - var cache = this.__interfaceCache; - if (cache) { - var cacheEntry = cache[interfaceName]; - if (typeof(cacheEntry) !== 'undefined') return cacheEntry; - } - else { - cache = this.__interfaceCache = {}; - } - var baseType = this; - while (baseType) { - var interfaces = baseType.__interfaces; - if (interfaces) { - if (Array.indexOf(interfaces, interfaceType) !== -1) { - return cache[interfaceName] = true; - } - } - baseType = baseType.__baseType; - } - return cache[interfaceName] = false; -} -Type.prototype.inheritsFrom = function Type$inheritsFrom(parentType) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "parentType", type: Type} - ]); - if (e) throw e; - this.resolveInheritance(); - var baseType = this.__baseType; - while (baseType) { - if (baseType === parentType) { - return true; - } - baseType = baseType.__baseType; - } - return false; -} -Type.prototype.initializeBase = function Type$initializeBase(instance, baseArguments) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "instance"}, - {name: "baseArguments", type: Array, mayBeNull: true, optional: true, elementMayBeNull: true} - ]); - if (e) throw e; - if (!Sys._isInstanceOfType(this, instance)) throw Error.argumentType('instance', Object.getType(instance), this); - this.resolveInheritance(); - if (this.__baseType) { - if (!baseArguments) { - this.__baseType.apply(instance); - } - else { - this.__baseType.apply(instance, baseArguments); - } - } - return instance; -} -Type.prototype.isImplementedBy = function Type$isImplementedBy(instance) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "instance", mayBeNull: true} - ]); - if (e) throw e; - if (typeof(instance) === "undefined" || instance === null) return false; - var instanceType = Object.getType(instance); - return !!(instanceType.implementsInterface && instanceType.implementsInterface(this)); -} -Type.prototype.isInstanceOfType = function Type$isInstanceOfType(instance) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "instance", mayBeNull: true} - ]); - if (e) throw e; - return Sys._isInstanceOfType(this, instance); -} -Type.prototype.registerClass = function Type$registerClass(typeName, baseType, interfaceTypes) { - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "typeName", type: String}, - {name: "baseType", type: Type, mayBeNull: true, optional: true}, - {name: "interfaceTypes", type: Type, parameterArray: true} - ]); - if (e) throw e; - if (!Type.__fullyQualifiedIdentifierRegExp.test(typeName)) throw Error.argument('typeName', Sys.Res.notATypeName); - var parsedName; - try { - parsedName = eval(typeName); - } - catch(e) { - throw Error.argument('typeName', Sys.Res.argumentTypeName); - } - if (parsedName !== this) throw Error.argument('typeName', Sys.Res.badTypeName); - if (Sys.__registeredTypes[typeName]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, typeName)); - if ((arguments.length > 1) && (typeof(baseType) === 'undefined')) throw Error.argumentUndefined('baseType'); - if (baseType && !baseType.__class) throw Error.argument('baseType', Sys.Res.baseNotAClass); - this.prototype.constructor = this; - this.__typeName = typeName; - this.__class = true; - if (baseType) { - this.__baseType = baseType; - this.__basePrototypePending = true; - } - Sys.__upperCaseTypes[typeName.toUpperCase()] = this; - if (interfaceTypes) { - this.__interfaces = []; - this.resolveInheritance(); - for (var i = 2, l = arguments.length; i < l; i++) { - var interfaceType = arguments[i]; - if (!interfaceType.__interface) throw Error.argument('interfaceTypes[' + (i - 2) + ']', Sys.Res.notAnInterface); - for (var methodName in interfaceType.prototype) { - var method = interfaceType.prototype[methodName]; - if (!this.prototype[methodName]) { - this.prototype[methodName] = method; - } - } - this.__interfaces.push(interfaceType); - } - } - Sys.__registeredTypes[typeName] = true; - return this; -} -Type.prototype.registerInterface = function Type$registerInterface(typeName) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "typeName", type: String} - ]); - if (e) throw e; - if (!Type.__fullyQualifiedIdentifierRegExp.test(typeName)) throw Error.argument('typeName', Sys.Res.notATypeName); - var parsedName; - try { - parsedName = eval(typeName); - } - catch(e) { - throw Error.argument('typeName', Sys.Res.argumentTypeName); - } - if (parsedName !== this) throw Error.argument('typeName', Sys.Res.badTypeName); - if (Sys.__registeredTypes[typeName]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, typeName)); - Sys.__upperCaseTypes[typeName.toUpperCase()] = this; - this.prototype.constructor = this; - this.__typeName = typeName; - this.__interface = true; - Sys.__registeredTypes[typeName] = true; - return this; -} -Type.prototype.resolveInheritance = function Type$resolveInheritance() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (this.__basePrototypePending) { - var baseType = this.__baseType; - baseType.resolveInheritance(); - for (var memberName in baseType.prototype) { - var memberValue = baseType.prototype[memberName]; - if (!this.prototype[memberName]) { - this.prototype[memberName] = memberValue; - } - } - delete this.__basePrototypePending; - } -} -Type.getRootNamespaces = function Type$getRootNamespaces() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return Array.clone(Sys.__rootNamespaces); -} -Type.isClass = function Type$isClass(type) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "type", mayBeNull: true} - ]); - if (e) throw e; - if ((typeof(type) === 'undefined') || (type === null)) return false; - return !!type.__class; -} -Type.isInterface = function Type$isInterface(type) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "type", mayBeNull: true} - ]); - if (e) throw e; - if ((typeof(type) === 'undefined') || (type === null)) return false; - return !!type.__interface; -} -Type.isNamespace = function Type$isNamespace(object) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "object", mayBeNull: true} - ]); - if (e) throw e; - if ((typeof(object) === 'undefined') || (object === null)) return false; - return !!object.__namespace; -} -Type.parse = function Type$parse(typeName, ns) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "typeName", type: String, mayBeNull: true}, - {name: "ns", mayBeNull: true, optional: true} - ]); - if (e) throw e; - var fn; - if (ns) { - fn = Sys.__upperCaseTypes[ns.getName().toUpperCase() + '.' + typeName.toUpperCase()]; - return fn || null; - } - if (!typeName) return null; - if (!Type.__htClasses) { - Type.__htClasses = {}; - } - fn = Type.__htClasses[typeName]; - if (!fn) { - fn = eval(typeName); - if (typeof(fn) !== 'function') throw Error.argument('typeName', Sys.Res.notATypeName); - Type.__htClasses[typeName] = fn; - } - return fn; -} -Type.registerNamespace = function Type$registerNamespace(namespacePath) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "namespacePath", type: String} - ]); - if (e) throw e; - Type._registerNamespace(namespacePath); -} -Type._registerNamespace = function Type$_registerNamespace(namespacePath) { - if (!Type.__fullyQualifiedIdentifierRegExp.test(namespacePath)) throw Error.argument('namespacePath', Sys.Res.invalidNameSpace); - var rootObject = window; - var namespaceParts = namespacePath.split('.'); - for (var i = 0; i < namespaceParts.length; i++) { - var currentPart = namespaceParts[i]; - var ns = rootObject[currentPart]; - var nsType = typeof(ns); - if ((nsType !== "undefined") && (ns !== null)) { - if (nsType === "function") { - throw Error.invalidOperation(String.format(Sys.Res.namespaceContainsClass, namespaceParts.splice(0, i + 1).join('.'))); - } - if ((typeof(ns) !== "object") || (ns instanceof Array)) { - throw Error.invalidOperation(String.format(Sys.Res.namespaceContainsNonObject, namespaceParts.splice(0, i + 1).join('.'))); - } - } - if (!ns) { - ns = rootObject[currentPart] = {}; - } - if (!ns.__namespace) { - if ((i === 0) && (namespacePath !== "Sys")) { - Sys.__rootNamespaces[Sys.__rootNamespaces.length] = ns; - } - ns.__namespace = true; - ns.__typeName = namespaceParts.slice(0, i + 1).join('.'); - var parsedName; - try { - parsedName = eval(ns.__typeName); - } - catch(e) { - parsedName = null; - } - if (parsedName !== ns) { - delete rootObject[currentPart]; - throw Error.argument('namespacePath', Sys.Res.invalidNameSpace); - } - ns.getName = function ns$getName() {return this.__typeName;} - } - rootObject = ns; - } -} -Type._checkDependency = function Type$_checkDependency(dependency, featureName) { - var scripts = Type._registerScript._scripts, isDependent = (scripts ? (!!scripts[dependency]) : false); - if ((typeof(featureName) !== 'undefined') && !isDependent) { - throw Error.invalidOperation(String.format(Sys.Res.requiredScriptReferenceNotIncluded, - featureName, dependency)); - } - return isDependent; -} -Type._registerScript = function Type$_registerScript(scriptName, dependencies) { - var scripts = Type._registerScript._scripts; - if (!scripts) { - Type._registerScript._scripts = scripts = {}; - } - if (scripts[scriptName]) { - throw Error.invalidOperation(String.format(Sys.Res.scriptAlreadyLoaded, scriptName)); - } - scripts[scriptName] = true; - if (dependencies) { - for (var i = 0, l = dependencies.length; i < l; i++) { - var dependency = dependencies[i]; - if (!Type._checkDependency(dependency)) { - throw Error.invalidOperation(String.format(Sys.Res.scriptDependencyNotFound, scriptName, dependency)); - } - } - } -} -Type._registerNamespace("Sys"); -Sys.__upperCaseTypes = {}; -Sys.__rootNamespaces = [Sys]; -Sys.__registeredTypes = {}; -Sys._isInstanceOfType = function Sys$_isInstanceOfType(type, instance) { - if (typeof(instance) === "undefined" || instance === null) return false; - if (instance instanceof type) return true; - var instanceType = Object.getType(instance); - return !!(instanceType === type) || - (instanceType.inheritsFrom && instanceType.inheritsFrom(type)) || - (instanceType.implementsInterface && instanceType.implementsInterface(type)); -} -Sys._getBaseMethod = function Sys$_getBaseMethod(type, instance, name) { - if (!Sys._isInstanceOfType(type, instance)) throw Error.argumentType('instance', Object.getType(instance), type); - var baseType = type.getBaseType(); - if (baseType) { - var baseMethod = baseType.prototype[name]; - return (baseMethod instanceof Function) ? baseMethod : null; - } - return null; -} -Sys._isDomElement = function Sys$_isDomElement(obj) { - var val = false; - if (typeof (obj.nodeType) !== 'number') { - var doc = obj.ownerDocument || obj.document || obj; - if (doc != obj) { - var w = doc.defaultView || doc.parentWindow; - val = (w != obj); - } - else { - val = (typeof (doc.body) === 'undefined'); - } - } - return !val; -} - -Array.__typeName = 'Array'; -Array.__class = true; -Array.add = Array.enqueue = function Array$enqueue(array, item) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "array", type: Array, elementMayBeNull: true}, - {name: "item", mayBeNull: true} - ]); - if (e) throw e; - array[array.length] = item; -} -Array.addRange = function Array$addRange(array, items) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "array", type: Array, elementMayBeNull: true}, - {name: "items", type: Array, elementMayBeNull: true} - ]); - if (e) throw e; - array.push.apply(array, items); -} -Array.clear = function Array$clear(array) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "array", type: Array, elementMayBeNull: true} - ]); - if (e) throw e; - array.length = 0; -} -Array.clone = function Array$clone(array) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "array", type: Array, elementMayBeNull: true} - ]); - if (e) throw e; - if (array.length === 1) { - return [array[0]]; - } - else { - return Array.apply(null, array); - } -} -Array.contains = function Array$contains(array, item) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "array", type: Array, elementMayBeNull: true}, - {name: "item", mayBeNull: true} - ]); - if (e) throw e; - return (Sys._indexOf(array, item) >= 0); -} -Array.dequeue = function Array$dequeue(array) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "array", type: Array, elementMayBeNull: true} - ]); - if (e) throw e; - return array.shift(); -} -Array.forEach = function Array$forEach(array, method, instance) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "array", type: Array, elementMayBeNull: true}, - {name: "method", type: Function}, - {name: "instance", mayBeNull: true, optional: true} - ]); - if (e) throw e; - for (var i = 0, l = array.length; i < l; i++) { - var elt = array[i]; - if (typeof(elt) !== 'undefined') method.call(instance, elt, i, array); - } -} -Array.indexOf = function Array$indexOf(array, item, start) { - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "array", type: Array, elementMayBeNull: true}, - {name: "item", mayBeNull: true, optional: true}, - {name: "start", mayBeNull: true, optional: true} - ]); - if (e) throw e; - return Sys._indexOf(array, item, start); -} -Array.insert = function Array$insert(array, index, item) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "array", type: Array, elementMayBeNull: true}, - {name: "index", mayBeNull: true}, - {name: "item", mayBeNull: true} - ]); - if (e) throw e; - array.splice(index, 0, item); -} -Array.parse = function Array$parse(value) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "value", type: String, mayBeNull: true} - ]); - if (e) throw e; - if (!value) return []; - var v = eval(value); - if (!Array.isInstanceOfType(v)) throw Error.argument('value', Sys.Res.arrayParseBadFormat); - return v; -} -Array.remove = function Array$remove(array, item) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "array", type: Array, elementMayBeNull: true}, - {name: "item", mayBeNull: true} - ]); - if (e) throw e; - var index = Sys._indexOf(array, item); - if (index >= 0) { - array.splice(index, 1); - } - return (index >= 0); -} -Array.removeAt = function Array$removeAt(array, index) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "array", type: Array, elementMayBeNull: true}, - {name: "index", mayBeNull: true} - ]); - if (e) throw e; - array.splice(index, 1); -} -Sys._indexOf = function Sys$_indexOf(array, item, start) { - if (typeof(item) === "undefined") return -1; - var length = array.length; - if (length !== 0) { - start = start - 0; - if (isNaN(start)) { - start = 0; - } - else { - if (isFinite(start)) { - start = start - (start % 1); - } - if (start < 0) { - start = Math.max(0, length + start); - } - } - for (var i = start; i < length; i++) { - if ((typeof(array[i]) !== "undefined") && (array[i] === item)) { - return i; - } - } - } - return -1; -} -Type._registerScript._scripts = { - "MicrosoftAjaxCore.js": true, - "MicrosoftAjaxGlobalization.js": true, - "MicrosoftAjaxSerialization.js": true, - "MicrosoftAjaxComponentModel.js": true, - "MicrosoftAjaxHistory.js": true, - "MicrosoftAjaxNetwork.js" : true, - "MicrosoftAjaxWebServices.js": true }; - -Sys.IDisposable = function Sys$IDisposable() { - throw Error.notImplemented(); -} - function Sys$IDisposable$dispose() { - throw Error.notImplemented(); - } -Sys.IDisposable.prototype = { - dispose: Sys$IDisposable$dispose -} -Sys.IDisposable.registerInterface('Sys.IDisposable'); - -Sys.StringBuilder = function Sys$StringBuilder(initialText) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "initialText", mayBeNull: true, optional: true} - ]); - if (e) throw e; - this._parts = (typeof(initialText) !== 'undefined' && initialText !== null && initialText !== '') ? - [initialText.toString()] : []; - this._value = {}; - this._len = 0; -} - function Sys$StringBuilder$append(text) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "text", mayBeNull: true} - ]); - if (e) throw e; - this._parts[this._parts.length] = text; - } - function Sys$StringBuilder$appendLine(text) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "text", mayBeNull: true, optional: true} - ]); - if (e) throw e; - this._parts[this._parts.length] = - ((typeof(text) === 'undefined') || (text === null) || (text === '')) ? - '\r\n' : text + '\r\n'; - } - function Sys$StringBuilder$clear() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - this._parts = []; - this._value = {}; - this._len = 0; - } - function Sys$StringBuilder$isEmpty() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (this._parts.length === 0) return true; - return this.toString() === ''; - } - function Sys$StringBuilder$toString(separator) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "separator", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - separator = separator || ''; - var parts = this._parts; - if (this._len !== parts.length) { - this._value = {}; - this._len = parts.length; - } - var val = this._value; - if (typeof(val[separator]) === 'undefined') { - if (separator !== '') { - for (var i = 0; i < parts.length;) { - if ((typeof(parts[i]) === 'undefined') || (parts[i] === '') || (parts[i] === null)) { - parts.splice(i, 1); - } - else { - i++; - } - } - } - val[separator] = this._parts.join(separator); - } - return val[separator]; - } -Sys.StringBuilder.prototype = { - append: Sys$StringBuilder$append, - appendLine: Sys$StringBuilder$appendLine, - clear: Sys$StringBuilder$clear, - isEmpty: Sys$StringBuilder$isEmpty, - toString: Sys$StringBuilder$toString -} -Sys.StringBuilder.registerClass('Sys.StringBuilder'); - -Sys.Browser = {}; -Sys.Browser.InternetExplorer = {}; -Sys.Browser.Firefox = {}; -Sys.Browser.Safari = {}; -Sys.Browser.Opera = {}; -Sys.Browser.agent = null; -Sys.Browser.hasDebuggerStatement = false; -Sys.Browser.name = navigator.appName; -Sys.Browser.version = parseFloat(navigator.appVersion); -Sys.Browser.documentMode = 0; -if (navigator.userAgent.indexOf(' MSIE ') > -1) { - Sys.Browser.agent = Sys.Browser.InternetExplorer; - Sys.Browser.version = parseFloat(navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1]); - if (Sys.Browser.version >= 8) { - if (document.documentMode >= 7) { - Sys.Browser.documentMode = document.documentMode; - } - } - Sys.Browser.hasDebuggerStatement = true; -} -else if (navigator.userAgent.indexOf(' Firefox/') > -1) { - Sys.Browser.agent = Sys.Browser.Firefox; - Sys.Browser.version = parseFloat(navigator.userAgent.match(/ Firefox\/(\d+\.\d+)/)[1]); - Sys.Browser.name = 'Firefox'; - Sys.Browser.hasDebuggerStatement = true; -} -else if (navigator.userAgent.indexOf(' AppleWebKit/') > -1) { - Sys.Browser.agent = Sys.Browser.Safari; - Sys.Browser.version = parseFloat(navigator.userAgent.match(/ AppleWebKit\/(\d+(\.\d+)?)/)[1]); - Sys.Browser.name = 'Safari'; -} -else if (navigator.userAgent.indexOf('Opera/') > -1) { - Sys.Browser.agent = Sys.Browser.Opera; -} - -Sys.EventArgs = function Sys$EventArgs() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); -} -Sys.EventArgs.registerClass('Sys.EventArgs'); -Sys.EventArgs.Empty = new Sys.EventArgs(); - -Sys.CancelEventArgs = function Sys$CancelEventArgs() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - Sys.CancelEventArgs.initializeBase(this); - this._cancel = false; -} - function Sys$CancelEventArgs$get_cancel() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._cancel; - } - function Sys$CancelEventArgs$set_cancel(value) { - var e = Function._validateParams(arguments, [{name: "value", type: Boolean}]); - if (e) throw e; - this._cancel = value; - } -Sys.CancelEventArgs.prototype = { - get_cancel: Sys$CancelEventArgs$get_cancel, - set_cancel: Sys$CancelEventArgs$set_cancel -} -Sys.CancelEventArgs.registerClass('Sys.CancelEventArgs', Sys.EventArgs); -Type.registerNamespace('Sys.UI'); - -Sys._Debug = function Sys$_Debug() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); -} - function Sys$_Debug$_appendConsole(text) { - if ((typeof(Debug) !== 'undefined') && Debug.writeln) { - Debug.writeln(text); - } - if (window.console && window.console.log) { - window.console.log(text); - } - if (window.opera) { - window.opera.postError(text); - } - if (window.debugService) { - window.debugService.trace(text); - } - } - function Sys$_Debug$_appendTrace(text) { - var traceElement = document.getElementById('TraceConsole'); - if (traceElement && (traceElement.tagName.toUpperCase() === 'TEXTAREA')) { - traceElement.value += text + '\n'; - } - } - function Sys$_Debug$assert(condition, message, displayCaller) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "condition", type: Boolean}, - {name: "message", type: String, mayBeNull: true, optional: true}, - {name: "displayCaller", type: Boolean, optional: true} - ]); - if (e) throw e; - if (!condition) { - message = (displayCaller && this.assert.caller) ? - String.format(Sys.Res.assertFailedCaller, message, this.assert.caller) : - String.format(Sys.Res.assertFailed, message); - if (confirm(String.format(Sys.Res.breakIntoDebugger, message))) { - this.fail(message); - } - } - } - function Sys$_Debug$clearTrace() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - var traceElement = document.getElementById('TraceConsole'); - if (traceElement && (traceElement.tagName.toUpperCase() === 'TEXTAREA')) { - traceElement.value = ''; - } - } - function Sys$_Debug$fail(message) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "message", type: String, mayBeNull: true} - ]); - if (e) throw e; - this._appendConsole(message); - if (Sys.Browser.hasDebuggerStatement) { - eval('debugger'); - } - } - function Sys$_Debug$trace(text) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "text"} - ]); - if (e) throw e; - this._appendConsole(text); - this._appendTrace(text); - } - function Sys$_Debug$traceDump(object, name) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "object", mayBeNull: true}, - {name: "name", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - var text = this._traceDump(object, name, true); - } - function Sys$_Debug$_traceDump(object, name, recursive, indentationPadding, loopArray) { - name = name? name : 'traceDump'; - indentationPadding = indentationPadding? indentationPadding : ''; - if (object === null) { - this.trace(indentationPadding + name + ': null'); - return; - } - switch(typeof(object)) { - case 'undefined': - this.trace(indentationPadding + name + ': Undefined'); - break; - case 'number': case 'string': case 'boolean': - this.trace(indentationPadding + name + ': ' + object); - break; - default: - if (Date.isInstanceOfType(object) || RegExp.isInstanceOfType(object)) { - this.trace(indentationPadding + name + ': ' + object.toString()); - break; - } - if (!loopArray) { - loopArray = []; - } - else if (Array.contains(loopArray, object)) { - this.trace(indentationPadding + name + ': ...'); - return; - } - Array.add(loopArray, object); - if ((object == window) || (object === document) || - (window.HTMLElement && (object instanceof HTMLElement)) || - (typeof(object.nodeName) === 'string')) { - var tag = object.tagName? object.tagName : 'DomElement'; - if (object.id) { - tag += ' - ' + object.id; - } - this.trace(indentationPadding + name + ' {' + tag + '}'); - } - else { - var typeName = Object.getTypeName(object); - this.trace(indentationPadding + name + (typeof(typeName) === 'string' ? ' {' + typeName + '}' : '')); - if ((indentationPadding === '') || recursive) { - indentationPadding += " "; - var i, length, properties, p, v; - if (Array.isInstanceOfType(object)) { - length = object.length; - for (i = 0; i < length; i++) { - this._traceDump(object[i], '[' + i + ']', recursive, indentationPadding, loopArray); - } - } - else { - for (p in object) { - v = object[p]; - if (!Function.isInstanceOfType(v)) { - this._traceDump(v, p, recursive, indentationPadding, loopArray); - } - } - } - } - } - Array.remove(loopArray, object); - } - } -Sys._Debug.prototype = { - _appendConsole: Sys$_Debug$_appendConsole, - _appendTrace: Sys$_Debug$_appendTrace, - assert: Sys$_Debug$assert, - clearTrace: Sys$_Debug$clearTrace, - fail: Sys$_Debug$fail, - trace: Sys$_Debug$trace, - traceDump: Sys$_Debug$traceDump, - _traceDump: Sys$_Debug$_traceDump -} -Sys._Debug.registerClass('Sys._Debug'); -Sys.Debug = new Sys._Debug(); - Sys.Debug.isDebug = true; - -function Sys$Enum$parse(value, ignoreCase) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "value", type: String}, - {name: "ignoreCase", type: Boolean, optional: true} - ]); - if (e) throw e; - var values, parsed, val; - if (ignoreCase) { - values = this.__lowerCaseValues; - if (!values) { - this.__lowerCaseValues = values = {}; - var prototype = this.prototype; - for (var name in prototype) { - values[name.toLowerCase()] = prototype[name]; - } - } - } - else { - values = this.prototype; - } - if (!this.__flags) { - val = (ignoreCase ? value.toLowerCase() : value); - parsed = values[val.trim()]; - if (typeof(parsed) !== 'number') throw Error.argument('value', String.format(Sys.Res.enumInvalidValue, value, this.__typeName)); - return parsed; - } - else { - var parts = (ignoreCase ? value.toLowerCase() : value).split(','); - var v = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var part = parts[i].trim(); - parsed = values[part]; - if (typeof(parsed) !== 'number') throw Error.argument('value', String.format(Sys.Res.enumInvalidValue, value.split(',')[i].trim(), this.__typeName)); - v |= parsed; - } - return v; - } -} -function Sys$Enum$toString(value) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "value", mayBeNull: true, optional: true} - ]); - if (e) throw e; - if ((typeof(value) === 'undefined') || (value === null)) return this.__string; - if ((typeof(value) != 'number') || ((value % 1) !== 0)) throw Error.argumentType('value', Object.getType(value), this); - var values = this.prototype; - var i; - if (!this.__flags || (value === 0)) { - for (i in values) { - if (values[i] === value) { - return i; - } - } - } - else { - var sorted = this.__sortedValues; - if (!sorted) { - sorted = []; - for (i in values) { - sorted[sorted.length] = {key: i, value: values[i]}; - } - sorted.sort(function(a, b) { - return a.value - b.value; - }); - this.__sortedValues = sorted; - } - var parts = []; - var v = value; - for (i = sorted.length - 1; i >= 0; i--) { - var kvp = sorted[i]; - var vali = kvp.value; - if (vali === 0) continue; - if ((vali & value) === vali) { - parts[parts.length] = kvp.key; - v -= vali; - if (v === 0) break; - } - } - if (parts.length && v === 0) return parts.reverse().join(', '); - } - throw Error.argumentOutOfRange('value', value, String.format(Sys.Res.enumInvalidValue, value, this.__typeName)); -} -Type.prototype.registerEnum = function Type$registerEnum(name, flags) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "name", type: String}, - {name: "flags", type: Boolean, optional: true} - ]); - if (e) throw e; - if (!Type.__fullyQualifiedIdentifierRegExp.test(name)) throw Error.argument('name', Sys.Res.notATypeName); - var parsedName; - try { - parsedName = eval(name); - } - catch(e) { - throw Error.argument('name', Sys.Res.argumentTypeName); - } - if (parsedName !== this) throw Error.argument('name', Sys.Res.badTypeName); - if (Sys.__registeredTypes[name]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, name)); - for (var j in this.prototype) { - var val = this.prototype[j]; - if (!Type.__identifierRegExp.test(j)) throw Error.invalidOperation(String.format(Sys.Res.enumInvalidValueName, j)); - if (typeof(val) !== 'number' || (val % 1) !== 0) throw Error.invalidOperation(Sys.Res.enumValueNotInteger); - if (typeof(this[j]) !== 'undefined') throw Error.invalidOperation(String.format(Sys.Res.enumReservedName, j)); - } - Sys.__upperCaseTypes[name.toUpperCase()] = this; - for (var i in this.prototype) { - this[i] = this.prototype[i]; - } - this.__typeName = name; - this.parse = Sys$Enum$parse; - this.__string = this.toString(); - this.toString = Sys$Enum$toString; - this.__flags = flags; - this.__enum = true; - Sys.__registeredTypes[name] = true; -} -Type.isEnum = function Type$isEnum(type) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "type", mayBeNull: true} - ]); - if (e) throw e; - if ((typeof(type) === 'undefined') || (type === null)) return false; - return !!type.__enum; -} -Type.isFlags = function Type$isFlags(type) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "type", mayBeNull: true} - ]); - if (e) throw e; - if ((typeof(type) === 'undefined') || (type === null)) return false; - return !!type.__flags; -} -Sys.CollectionChange = function Sys$CollectionChange(action, newItems, newStartingIndex, oldItems, oldStartingIndex) { - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "action", type: Sys.NotifyCollectionChangedAction}, - {name: "newItems", mayBeNull: true, optional: true}, - {name: "newStartingIndex", type: Number, mayBeNull: true, integer: true, optional: true}, - {name: "oldItems", mayBeNull: true, optional: true}, - {name: "oldStartingIndex", type: Number, mayBeNull: true, integer: true, optional: true} - ]); - if (e) throw e; - this.action = action; - if (newItems) { - if (!(newItems instanceof Array)) { - newItems = [newItems]; - } - } - this.newItems = newItems || null; - if (typeof newStartingIndex !== "number") { - newStartingIndex = -1; - } - this.newStartingIndex = newStartingIndex; - if (oldItems) { - if (!(oldItems instanceof Array)) { - oldItems = [oldItems]; - } - } - this.oldItems = oldItems || null; - if (typeof oldStartingIndex !== "number") { - oldStartingIndex = -1; - } - this.oldStartingIndex = oldStartingIndex; -} -Sys.CollectionChange.registerClass("Sys.CollectionChange"); -Sys.NotifyCollectionChangedAction = function Sys$NotifyCollectionChangedAction() { - /// - /// - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); -} -Sys.NotifyCollectionChangedAction.prototype = { - add: 0, - remove: 1, - reset: 2 -} -Sys.NotifyCollectionChangedAction.registerEnum('Sys.NotifyCollectionChangedAction'); -Sys.NotifyCollectionChangedEventArgs = function Sys$NotifyCollectionChangedEventArgs(changes) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "changes", type: Array, elementType: Sys.CollectionChange} - ]); - if (e) throw e; - this._changes = changes; - Sys.NotifyCollectionChangedEventArgs.initializeBase(this); -} - function Sys$NotifyCollectionChangedEventArgs$get_changes() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._changes || []; - } -Sys.NotifyCollectionChangedEventArgs.prototype = { - get_changes: Sys$NotifyCollectionChangedEventArgs$get_changes -} -Sys.NotifyCollectionChangedEventArgs.registerClass("Sys.NotifyCollectionChangedEventArgs", Sys.EventArgs); -Sys.Observer = function Sys$Observer() { - throw Error.invalidOperation(); -} -Sys.Observer.registerClass("Sys.Observer"); -Sys.Observer.makeObservable = function Sys$Observer$makeObservable(target) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target"} - ]); - if (e) throw e; - var isArray = target instanceof Array, - o = Sys.Observer; - Sys.Observer._ensureObservable(target); - if (target.setValue === o._observeMethods.setValue) return target; - o._addMethods(target, o._observeMethods); - if (isArray) { - o._addMethods(target, o._arrayMethods); - } - return target; -} -Sys.Observer._ensureObservable = function Sys$Observer$_ensureObservable(target) { - var type = typeof target; - if ((type === "string") || (type === "number") || (type === "boolean") || (type === "date")) { - throw Error.invalidOperation(String.format(Sys.Res.notObservable, type)); - } -} -Sys.Observer._addMethods = function Sys$Observer$_addMethods(target, methods) { - for (var m in methods) { - if (target[m] && (target[m] !== methods[m])) { - throw Error.invalidOperation(String.format(Sys.Res.observableConflict, m)); - } - target[m] = methods[m]; - } -} -Sys.Observer._addEventHandler = function Sys$Observer$_addEventHandler(target, eventName, handler) { - Sys.Observer._getContext(target, true).events._addHandler(eventName, handler); -} -Sys.Observer.addEventHandler = function Sys$Observer$addEventHandler(target, eventName, handler) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target"}, - {name: "eventName", type: String}, - {name: "handler", type: Function} - ]); - if (e) throw e; - Sys.Observer._ensureObservable(target); - Sys.Observer._addEventHandler(target, eventName, handler); -} -Sys.Observer._removeEventHandler = function Sys$Observer$_removeEventHandler(target, eventName, handler) { - Sys.Observer._getContext(target, true).events._removeHandler(eventName, handler); -} -Sys.Observer.removeEventHandler = function Sys$Observer$removeEventHandler(target, eventName, handler) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target"}, - {name: "eventName", type: String}, - {name: "handler", type: Function} - ]); - if (e) throw e; - Sys.Observer._ensureObservable(target); - Sys.Observer._removeEventHandler(target, eventName, handler); -} -Sys.Observer.raiseEvent = function Sys$Observer$raiseEvent(target, eventName, eventArgs) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target"}, - {name: "eventName", type: String}, - {name: "eventArgs", type: Sys.EventArgs} - ]); - if (e) throw e; - Sys.Observer._ensureObservable(target); - var ctx = Sys.Observer._getContext(target); - if (!ctx) return; - var handler = ctx.events.getHandler(eventName); - if (handler) { - handler(target, eventArgs); - } -} -Sys.Observer.addPropertyChanged = function Sys$Observer$addPropertyChanged(target, handler) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target"}, - {name: "handler", type: Function} - ]); - if (e) throw e; - Sys.Observer._ensureObservable(target); - Sys.Observer._addEventHandler(target, "propertyChanged", handler); -} -Sys.Observer.removePropertyChanged = function Sys$Observer$removePropertyChanged(target, handler) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target"}, - {name: "handler", type: Function} - ]); - if (e) throw e; - Sys.Observer._ensureObservable(target); - Sys.Observer._removeEventHandler(target, "propertyChanged", handler); -} -Sys.Observer.beginUpdate = function Sys$Observer$beginUpdate(target) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target"} - ]); - if (e) throw e; - Sys.Observer._ensureObservable(target); - Sys.Observer._getContext(target, true).updating = true; -} -Sys.Observer.endUpdate = function Sys$Observer$endUpdate(target) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target"} - ]); - if (e) throw e; - Sys.Observer._ensureObservable(target); - var ctx = Sys.Observer._getContext(target); - if (!ctx || !ctx.updating) return; - ctx.updating = false; - var dirty = ctx.dirty; - ctx.dirty = false; - if (dirty) { - if (target instanceof Array) { - var changes = ctx.changes; - ctx.changes = null; - Sys.Observer.raiseCollectionChanged(target, changes); - } - Sys.Observer.raisePropertyChanged(target, ""); - } -} -Sys.Observer.isUpdating = function Sys$Observer$isUpdating(target) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target"} - ]); - if (e) throw e; - Sys.Observer._ensureObservable(target); - var ctx = Sys.Observer._getContext(target); - return ctx ? ctx.updating : false; -} -Sys.Observer._setValue = function Sys$Observer$_setValue(target, propertyName, value) { - var getter, setter, mainTarget = target, path = propertyName.split('.'); - for (var i = 0, l = (path.length - 1); i < l ; i++) { - var name = path[i]; - getter = target["get_" + name]; - if (typeof (getter) === "function") { - target = getter.call(target); - } - else { - target = target[name]; - } - var type = typeof (target); - if ((target === null) || (type === "undefined")) { - throw Error.invalidOperation(String.format(Sys.Res.nullReferenceInPath, propertyName)); - } - } - var currentValue, lastPath = path[l]; - getter = target["get_" + lastPath]; - setter = target["set_" + lastPath]; - if (typeof(getter) === 'function') { - currentValue = getter.call(target); - } - else { - currentValue = target[lastPath]; - } - if (typeof(setter) === 'function') { - setter.call(target, value); - } - else { - target[lastPath] = value; - } - if (currentValue !== value) { - var ctx = Sys.Observer._getContext(mainTarget); - if (ctx && ctx.updating) { - ctx.dirty = true; - return; - }; - Sys.Observer.raisePropertyChanged(mainTarget, path[0]); - } -} -Sys.Observer.setValue = function Sys$Observer$setValue(target, propertyName, value) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target"}, - {name: "propertyName", type: String}, - {name: "value", mayBeNull: true} - ]); - if (e) throw e; - Sys.Observer._ensureObservable(target); - Sys.Observer._setValue(target, propertyName, value); -} -Sys.Observer.raisePropertyChanged = function Sys$Observer$raisePropertyChanged(target, propertyName) { - /// - /// - /// - Sys.Observer.raiseEvent(target, "propertyChanged", new Sys.PropertyChangedEventArgs(propertyName)); -} -Sys.Observer.addCollectionChanged = function Sys$Observer$addCollectionChanged(target, handler) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target", type: Array, elementMayBeNull: true}, - {name: "handler", type: Function} - ]); - if (e) throw e; - Sys.Observer._addEventHandler(target, "collectionChanged", handler); -} -Sys.Observer.removeCollectionChanged = function Sys$Observer$removeCollectionChanged(target, handler) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target", type: Array, elementMayBeNull: true}, - {name: "handler", type: Function} - ]); - if (e) throw e; - Sys.Observer._removeEventHandler(target, "collectionChanged", handler); -} -Sys.Observer._collectionChange = function Sys$Observer$_collectionChange(target, change) { - var ctx = Sys.Observer._getContext(target); - if (ctx && ctx.updating) { - ctx.dirty = true; - var changes = ctx.changes; - if (!changes) { - ctx.changes = changes = [change]; - } - else { - changes.push(change); - } - } - else { - Sys.Observer.raiseCollectionChanged(target, [change]); - Sys.Observer.raisePropertyChanged(target, 'length'); - } -} -Sys.Observer.add = function Sys$Observer$add(target, item) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target", type: Array, elementMayBeNull: true}, - {name: "item", mayBeNull: true} - ]); - if (e) throw e; - var change = new Sys.CollectionChange(Sys.NotifyCollectionChangedAction.add, [item], target.length); - Array.add(target, item); - Sys.Observer._collectionChange(target, change); -} -Sys.Observer.addRange = function Sys$Observer$addRange(target, items) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target", type: Array, elementMayBeNull: true}, - {name: "items", type: Array, elementMayBeNull: true} - ]); - if (e) throw e; - var change = new Sys.CollectionChange(Sys.NotifyCollectionChangedAction.add, items, target.length); - Array.addRange(target, items); - Sys.Observer._collectionChange(target, change); -} -Sys.Observer.clear = function Sys$Observer$clear(target) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target", type: Array, elementMayBeNull: true} - ]); - if (e) throw e; - var oldItems = Array.clone(target); - Array.clear(target); - Sys.Observer._collectionChange(target, new Sys.CollectionChange(Sys.NotifyCollectionChangedAction.reset, null, -1, oldItems, 0)); -} -Sys.Observer.insert = function Sys$Observer$insert(target, index, item) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target", type: Array, elementMayBeNull: true}, - {name: "index", type: Number, integer: true}, - {name: "item", mayBeNull: true} - ]); - if (e) throw e; - Array.insert(target, index, item); - Sys.Observer._collectionChange(target, new Sys.CollectionChange(Sys.NotifyCollectionChangedAction.add, [item], index)); -} -Sys.Observer.remove = function Sys$Observer$remove(target, item) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target", type: Array, elementMayBeNull: true}, - {name: "item", mayBeNull: true} - ]); - if (e) throw e; - var index = Array.indexOf(target, item); - if (index !== -1) { - Array.remove(target, item); - Sys.Observer._collectionChange(target, new Sys.CollectionChange(Sys.NotifyCollectionChangedAction.remove, null, -1, [item], index)); - return true; - } - return false; -} -Sys.Observer.removeAt = function Sys$Observer$removeAt(target, index) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target", type: Array, elementMayBeNull: true}, - {name: "index", type: Number, integer: true} - ]); - if (e) throw e; - if ((index > -1) && (index < target.length)) { - var item = target[index]; - Array.removeAt(target, index); - Sys.Observer._collectionChange(target, new Sys.CollectionChange(Sys.NotifyCollectionChangedAction.remove, null, -1, [item], index)); - } -} -Sys.Observer.raiseCollectionChanged = function Sys$Observer$raiseCollectionChanged(target, changes) { - /// - /// - /// - Sys.Observer.raiseEvent(target, "collectionChanged", new Sys.NotifyCollectionChangedEventArgs(changes)); -} -Sys.Observer._observeMethods = { - add_propertyChanged: function(handler) { - Sys.Observer._addEventHandler(this, "propertyChanged", handler); - }, - remove_propertyChanged: function(handler) { - Sys.Observer._removeEventHandler(this, "propertyChanged", handler); - }, - addEventHandler: function(eventName, handler) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "eventName", type: String}, - {name: "handler", type: Function} - ]); - if (e) throw e; - Sys.Observer._addEventHandler(this, eventName, handler); - }, - removeEventHandler: function(eventName, handler) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "eventName", type: String}, - {name: "handler", type: Function} - ]); - if (e) throw e; - Sys.Observer._removeEventHandler(this, eventName, handler); - }, - get_isUpdating: function() { - /// - /// - return Sys.Observer.isUpdating(this); - }, - beginUpdate: function() { - /// - Sys.Observer.beginUpdate(this); - }, - endUpdate: function() { - /// - Sys.Observer.endUpdate(this); - }, - setValue: function(name, value) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "name", type: String}, - {name: "value", mayBeNull: true} - ]); - if (e) throw e; - Sys.Observer._setValue(this, name, value); - }, - raiseEvent: function(eventName, eventArgs) { - /// - /// - /// - Sys.Observer.raiseEvent(this, eventName, eventArgs); - }, - raisePropertyChanged: function(name) { - /// - /// - Sys.Observer.raiseEvent(this, "propertyChanged", new Sys.PropertyChangedEventArgs(name)); - } -} -Sys.Observer._arrayMethods = { - add_collectionChanged: function(handler) { - Sys.Observer._addEventHandler(this, "collectionChanged", handler); - }, - remove_collectionChanged: function(handler) { - Sys.Observer._removeEventHandler(this, "collectionChanged", handler); - }, - add: function(item) { - /// - /// - Sys.Observer.add(this, item); - }, - addRange: function(items) { - /// - /// - Sys.Observer.addRange(this, items); - }, - clear: function() { - /// - Sys.Observer.clear(this); - }, - insert: function(index, item) { - /// - /// - /// - Sys.Observer.insert(this, index, item); - }, - remove: function(item) { - /// - /// - /// - return Sys.Observer.remove(this, item); - }, - removeAt: function(index) { - /// - /// - Sys.Observer.removeAt(this, index); - }, - raiseCollectionChanged: function(changes) { - /// - /// - Sys.Observer.raiseEvent(this, "collectionChanged", new Sys.NotifyCollectionChangedEventArgs(changes)); - } -} -Sys.Observer._getContext = function Sys$Observer$_getContext(obj, create) { - var ctx = obj._observerContext; - if (ctx) return ctx(); - if (create) { - return (obj._observerContext = Sys.Observer._createContext())(); - } - return null; -} -Sys.Observer._createContext = function Sys$Observer$_createContext() { - var ctx = { - events: new Sys.EventHandlerList() - }; - return function() { - return ctx; - } -} -Date._appendPreOrPostMatch = function Date$_appendPreOrPostMatch(preMatch, strBuilder) { - var quoteCount = 0; - var escaped = false; - for (var i = 0, il = preMatch.length; i < il; i++) { - var c = preMatch.charAt(i); - switch (c) { - case '\'': - if (escaped) strBuilder.append("'"); - else quoteCount++; - escaped = false; - break; - case '\\': - if (escaped) strBuilder.append("\\"); - escaped = !escaped; - break; - default: - strBuilder.append(c); - escaped = false; - break; - } - } - return quoteCount; -} -Date._expandFormat = function Date$_expandFormat(dtf, format) { - if (!format) { - format = "F"; - } - var len = format.length; - if (len === 1) { - switch (format) { - case "d": - return dtf.ShortDatePattern; - case "D": - return dtf.LongDatePattern; - case "t": - return dtf.ShortTimePattern; - case "T": - return dtf.LongTimePattern; - case "f": - return dtf.LongDatePattern + " " + dtf.ShortTimePattern; - case "F": - return dtf.FullDateTimePattern; - case "M": case "m": - return dtf.MonthDayPattern; - case "s": - return dtf.SortableDateTimePattern; - case "Y": case "y": - return dtf.YearMonthPattern; - default: - throw Error.format(Sys.Res.formatInvalidString); - } - } - else if ((len === 2) && (format.charAt(0) === "%")) { - format = format.charAt(1); - } - return format; -} -Date._expandYear = function Date$_expandYear(dtf, year) { - var now = new Date(), - era = Date._getEra(now); - if (year < 100) { - var curr = Date._getEraYear(now, dtf, era); - year += curr - (curr % 100); - if (year > dtf.Calendar.TwoDigitYearMax) { - year -= 100; - } - } - return year; -} -Date._getEra = function Date$_getEra(date, eras) { - if (!eras) return 0; - var start, ticks = date.getTime(); - for (var i = 0, l = eras.length; i < l; i += 4) { - start = eras[i+2]; - if ((start === null) || (ticks >= start)) { - return i; - } - } - return 0; -} -Date._getEraYear = function Date$_getEraYear(date, dtf, era, sortable) { - var year = date.getFullYear(); - if (!sortable && dtf.eras) { - year -= dtf.eras[era + 3]; - } - return year; -} -Date._getParseRegExp = function Date$_getParseRegExp(dtf, format) { - if (!dtf._parseRegExp) { - dtf._parseRegExp = {}; - } - else if (dtf._parseRegExp[format]) { - return dtf._parseRegExp[format]; - } - var expFormat = Date._expandFormat(dtf, format); - expFormat = expFormat.replace(/([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g, "\\\\$1"); - var regexp = new Sys.StringBuilder("^"); - var groups = []; - var index = 0; - var quoteCount = 0; - var tokenRegExp = Date._getTokenRegExp(); - var match; - while ((match = tokenRegExp.exec(expFormat)) !== null) { - var preMatch = expFormat.slice(index, match.index); - index = tokenRegExp.lastIndex; - quoteCount += Date._appendPreOrPostMatch(preMatch, regexp); - if ((quoteCount%2) === 1) { - regexp.append(match[0]); - continue; - } - switch (match[0]) { - case 'dddd': case 'ddd': - case 'MMMM': case 'MMM': - case 'gg': case 'g': - regexp.append("(\\D+)"); - break; - case 'tt': case 't': - regexp.append("(\\D*)"); - break; - case 'yyyy': - regexp.append("(\\d{4})"); - break; - case 'fff': - regexp.append("(\\d{3})"); - break; - case 'ff': - regexp.append("(\\d{2})"); - break; - case 'f': - regexp.append("(\\d)"); - break; - case 'dd': case 'd': - case 'MM': case 'M': - case 'yy': case 'y': - case 'HH': case 'H': - case 'hh': case 'h': - case 'mm': case 'm': - case 'ss': case 's': - regexp.append("(\\d\\d?)"); - break; - case 'zzz': - regexp.append("([+-]?\\d\\d?:\\d{2})"); - break; - case 'zz': case 'z': - regexp.append("([+-]?\\d\\d?)"); - break; - case '/': - regexp.append("(\\" + dtf.DateSeparator + ")"); - break; - default: - Sys.Debug.fail("Invalid date format pattern"); - } - Array.add(groups, match[0]); - } - Date._appendPreOrPostMatch(expFormat.slice(index), regexp); - regexp.append("$"); - var regexpStr = regexp.toString().replace(/\s+/g, "\\s+"); - var parseRegExp = {'regExp': regexpStr, 'groups': groups}; - dtf._parseRegExp[format] = parseRegExp; - return parseRegExp; -} -Date._getTokenRegExp = function Date$_getTokenRegExp() { - return /\/|dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z|gg|g/g; -} -Date.parseLocale = function Date$parseLocale(value, formats) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "value", type: String}, - {name: "formats", mayBeNull: true, optional: true, parameterArray: true} - ]); - if (e) throw e; - return Date._parse(value, Sys.CultureInfo.CurrentCulture, arguments); -} -Date.parseInvariant = function Date$parseInvariant(value, formats) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "value", type: String}, - {name: "formats", mayBeNull: true, optional: true, parameterArray: true} - ]); - if (e) throw e; - return Date._parse(value, Sys.CultureInfo.InvariantCulture, arguments); -} -Date._parse = function Date$_parse(value, cultureInfo, args) { - var i, l, date, format, formats, custom = false; - for (i = 1, l = args.length; i < l; i++) { - format = args[i]; - if (format) { - custom = true; - date = Date._parseExact(value, format, cultureInfo); - if (date) return date; - } - } - if (! custom) { - formats = cultureInfo._getDateTimeFormats(); - for (i = 0, l = formats.length; i < l; i++) { - date = Date._parseExact(value, formats[i], cultureInfo); - if (date) return date; - } - } - return null; -} -Date._parseExact = function Date$_parseExact(value, format, cultureInfo) { - value = value.trim(); - var dtf = cultureInfo.dateTimeFormat, - parseInfo = Date._getParseRegExp(dtf, format), - match = new RegExp(parseInfo.regExp).exec(value); - if (match === null) return null; - - var groups = parseInfo.groups, - era = null, year = null, month = null, date = null, weekDay = null, - hour = 0, hourOffset, min = 0, sec = 0, msec = 0, tzMinOffset = null, - pmHour = false; - for (var j = 0, jl = groups.length; j < jl; j++) { - var matchGroup = match[j+1]; - if (matchGroup) { - switch (groups[j]) { - case 'dd': case 'd': - date = parseInt(matchGroup, 10); - if ((date < 1) || (date > 31)) return null; - break; - case 'MMMM': - month = cultureInfo._getMonthIndex(matchGroup); - if ((month < 0) || (month > 11)) return null; - break; - case 'MMM': - month = cultureInfo._getAbbrMonthIndex(matchGroup); - if ((month < 0) || (month > 11)) return null; - break; - case 'M': case 'MM': - month = parseInt(matchGroup, 10) - 1; - if ((month < 0) || (month > 11)) return null; - break; - case 'y': case 'yy': - year = Date._expandYear(dtf,parseInt(matchGroup, 10)); - if ((year < 0) || (year > 9999)) return null; - break; - case 'yyyy': - year = parseInt(matchGroup, 10); - if ((year < 0) || (year > 9999)) return null; - break; - case 'h': case 'hh': - hour = parseInt(matchGroup, 10); - if (hour === 12) hour = 0; - if ((hour < 0) || (hour > 11)) return null; - break; - case 'H': case 'HH': - hour = parseInt(matchGroup, 10); - if ((hour < 0) || (hour > 23)) return null; - break; - case 'm': case 'mm': - min = parseInt(matchGroup, 10); - if ((min < 0) || (min > 59)) return null; - break; - case 's': case 'ss': - sec = parseInt(matchGroup, 10); - if ((sec < 0) || (sec > 59)) return null; - break; - case 'tt': case 't': - var upperToken = matchGroup.toUpperCase(); - pmHour = (upperToken === dtf.PMDesignator.toUpperCase()); - if (!pmHour && (upperToken !== dtf.AMDesignator.toUpperCase())) return null; - break; - case 'f': - msec = parseInt(matchGroup, 10) * 100; - if ((msec < 0) || (msec > 999)) return null; - break; - case 'ff': - msec = parseInt(matchGroup, 10) * 10; - if ((msec < 0) || (msec > 999)) return null; - break; - case 'fff': - msec = parseInt(matchGroup, 10); - if ((msec < 0) || (msec > 999)) return null; - break; - case 'dddd': - weekDay = cultureInfo._getDayIndex(matchGroup); - if ((weekDay < 0) || (weekDay > 6)) return null; - break; - case 'ddd': - weekDay = cultureInfo._getAbbrDayIndex(matchGroup); - if ((weekDay < 0) || (weekDay > 6)) return null; - break; - case 'zzz': - var offsets = matchGroup.split(/:/); - if (offsets.length !== 2) return null; - hourOffset = parseInt(offsets[0], 10); - if ((hourOffset < -12) || (hourOffset > 13)) return null; - var minOffset = parseInt(offsets[1], 10); - if ((minOffset < 0) || (minOffset > 59)) return null; - tzMinOffset = (hourOffset * 60) + (matchGroup.startsWith('-')? -minOffset : minOffset); - break; - case 'z': case 'zz': - hourOffset = parseInt(matchGroup, 10); - if ((hourOffset < -12) || (hourOffset > 13)) return null; - tzMinOffset = hourOffset * 60; - break; - case 'g': case 'gg': - var eraName = matchGroup; - if (!eraName || !dtf.eras) return null; - eraName = eraName.toLowerCase().trim(); - for (var i = 0, l = dtf.eras.length; i < l; i += 4) { - if (eraName === dtf.eras[i + 1].toLowerCase()) { - era = i; - break; - } - } - if (era === null) return null; - break; - } - } - } - var result = new Date(), defaults, convert = dtf.Calendar.convert; - if (convert) { - defaults = convert.fromGregorian(result); - } - if (!convert) { - defaults = [result.getFullYear(), result.getMonth(), result.getDate()]; - } - if (year === null) { - year = defaults[0]; - } - else if (dtf.eras) { - year += dtf.eras[(era || 0) + 3]; - } - if (month === null) { - month = defaults[1]; - } - if (date === null) { - date = defaults[2]; - } - if (convert) { - result = convert.toGregorian(year, month, date); - if (result === null) return null; - } - else { - result.setFullYear(year, month, date); - if (result.getDate() !== date) return null; - if ((weekDay !== null) && (result.getDay() !== weekDay)) { - return null; - } - } - if (pmHour && (hour < 12)) { - hour += 12; - } - result.setHours(hour, min, sec, msec); - if (tzMinOffset !== null) { - var adjustedMin = result.getMinutes() - (tzMinOffset + result.getTimezoneOffset()); - result.setHours(result.getHours() + parseInt(adjustedMin/60, 10), adjustedMin%60); - } - return result; -} -Date.prototype.format = function Date$format(format) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "format", type: String} - ]); - if (e) throw e; - return this._toFormattedString(format, Sys.CultureInfo.InvariantCulture); -} -Date.prototype.localeFormat = function Date$localeFormat(format) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "format", type: String} - ]); - if (e) throw e; - return this._toFormattedString(format, Sys.CultureInfo.CurrentCulture); -} -Date.prototype._toFormattedString = function Date$_toFormattedString(format, cultureInfo) { - var dtf = cultureInfo.dateTimeFormat, - convert = dtf.Calendar.convert; - if (!format || !format.length || (format === 'i')) { - if (cultureInfo && cultureInfo.name.length) { - if (convert) { - return this._toFormattedString(dtf.FullDateTimePattern, cultureInfo); - } - else { - var eraDate = new Date(this.getTime()); - var era = Date._getEra(this, dtf.eras); - eraDate.setFullYear(Date._getEraYear(this, dtf, era)); - return eraDate.toLocaleString(); - } - } - else { - return this.toString(); - } - } - var eras = dtf.eras, - sortable = (format === "s"); - format = Date._expandFormat(dtf, format); - var ret = new Sys.StringBuilder(); - var hour; - function addLeadingZero(num) { - if (num < 10) { - return '0' + num; - } - return num.toString(); - } - function addLeadingZeros(num) { - if (num < 10) { - return '00' + num; - } - if (num < 100) { - return '0' + num; - } - return num.toString(); - } - function padYear(year) { - if (year < 10) { - return '000' + year; - } - else if (year < 100) { - return '00' + year; - } - else if (year < 1000) { - return '0' + year; - } - return year.toString(); - } - - var foundDay, checkedDay, dayPartRegExp = /([^d]|^)(d|dd)([^d]|$)/g; - function hasDay() { - if (foundDay || checkedDay) { - return foundDay; - } - foundDay = dayPartRegExp.test(format); - checkedDay = true; - return foundDay; - } - - var quoteCount = 0, - tokenRegExp = Date._getTokenRegExp(), - converted; - if (!sortable && convert) { - converted = convert.fromGregorian(this); - } - for (;;) { - var index = tokenRegExp.lastIndex; - var ar = tokenRegExp.exec(format); - var preMatch = format.slice(index, ar ? ar.index : format.length); - quoteCount += Date._appendPreOrPostMatch(preMatch, ret); - if (!ar) break; - if ((quoteCount%2) === 1) { - ret.append(ar[0]); - continue; - } - - function getPart(date, part) { - if (converted) { - return converted[part]; - } - switch (part) { - case 0: return date.getFullYear(); - case 1: return date.getMonth(); - case 2: return date.getDate(); - } - } - switch (ar[0]) { - case "dddd": - ret.append(dtf.DayNames[this.getDay()]); - break; - case "ddd": - ret.append(dtf.AbbreviatedDayNames[this.getDay()]); - break; - case "dd": - foundDay = true; - ret.append(addLeadingZero(getPart(this, 2))); - break; - case "d": - foundDay = true; - ret.append(getPart(this, 2)); - break; - case "MMMM": - ret.append((dtf.MonthGenitiveNames && hasDay()) - ? dtf.MonthGenitiveNames[getPart(this, 1)] - : dtf.MonthNames[getPart(this, 1)]); - break; - case "MMM": - ret.append((dtf.AbbreviatedMonthGenitiveNames && hasDay()) - ? dtf.AbbreviatedMonthGenitiveNames[getPart(this, 1)] - : dtf.AbbreviatedMonthNames[getPart(this, 1)]); - break; - case "MM": - ret.append(addLeadingZero(getPart(this, 1) + 1)); - break; - case "M": - ret.append(getPart(this, 1) + 1); - break; - case "yyyy": - ret.append(padYear(converted ? converted[0] : Date._getEraYear(this, dtf, Date._getEra(this, eras), sortable))); - break; - case "yy": - ret.append(addLeadingZero((converted ? converted[0] : Date._getEraYear(this, dtf, Date._getEra(this, eras), sortable)) % 100)); - break; - case "y": - ret.append((converted ? converted[0] : Date._getEraYear(this, dtf, Date._getEra(this, eras), sortable)) % 100); - break; - case "hh": - hour = this.getHours() % 12; - if (hour === 0) hour = 12; - ret.append(addLeadingZero(hour)); - break; - case "h": - hour = this.getHours() % 12; - if (hour === 0) hour = 12; - ret.append(hour); - break; - case "HH": - ret.append(addLeadingZero(this.getHours())); - break; - case "H": - ret.append(this.getHours()); - break; - case "mm": - ret.append(addLeadingZero(this.getMinutes())); - break; - case "m": - ret.append(this.getMinutes()); - break; - case "ss": - ret.append(addLeadingZero(this.getSeconds())); - break; - case "s": - ret.append(this.getSeconds()); - break; - case "tt": - ret.append((this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator); - break; - case "t": - ret.append(((this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator).charAt(0)); - break; - case "f": - ret.append(addLeadingZeros(this.getMilliseconds()).charAt(0)); - break; - case "ff": - ret.append(addLeadingZeros(this.getMilliseconds()).substr(0, 2)); - break; - case "fff": - ret.append(addLeadingZeros(this.getMilliseconds())); - break; - case "z": - hour = this.getTimezoneOffset() / 60; - ret.append(((hour <= 0) ? '+' : '-') + Math.floor(Math.abs(hour))); - break; - case "zz": - hour = this.getTimezoneOffset() / 60; - ret.append(((hour <= 0) ? '+' : '-') + addLeadingZero(Math.floor(Math.abs(hour)))); - break; - case "zzz": - hour = this.getTimezoneOffset() / 60; - ret.append(((hour <= 0) ? '+' : '-') + addLeadingZero(Math.floor(Math.abs(hour))) + - ":" + addLeadingZero(Math.abs(this.getTimezoneOffset() % 60))); - break; - case "g": - case "gg": - if (dtf.eras) { - ret.append(dtf.eras[Date._getEra(this, eras) + 1]); - } - break; - case "/": - ret.append(dtf.DateSeparator); - break; - default: - Sys.Debug.fail("Invalid date format pattern"); - } - } - return ret.toString(); -} -String.localeFormat = function String$localeFormat(format, args) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "format", type: String}, - {name: "args", mayBeNull: true, parameterArray: true} - ]); - if (e) throw e; - return String._toFormattedString(true, arguments); -} -Number.parseLocale = function Number$parseLocale(value) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "value", type: String} - ], false); - if (e) throw e; - return Number._parse(value, Sys.CultureInfo.CurrentCulture); -} -Number.parseInvariant = function Number$parseInvariant(value) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "value", type: String} - ], false); - if (e) throw e; - return Number._parse(value, Sys.CultureInfo.InvariantCulture); -} -Number._parse = function Number$_parse(value, cultureInfo) { - value = value.trim(); - - if (value.match(/^[+-]?infinity$/i)) { - return parseFloat(value); - } - if (value.match(/^0x[a-f0-9]+$/i)) { - return parseInt(value); - } - var numFormat = cultureInfo.numberFormat; - var signInfo = Number._parseNumberNegativePattern(value, numFormat, numFormat.NumberNegativePattern); - var sign = signInfo[0]; - var num = signInfo[1]; - - if ((sign === '') && (numFormat.NumberNegativePattern !== 1)) { - signInfo = Number._parseNumberNegativePattern(value, numFormat, 1); - sign = signInfo[0]; - num = signInfo[1]; - } - if (sign === '') sign = '+'; - - var exponent; - var intAndFraction; - var exponentPos = num.indexOf('e'); - if (exponentPos < 0) exponentPos = num.indexOf('E'); - if (exponentPos < 0) { - intAndFraction = num; - exponent = null; - } - else { - intAndFraction = num.substr(0, exponentPos); - exponent = num.substr(exponentPos + 1); - } - - var integer; - var fraction; - var decimalPos = intAndFraction.indexOf(numFormat.NumberDecimalSeparator); - if (decimalPos < 0) { - integer = intAndFraction; - fraction = null; - } - else { - integer = intAndFraction.substr(0, decimalPos); - fraction = intAndFraction.substr(decimalPos + numFormat.NumberDecimalSeparator.length); - } - - integer = integer.split(numFormat.NumberGroupSeparator).join(''); - var altNumGroupSeparator = numFormat.NumberGroupSeparator.replace(/\u00A0/g, " "); - if (numFormat.NumberGroupSeparator !== altNumGroupSeparator) { - integer = integer.split(altNumGroupSeparator).join(''); - } - - var p = sign + integer; - if (fraction !== null) { - p += '.' + fraction; - } - if (exponent !== null) { - var expSignInfo = Number._parseNumberNegativePattern(exponent, numFormat, 1); - if (expSignInfo[0] === '') { - expSignInfo[0] = '+'; - } - p += 'e' + expSignInfo[0] + expSignInfo[1]; - } - if (p.match(/^[+-]?\d*\.?\d*(e[+-]?\d+)?$/)) { - return parseFloat(p); - } - return Number.NaN; -} -Number._parseNumberNegativePattern = function Number$_parseNumberNegativePattern(value, numFormat, numberNegativePattern) { - var neg = numFormat.NegativeSign; - var pos = numFormat.PositiveSign; - switch (numberNegativePattern) { - case 4: - neg = ' ' + neg; - pos = ' ' + pos; - case 3: - if (value.endsWith(neg)) { - return ['-', value.substr(0, value.length - neg.length)]; - } - else if (value.endsWith(pos)) { - return ['+', value.substr(0, value.length - pos.length)]; - } - break; - case 2: - neg += ' '; - pos += ' '; - case 1: - if (value.startsWith(neg)) { - return ['-', value.substr(neg.length)]; - } - else if (value.startsWith(pos)) { - return ['+', value.substr(pos.length)]; - } - break; - case 0: - if (value.startsWith('(') && value.endsWith(')')) { - return ['-', value.substr(1, value.length - 2)]; - } - break; - default: - Sys.Debug.fail(""); - } - return ['', value]; -} -Number.prototype.format = function Number$format(format) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "format", type: String} - ]); - if (e) throw e; - return this._toFormattedString(format, Sys.CultureInfo.InvariantCulture); -} -Number.prototype.localeFormat = function Number$localeFormat(format) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "format", type: String} - ]); - if (e) throw e; - return this._toFormattedString(format, Sys.CultureInfo.CurrentCulture); -} -Number.prototype._toFormattedString = function Number$_toFormattedString(format, cultureInfo) { - if (!format || (format.length === 0) || (format === 'i')) { - if (cultureInfo && (cultureInfo.name.length > 0)) { - return this.toLocaleString(); - } - else { - return this.toString(); - } - } - - var _percentPositivePattern = ["n %", "n%", "%n" ]; - var _percentNegativePattern = ["-n %", "-n%", "-%n"]; - var _numberNegativePattern = ["(n)","-n","- n","n-","n -"]; - var _currencyPositivePattern = ["$n","n$","$ n","n $"]; - var _currencyNegativePattern = ["($n)","-$n","$-n","$n-","(n$)","-n$","n-$","n$-","-n $","-$ n","n $-","$ n-","$ -n","n- $","($ n)","(n $)"]; - function zeroPad(str, count, left) { - for (var l=str.length; l < count; l++) { - str = (left ? ('0' + str) : (str + '0')); - } - return str; - } - - function expandNumber(number, precision, groupSizes, sep, decimalChar) { - Sys.Debug.assert(groupSizes.length > 0, "groupSizes must be an array of at least 1"); - var curSize = groupSizes[0]; - var curGroupIndex = 1; - var factor = Math.pow(10, precision); - var rounded = (Math.round(number * factor) / factor); - if (!isFinite(rounded)) { - rounded = number; - } - number = rounded; - - var numberString = number.toString(); - var right = ""; - var exponent; - - - var split = numberString.split(/e/i); - numberString = split[0]; - exponent = (split.length > 1 ? parseInt(split[1]) : 0); - split = numberString.split('.'); - numberString = split[0]; - right = split.length > 1 ? split[1] : ""; - - var l; - if (exponent > 0) { - right = zeroPad(right, exponent, false); - numberString += right.slice(0, exponent); - right = right.substr(exponent); - } - else if (exponent < 0) { - exponent = -exponent; - numberString = zeroPad(numberString, exponent+1, true); - right = numberString.slice(-exponent, numberString.length) + right; - numberString = numberString.slice(0, -exponent); - } - if (precision > 0) { - if (right.length > precision) { - right = right.slice(0, precision); - } - else { - right = zeroPad(right, precision, false); - } - right = decimalChar + right; - } - else { - right = ""; - } - var stringIndex = numberString.length-1; - var ret = ""; - while (stringIndex >= 0) { - if (curSize === 0 || curSize > stringIndex) { - if (ret.length > 0) - return numberString.slice(0, stringIndex + 1) + sep + ret + right; - else - return numberString.slice(0, stringIndex + 1) + right; - } - if (ret.length > 0) - ret = numberString.slice(stringIndex - curSize + 1, stringIndex+1) + sep + ret; - else - ret = numberString.slice(stringIndex - curSize + 1, stringIndex+1); - stringIndex -= curSize; - if (curGroupIndex < groupSizes.length) { - curSize = groupSizes[curGroupIndex]; - curGroupIndex++; - } - } - return numberString.slice(0, stringIndex + 1) + sep + ret + right; - } - var nf = cultureInfo.numberFormat; - var number = Math.abs(this); - if (!format) - format = "D"; - var precision = -1; - if (format.length > 1) precision = parseInt(format.slice(1), 10); - var pattern; - switch (format.charAt(0)) { - case "d": - case "D": - pattern = 'n'; - if (precision !== -1) { - number = zeroPad(""+number, precision, true); - } - if (this < 0) number = -number; - break; - case "c": - case "C": - if (this < 0) pattern = _currencyNegativePattern[nf.CurrencyNegativePattern]; - else pattern = _currencyPositivePattern[nf.CurrencyPositivePattern]; - if (precision === -1) precision = nf.CurrencyDecimalDigits; - number = expandNumber(Math.abs(this), precision, nf.CurrencyGroupSizes, nf.CurrencyGroupSeparator, nf.CurrencyDecimalSeparator); - break; - case "n": - case "N": - if (this < 0) pattern = _numberNegativePattern[nf.NumberNegativePattern]; - else pattern = 'n'; - if (precision === -1) precision = nf.NumberDecimalDigits; - number = expandNumber(Math.abs(this), precision, nf.NumberGroupSizes, nf.NumberGroupSeparator, nf.NumberDecimalSeparator); - break; - case "p": - case "P": - if (this < 0) pattern = _percentNegativePattern[nf.PercentNegativePattern]; - else pattern = _percentPositivePattern[nf.PercentPositivePattern]; - if (precision === -1) precision = nf.PercentDecimalDigits; - number = expandNumber(Math.abs(this) * 100, precision, nf.PercentGroupSizes, nf.PercentGroupSeparator, nf.PercentDecimalSeparator); - break; - default: - throw Error.format(Sys.Res.formatBadFormatSpecifier); - } - var regex = /n|\$|-|%/g; - var ret = ""; - for (;;) { - var index = regex.lastIndex; - var ar = regex.exec(pattern); - ret += pattern.slice(index, ar ? ar.index : pattern.length); - if (!ar) - break; - switch (ar[0]) { - case "n": - ret += number; - break; - case "$": - ret += nf.CurrencySymbol; - break; - case "-": - if (/[1-9]/.test(number)) { - ret += nf.NegativeSign; - } - break; - case "%": - ret += nf.PercentSymbol; - break; - default: - Sys.Debug.fail("Invalid number format pattern"); - } - } - return ret; -} - -Sys.CultureInfo = function Sys$CultureInfo(name, numberFormat, dateTimeFormat) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "name", type: String}, - {name: "numberFormat", type: Object}, - {name: "dateTimeFormat", type: Object} - ]); - if (e) throw e; - this.name = name; - this.numberFormat = numberFormat; - this.dateTimeFormat = dateTimeFormat; -} - function Sys$CultureInfo$_getDateTimeFormats() { - if (! this._dateTimeFormats) { - var dtf = this.dateTimeFormat; - this._dateTimeFormats = - [ dtf.MonthDayPattern, - dtf.YearMonthPattern, - dtf.ShortDatePattern, - dtf.ShortTimePattern, - dtf.LongDatePattern, - dtf.LongTimePattern, - dtf.FullDateTimePattern, - dtf.RFC1123Pattern, - dtf.SortableDateTimePattern, - dtf.UniversalSortableDateTimePattern ]; - } - return this._dateTimeFormats; - } - function Sys$CultureInfo$_getIndex(value, a1, a2) { - var upper = this._toUpper(value), - i = Array.indexOf(a1, upper); - if (i === -1) { - i = Array.indexOf(a2, upper); - } - return i; - } - function Sys$CultureInfo$_getMonthIndex(value) { - if (!this._upperMonths) { - this._upperMonths = this._toUpperArray(this.dateTimeFormat.MonthNames); - this._upperMonthsGenitive = this._toUpperArray(this.dateTimeFormat.MonthGenitiveNames); - } - return this._getIndex(value, this._upperMonths, this._upperMonthsGenitive); - } - function Sys$CultureInfo$_getAbbrMonthIndex(value) { - if (!this._upperAbbrMonths) { - this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames); - this._upperAbbrMonthsGenitive = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthGenitiveNames); - } - return this._getIndex(value, this._upperAbbrMonths, this._upperAbbrMonthsGenitive); - } - function Sys$CultureInfo$_getDayIndex(value) { - if (!this._upperDays) { - this._upperDays = this._toUpperArray(this.dateTimeFormat.DayNames); - } - return Array.indexOf(this._upperDays, this._toUpper(value)); - } - function Sys$CultureInfo$_getAbbrDayIndex(value) { - if (!this._upperAbbrDays) { - this._upperAbbrDays = this._toUpperArray(this.dateTimeFormat.AbbreviatedDayNames); - } - return Array.indexOf(this._upperAbbrDays, this._toUpper(value)); - } - function Sys$CultureInfo$_toUpperArray(arr) { - var result = []; - for (var i = 0, il = arr.length; i < il; i++) { - result[i] = this._toUpper(arr[i]); - } - return result; - } - function Sys$CultureInfo$_toUpper(value) { - return value.split("\u00A0").join(' ').toUpperCase(); - } -Sys.CultureInfo.prototype = { - _getDateTimeFormats: Sys$CultureInfo$_getDateTimeFormats, - _getIndex: Sys$CultureInfo$_getIndex, - _getMonthIndex: Sys$CultureInfo$_getMonthIndex, - _getAbbrMonthIndex: Sys$CultureInfo$_getAbbrMonthIndex, - _getDayIndex: Sys$CultureInfo$_getDayIndex, - _getAbbrDayIndex: Sys$CultureInfo$_getAbbrDayIndex, - _toUpperArray: Sys$CultureInfo$_toUpperArray, - _toUpper: Sys$CultureInfo$_toUpper -} -Sys.CultureInfo.registerClass('Sys.CultureInfo'); -Sys.CultureInfo._parse = function Sys$CultureInfo$_parse(value) { - var dtf = value.dateTimeFormat; - if (dtf && !dtf.eras) { - dtf.eras = value.eras; - } - return new Sys.CultureInfo(value.name, value.numberFormat, dtf); -} -Sys.CultureInfo.InvariantCulture = Sys.CultureInfo._parse({"name":"","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":true,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"\u00A4","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":0,"PercentNegativePattern":0,"NegativeInfinitySymbol":"-Infinity","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"Infinity","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"\u2030","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"@-62135568000000@","MaxSupportedDateTime":"@253402300799999@","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, dd MMMM yyyy HH:mm:ss","LongDatePattern":"dddd, dd MMMM yyyy","LongTimePattern":"HH:mm:ss","MonthDayPattern":"MMMM dd","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\':\'mm\':\'ss \'GMT\'","ShortDatePattern":"MM/dd/yyyy","ShortTimePattern":"HH:mm","SortableDateTimePattern":"yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy\'-\'MM\'-\'dd HH\':\'mm\':\'ss\'Z\'","YearMonthPattern":"yyyy MMMM","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":true,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]},"eras":[1,"A.D.",null,0]}); -if (typeof(__cultureInfo) === "object") { - Sys.CultureInfo.CurrentCulture = Sys.CultureInfo._parse(__cultureInfo); - delete __cultureInfo; -} -else { - Sys.CultureInfo.CurrentCulture = Sys.CultureInfo._parse({"name":"en-US","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":false,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"$","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":0,"PercentNegativePattern":0,"NegativeInfinitySymbol":"-Infinity","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"Infinity","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"\u2030","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"@-62135568000000@","MaxSupportedDateTime":"@253402300799999@","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":false},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, MMMM dd, yyyy h:mm:ss tt","LongDatePattern":"dddd, MMMM dd, yyyy","LongTimePattern":"h:mm:ss tt","MonthDayPattern":"MMMM dd","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\':\'mm\':\'ss \'GMT\'","ShortDatePattern":"M/d/yyyy","ShortTimePattern":"h:mm tt","SortableDateTimePattern":"yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy\'-\'MM\'-\'dd HH\':\'mm\':\'ss\'Z\'","YearMonthPattern":"MMMM, yyyy","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":false,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]},"eras":[1,"A.D.",null,0]}); -} -Type.registerNamespace('Sys.Serialization'); -Sys.Serialization.JavaScriptSerializer = function Sys$Serialization$JavaScriptSerializer() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); -} -Sys.Serialization.JavaScriptSerializer.registerClass('Sys.Serialization.JavaScriptSerializer'); -Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs = []; -Sys.Serialization.JavaScriptSerializer._charsToEscape = []; -Sys.Serialization.JavaScriptSerializer._dateRegEx = new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)\\\\/\\"', 'g'); -Sys.Serialization.JavaScriptSerializer._escapeChars = {}; -Sys.Serialization.JavaScriptSerializer._escapeRegEx = new RegExp('["\\\\\\x00-\\x1F]', 'i'); -Sys.Serialization.JavaScriptSerializer._escapeRegExGlobal = new RegExp('["\\\\\\x00-\\x1F]', 'g'); -Sys.Serialization.JavaScriptSerializer._jsonRegEx = new RegExp('[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]', 'g'); -Sys.Serialization.JavaScriptSerializer._jsonStringRegEx = new RegExp('"(\\\\.|[^"\\\\])*"', 'g'); -Sys.Serialization.JavaScriptSerializer._serverTypeFieldName = '__type'; -Sys.Serialization.JavaScriptSerializer._init = function Sys$Serialization$JavaScriptSerializer$_init() { - var replaceChars = ['\\u0000','\\u0001','\\u0002','\\u0003','\\u0004','\\u0005','\\u0006','\\u0007', - '\\b','\\t','\\n','\\u000b','\\f','\\r','\\u000e','\\u000f','\\u0010','\\u0011', - '\\u0012','\\u0013','\\u0014','\\u0015','\\u0016','\\u0017','\\u0018','\\u0019', - '\\u001a','\\u001b','\\u001c','\\u001d','\\u001e','\\u001f']; - Sys.Serialization.JavaScriptSerializer._charsToEscape[0] = '\\'; - Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs['\\'] = new RegExp('\\\\', 'g'); - Sys.Serialization.JavaScriptSerializer._escapeChars['\\'] = '\\\\'; - Sys.Serialization.JavaScriptSerializer._charsToEscape[1] = '"'; - Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs['"'] = new RegExp('"', 'g'); - Sys.Serialization.JavaScriptSerializer._escapeChars['"'] = '\\"'; - for (var i = 0; i < 32; i++) { - var c = String.fromCharCode(i); - Sys.Serialization.JavaScriptSerializer._charsToEscape[i+2] = c; - Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs[c] = new RegExp(c, 'g'); - Sys.Serialization.JavaScriptSerializer._escapeChars[c] = replaceChars[i]; - } -} -Sys.Serialization.JavaScriptSerializer._serializeBooleanWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeBooleanWithBuilder(object, stringBuilder) { - stringBuilder.append(object.toString()); -} -Sys.Serialization.JavaScriptSerializer._serializeNumberWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeNumberWithBuilder(object, stringBuilder) { - if (isFinite(object)) { - stringBuilder.append(String(object)); - } - else { - throw Error.invalidOperation(Sys.Res.cannotSerializeNonFiniteNumbers); - } -} -Sys.Serialization.JavaScriptSerializer._serializeStringWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeStringWithBuilder(string, stringBuilder) { - stringBuilder.append('"'); - if (Sys.Serialization.JavaScriptSerializer._escapeRegEx.test(string)) { - if (Sys.Serialization.JavaScriptSerializer._charsToEscape.length === 0) { - Sys.Serialization.JavaScriptSerializer._init(); - } - if (string.length < 128) { - string = string.replace(Sys.Serialization.JavaScriptSerializer._escapeRegExGlobal, - function(x) { return Sys.Serialization.JavaScriptSerializer._escapeChars[x]; }); - } - else { - for (var i = 0; i < 34; i++) { - var c = Sys.Serialization.JavaScriptSerializer._charsToEscape[i]; - if (string.indexOf(c) !== -1) { - if (Sys.Browser.agent === Sys.Browser.Opera || Sys.Browser.agent === Sys.Browser.FireFox) { - string = string.split(c).join(Sys.Serialization.JavaScriptSerializer._escapeChars[c]); - } - else { - string = string.replace(Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs[c], - Sys.Serialization.JavaScriptSerializer._escapeChars[c]); - } - } - } - } - } - stringBuilder.append(string); - stringBuilder.append('"'); -} -Sys.Serialization.JavaScriptSerializer._serializeWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeWithBuilder(object, stringBuilder, sort, prevObjects) { - var i; - switch (typeof object) { - case 'object': - if (object) { - if (prevObjects){ - for( var j = 0; j < prevObjects.length; j++) { - if (prevObjects[j] === object) { - throw Error.invalidOperation(Sys.Res.cannotSerializeObjectWithCycle); - } - } - } - else { - prevObjects = new Array(); - } - try { - Array.add(prevObjects, object); - - if (Number.isInstanceOfType(object)){ - Sys.Serialization.JavaScriptSerializer._serializeNumberWithBuilder(object, stringBuilder); - } - else if (Boolean.isInstanceOfType(object)){ - Sys.Serialization.JavaScriptSerializer._serializeBooleanWithBuilder(object, stringBuilder); - } - else if (String.isInstanceOfType(object)){ - Sys.Serialization.JavaScriptSerializer._serializeStringWithBuilder(object, stringBuilder); - } - - else if (Array.isInstanceOfType(object)) { - stringBuilder.append('['); - - for (i = 0; i < object.length; ++i) { - if (i > 0) { - stringBuilder.append(','); - } - Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(object[i], stringBuilder,false,prevObjects); - } - stringBuilder.append(']'); - } - else { - if (Date.isInstanceOfType(object)) { - stringBuilder.append('"\\/Date('); - stringBuilder.append(object.getTime()); - stringBuilder.append(')\\/"'); - break; - } - var properties = []; - var propertyCount = 0; - for (var name in object) { - if (name.startsWith('$')) { - continue; - } - if (name === Sys.Serialization.JavaScriptSerializer._serverTypeFieldName && propertyCount !== 0){ - properties[propertyCount++] = properties[0]; - properties[0] = name; - } - else{ - properties[propertyCount++] = name; - } - } - if (sort) properties.sort(); - stringBuilder.append('{'); - var needComma = false; - - for (i=0; i - /// - /// - var e = Function._validateParams(arguments, [ - {name: "object", mayBeNull: true} - ]); - if (e) throw e; - var stringBuilder = new Sys.StringBuilder(); - Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(object, stringBuilder, false); - return stringBuilder.toString(); -} -Sys.Serialization.JavaScriptSerializer.deserialize = function Sys$Serialization$JavaScriptSerializer$deserialize(data, secure) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "data", type: String}, - {name: "secure", type: Boolean, optional: true} - ]); - if (e) throw e; - - if (data.length === 0) throw Error.argument('data', Sys.Res.cannotDeserializeEmptyString); - try { - var exp = data.replace(Sys.Serialization.JavaScriptSerializer._dateRegEx, "$1new Date($2)"); - - if (secure && Sys.Serialization.JavaScriptSerializer._jsonRegEx.test( - exp.replace(Sys.Serialization.JavaScriptSerializer._jsonStringRegEx, ''))) throw null; - return eval('(' + exp + ')'); - } - catch (e) { - throw Error.argument('data', Sys.Res.cannotDeserializeInvalidJson); - } -} -Type.registerNamespace('Sys.UI'); - -Sys.EventHandlerList = function Sys$EventHandlerList() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - this._list = {}; -} - function Sys$EventHandlerList$_addHandler(id, handler) { - Array.add(this._getEvent(id, true), handler); - } - function Sys$EventHandlerList$addHandler(id, handler) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "id", type: String}, - {name: "handler", type: Function} - ]); - if (e) throw e; - this._addHandler(id, handler); - } - function Sys$EventHandlerList$_removeHandler(id, handler) { - var evt = this._getEvent(id); - if (!evt) return; - Array.remove(evt, handler); - } - function Sys$EventHandlerList$removeHandler(id, handler) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "id", type: String}, - {name: "handler", type: Function} - ]); - if (e) throw e; - this._removeHandler(id, handler); - } - function Sys$EventHandlerList$getHandler(id) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "id", type: String} - ]); - if (e) throw e; - var evt = this._getEvent(id); - if (!evt || (evt.length === 0)) return null; - evt = Array.clone(evt); - return function(source, args) { - for (var i = 0, l = evt.length; i < l; i++) { - evt[i](source, args); - } - }; - } - function Sys$EventHandlerList$_getEvent(id, create) { - if (!this._list[id]) { - if (!create) return null; - this._list[id] = []; - } - return this._list[id]; - } -Sys.EventHandlerList.prototype = { - _addHandler: Sys$EventHandlerList$_addHandler, - addHandler: Sys$EventHandlerList$addHandler, - _removeHandler: Sys$EventHandlerList$_removeHandler, - removeHandler: Sys$EventHandlerList$removeHandler, - getHandler: Sys$EventHandlerList$getHandler, - _getEvent: Sys$EventHandlerList$_getEvent -} -Sys.EventHandlerList.registerClass('Sys.EventHandlerList'); -Sys.CommandEventArgs = function Sys$CommandEventArgs(commandName, commandArgument, commandSource) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "commandName", type: String}, - {name: "commandArgument", mayBeNull: true}, - {name: "commandSource", mayBeNull: true} - ]); - if (e) throw e; - Sys.CommandEventArgs.initializeBase(this); - this._commandName = commandName; - this._commandArgument = commandArgument; - this._commandSource = commandSource; -} - function Sys$CommandEventArgs$get_commandName() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._commandName; - } - function Sys$CommandEventArgs$get_commandArgument() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._commandArgument; - } - function Sys$CommandEventArgs$get_commandSource() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._commandSource; - } -Sys.CommandEventArgs.prototype = { - _commandName: null, - _commandArgument: null, - _commandSource: null, - get_commandName: Sys$CommandEventArgs$get_commandName, - get_commandArgument: Sys$CommandEventArgs$get_commandArgument, - get_commandSource: Sys$CommandEventArgs$get_commandSource -} -Sys.CommandEventArgs.registerClass("Sys.CommandEventArgs", Sys.CancelEventArgs); - -Sys.INotifyPropertyChange = function Sys$INotifyPropertyChange() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); -} - function Sys$INotifyPropertyChange$add_propertyChanged(handler) { - /// - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - throw Error.notImplemented(); - } - function Sys$INotifyPropertyChange$remove_propertyChanged(handler) { - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - throw Error.notImplemented(); - } -Sys.INotifyPropertyChange.prototype = { - add_propertyChanged: Sys$INotifyPropertyChange$add_propertyChanged, - remove_propertyChanged: Sys$INotifyPropertyChange$remove_propertyChanged -} -Sys.INotifyPropertyChange.registerInterface('Sys.INotifyPropertyChange'); - -Sys.PropertyChangedEventArgs = function Sys$PropertyChangedEventArgs(propertyName) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "propertyName", type: String} - ]); - if (e) throw e; - Sys.PropertyChangedEventArgs.initializeBase(this); - this._propertyName = propertyName; -} - - function Sys$PropertyChangedEventArgs$get_propertyName() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._propertyName; - } -Sys.PropertyChangedEventArgs.prototype = { - get_propertyName: Sys$PropertyChangedEventArgs$get_propertyName -} -Sys.PropertyChangedEventArgs.registerClass('Sys.PropertyChangedEventArgs', Sys.EventArgs); - -Sys.INotifyDisposing = function Sys$INotifyDisposing() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); -} - function Sys$INotifyDisposing$add_disposing(handler) { - /// - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - throw Error.notImplemented(); - } - function Sys$INotifyDisposing$remove_disposing(handler) { - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - throw Error.notImplemented(); - } -Sys.INotifyDisposing.prototype = { - add_disposing: Sys$INotifyDisposing$add_disposing, - remove_disposing: Sys$INotifyDisposing$remove_disposing -} -Sys.INotifyDisposing.registerInterface("Sys.INotifyDisposing"); - -Sys.Component = function Sys$Component() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (Sys.Application) Sys.Application.registerDisposableObject(this); -} - function Sys$Component$get_events() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (!this._events) { - this._events = new Sys.EventHandlerList(); - } - return this._events; - } - function Sys$Component$get_id() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._id; - } - function Sys$Component$set_id(value) { - var e = Function._validateParams(arguments, [{name: "value", type: String}]); - if (e) throw e; - if (this._idSet) throw Error.invalidOperation(Sys.Res.componentCantSetIdTwice); - this._idSet = true; - var oldId = this.get_id(); - if (oldId && Sys.Application.findComponent(oldId)) throw Error.invalidOperation(Sys.Res.componentCantSetIdAfterAddedToApp); - this._id = value; - } - function Sys$Component$get_isInitialized() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._initialized; - } - function Sys$Component$get_isUpdating() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._updating; - } - function Sys$Component$add_disposing(handler) { - /// - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this.get_events().addHandler("disposing", handler); - } - function Sys$Component$remove_disposing(handler) { - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this.get_events().removeHandler("disposing", handler); - } - function Sys$Component$add_propertyChanged(handler) { - /// - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this.get_events().addHandler("propertyChanged", handler); - } - function Sys$Component$remove_propertyChanged(handler) { - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this.get_events().removeHandler("propertyChanged", handler); - } - function Sys$Component$beginUpdate() { - this._updating = true; - } - function Sys$Component$dispose() { - if (this._events) { - var handler = this._events.getHandler("disposing"); - if (handler) { - handler(this, Sys.EventArgs.Empty); - } - } - delete this._events; - Sys.Application.unregisterDisposableObject(this); - Sys.Application.removeComponent(this); - } - function Sys$Component$endUpdate() { - this._updating = false; - if (!this._initialized) this.initialize(); - this.updated(); - } - function Sys$Component$initialize() { - this._initialized = true; - } - function Sys$Component$raisePropertyChanged(propertyName) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "propertyName", type: String} - ]); - if (e) throw e; - if (!this._events) return; - var handler = this._events.getHandler("propertyChanged"); - if (handler) { - handler(this, new Sys.PropertyChangedEventArgs(propertyName)); - } - } - function Sys$Component$updated() { - } -Sys.Component.prototype = { - _id: null, - _idSet: false, - _initialized: false, - _updating: false, - get_events: Sys$Component$get_events, - get_id: Sys$Component$get_id, - set_id: Sys$Component$set_id, - get_isInitialized: Sys$Component$get_isInitialized, - get_isUpdating: Sys$Component$get_isUpdating, - add_disposing: Sys$Component$add_disposing, - remove_disposing: Sys$Component$remove_disposing, - add_propertyChanged: Sys$Component$add_propertyChanged, - remove_propertyChanged: Sys$Component$remove_propertyChanged, - beginUpdate: Sys$Component$beginUpdate, - dispose: Sys$Component$dispose, - endUpdate: Sys$Component$endUpdate, - initialize: Sys$Component$initialize, - raisePropertyChanged: Sys$Component$raisePropertyChanged, - updated: Sys$Component$updated -} -Sys.Component.registerClass('Sys.Component', null, Sys.IDisposable, Sys.INotifyPropertyChange, Sys.INotifyDisposing); -function Sys$Component$_setProperties(target, properties) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "target"}, - {name: "properties"} - ]); - if (e) throw e; - var current; - var targetType = Object.getType(target); - var isObject = (targetType === Object) || (targetType === Sys.UI.DomElement); - var isComponent = Sys.Component.isInstanceOfType(target) && !target.get_isUpdating(); - if (isComponent) target.beginUpdate(); - for (var name in properties) { - var val = properties[name]; - var getter = isObject ? null : target["get_" + name]; - if (isObject || typeof(getter) !== 'function') { - var targetVal = target[name]; - if (!isObject && typeof(targetVal) === 'undefined') throw Error.invalidOperation(String.format(Sys.Res.propertyUndefined, name)); - if (!val || (typeof(val) !== 'object') || (isObject && !targetVal)) { - target[name] = val; - } - else { - Sys$Component$_setProperties(targetVal, val); - } - } - else { - var setter = target["set_" + name]; - if (typeof(setter) === 'function') { - setter.apply(target, [val]); - } - else if (val instanceof Array) { - current = getter.apply(target); - if (!(current instanceof Array)) throw new Error.invalidOperation(String.format(Sys.Res.propertyNotAnArray, name)); - for (var i = 0, j = current.length, l= val.length; i < l; i++, j++) { - current[j] = val[i]; - } - } - else if ((typeof(val) === 'object') && (Object.getType(val) === Object)) { - current = getter.apply(target); - if ((typeof(current) === 'undefined') || (current === null)) throw new Error.invalidOperation(String.format(Sys.Res.propertyNullOrUndefined, name)); - Sys$Component$_setProperties(current, val); - } - else { - throw new Error.invalidOperation(String.format(Sys.Res.propertyNotWritable, name)); - } - } - } - if (isComponent) target.endUpdate(); -} -function Sys$Component$_setReferences(component, references) { - for (var name in references) { - var setter = component["set_" + name]; - var reference = $find(references[name]); - if (typeof(setter) !== 'function') throw new Error.invalidOperation(String.format(Sys.Res.propertyNotWritable, name)); - if (!reference) throw Error.invalidOperation(String.format(Sys.Res.referenceNotFound, references[name])); - setter.apply(component, [reference]); - } -} -var $create = Sys.Component.create = function Sys$Component$create(type, properties, events, references, element) { - /// - /// - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "type", type: Type}, - {name: "properties", mayBeNull: true, optional: true}, - {name: "events", mayBeNull: true, optional: true}, - {name: "references", mayBeNull: true, optional: true}, - {name: "element", mayBeNull: true, domElement: true, optional: true} - ]); - if (e) throw e; - if (!type.inheritsFrom(Sys.Component)) { - throw Error.argument('type', String.format(Sys.Res.createNotComponent, type.getName())); - } - if (type.inheritsFrom(Sys.UI.Behavior) || type.inheritsFrom(Sys.UI.Control)) { - if (!element) throw Error.argument('element', Sys.Res.createNoDom); - } - else if (element) throw Error.argument('element', Sys.Res.createComponentOnDom); - var component = (element ? new type(element): new type()); - var app = Sys.Application; - var creatingComponents = app.get_isCreatingComponents(); - component.beginUpdate(); - if (properties) { - Sys$Component$_setProperties(component, properties); - } - if (events) { - for (var name in events) { - if (!(component["add_" + name] instanceof Function)) throw new Error.invalidOperation(String.format(Sys.Res.undefinedEvent, name)); - if (!(events[name] instanceof Function)) throw new Error.invalidOperation(Sys.Res.eventHandlerNotFunction); - component["add_" + name](events[name]); - } - } - if (component.get_id()) { - app.addComponent(component); - } - if (creatingComponents) { - app._createdComponents[app._createdComponents.length] = component; - if (references) { - app._addComponentToSecondPass(component, references); - } - else { - component.endUpdate(); - } - } - else { - if (references) { - Sys$Component$_setReferences(component, references); - } - component.endUpdate(); - } - return component; -} - -Sys.UI.MouseButton = function Sys$UI$MouseButton() { - /// - /// - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); -} -Sys.UI.MouseButton.prototype = { - leftButton: 0, - middleButton: 1, - rightButton: 2 -} -Sys.UI.MouseButton.registerEnum("Sys.UI.MouseButton"); - -Sys.UI.Key = function Sys$UI$Key() { - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); -} -Sys.UI.Key.prototype = { - backspace: 8, - tab: 9, - enter: 13, - esc: 27, - space: 32, - pageUp: 33, - pageDown: 34, - end: 35, - home: 36, - left: 37, - up: 38, - right: 39, - down: 40, - del: 127 -} -Sys.UI.Key.registerEnum("Sys.UI.Key"); - -Sys.UI.Point = function Sys$UI$Point(x, y) { - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "x", type: Number, integer: true}, - {name: "y", type: Number, integer: true} - ]); - if (e) throw e; - this.x = x; - this.y = y; -} -Sys.UI.Point.registerClass('Sys.UI.Point'); - -Sys.UI.Bounds = function Sys$UI$Bounds(x, y, width, height) { - /// - /// - /// - /// - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "x", type: Number, integer: true}, - {name: "y", type: Number, integer: true}, - {name: "width", type: Number, integer: true}, - {name: "height", type: Number, integer: true} - ]); - if (e) throw e; - this.x = x; - this.y = y; - this.height = height; - this.width = width; -} -Sys.UI.Bounds.registerClass('Sys.UI.Bounds'); - -Sys.UI.DomEvent = function Sys$UI$DomEvent(eventObject) { - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "eventObject"} - ]); - if (e) throw e; - var ev = eventObject; - var etype = this.type = ev.type.toLowerCase(); - this.rawEvent = ev; - this.altKey = ev.altKey; - if (typeof(ev.button) !== 'undefined') { - this.button = (typeof(ev.which) !== 'undefined') ? ev.button : - (ev.button === 4) ? Sys.UI.MouseButton.middleButton : - (ev.button === 2) ? Sys.UI.MouseButton.rightButton : - Sys.UI.MouseButton.leftButton; - } - if (etype === 'keypress') { - this.charCode = ev.charCode || ev.keyCode; - } - else if (ev.keyCode && (ev.keyCode === 46)) { - this.keyCode = 127; - } - else { - this.keyCode = ev.keyCode; - } - this.clientX = ev.clientX; - this.clientY = ev.clientY; - this.ctrlKey = ev.ctrlKey; - this.target = ev.target ? ev.target : ev.srcElement; - if (!etype.startsWith('key')) { - if ((typeof(ev.offsetX) !== 'undefined') && (typeof(ev.offsetY) !== 'undefined')) { - this.offsetX = ev.offsetX; - this.offsetY = ev.offsetY; - } - else if (this.target && (this.target.nodeType !== 3) && (typeof(ev.clientX) === 'number')) { - var loc = Sys.UI.DomElement.getLocation(this.target); - var w = Sys.UI.DomElement._getWindow(this.target); - this.offsetX = (w.pageXOffset || 0) + ev.clientX - loc.x; - this.offsetY = (w.pageYOffset || 0) + ev.clientY - loc.y; - } - } - this.screenX = ev.screenX; - this.screenY = ev.screenY; - this.shiftKey = ev.shiftKey; -} - function Sys$UI$DomEvent$preventDefault() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (this.rawEvent.preventDefault) { - this.rawEvent.preventDefault(); - } - else if (window.event) { - this.rawEvent.returnValue = false; - } - } - function Sys$UI$DomEvent$stopPropagation() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (this.rawEvent.stopPropagation) { - this.rawEvent.stopPropagation(); - } - else if (window.event) { - this.rawEvent.cancelBubble = true; - } - } -Sys.UI.DomEvent.prototype = { - preventDefault: Sys$UI$DomEvent$preventDefault, - stopPropagation: Sys$UI$DomEvent$stopPropagation -} -Sys.UI.DomEvent.registerClass('Sys.UI.DomEvent'); -var $addHandler = Sys.UI.DomEvent.addHandler = function Sys$UI$DomEvent$addHandler(element, eventName, handler, autoRemove) { - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element"}, - {name: "eventName", type: String}, - {name: "handler", type: Function}, - {name: "autoRemove", type: Boolean, optional: true} - ]); - if (e) throw e; - Sys.UI.DomEvent._ensureDomNode(element); - if (eventName === "error") throw Error.invalidOperation(Sys.Res.addHandlerCantBeUsedForError); - if (!element._events) { - element._events = {}; - } - var eventCache = element._events[eventName]; - if (!eventCache) { - element._events[eventName] = eventCache = []; - } - var browserHandler; - if (element.addEventListener) { - browserHandler = function(e) { - return handler.call(element, new Sys.UI.DomEvent(e)); - } - element.addEventListener(eventName, browserHandler, false); - } - else if (element.attachEvent) { - browserHandler = function() { - var e = {}; - try {e = Sys.UI.DomElement._getWindow(element).event} catch(ex) {} - return handler.call(element, new Sys.UI.DomEvent(e)); - } - element.attachEvent('on' + eventName, browserHandler); - } - eventCache[eventCache.length] = {handler: handler, browserHandler: browserHandler, autoRemove: autoRemove }; - if (autoRemove) { - var d = element.dispose; - if (d !== Sys.UI.DomEvent._disposeHandlers) { - element.dispose = Sys.UI.DomEvent._disposeHandlers; - if (typeof(d) !== "undefined") { - element._chainDispose = d; - } - } - } -} -var $addHandlers = Sys.UI.DomEvent.addHandlers = function Sys$UI$DomEvent$addHandlers(element, events, handlerOwner, autoRemove) { - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element"}, - {name: "events", type: Object}, - {name: "handlerOwner", optional: true}, - {name: "autoRemove", type: Boolean, optional: true} - ]); - if (e) throw e; - Sys.UI.DomEvent._ensureDomNode(element); - for (var name in events) { - var handler = events[name]; - if (typeof(handler) !== 'function') throw Error.invalidOperation(Sys.Res.cantAddNonFunctionhandler); - if (handlerOwner) { - handler = Function.createDelegate(handlerOwner, handler); - } - $addHandler(element, name, handler, autoRemove || false); - } -} -var $clearHandlers = Sys.UI.DomEvent.clearHandlers = function Sys$UI$DomEvent$clearHandlers(element) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element"} - ]); - if (e) throw e; - Sys.UI.DomEvent._ensureDomNode(element); - Sys.UI.DomEvent._clearHandlers(element, false); -} -Sys.UI.DomEvent._clearHandlers = function Sys$UI$DomEvent$_clearHandlers(element, autoRemoving) { - if (element._events) { - var cache = element._events; - for (var name in cache) { - var handlers = cache[name]; - for (var i = handlers.length - 1; i >= 0; i--) { - var entry = handlers[i]; - if (!autoRemoving || entry.autoRemove) { - $removeHandler(element, name, entry.handler); - } - } - } - element._events = null; - } -} -Sys.UI.DomEvent._disposeHandlers = function Sys$UI$DomEvent$_disposeHandlers() { - Sys.UI.DomEvent._clearHandlers(this, true); - var d = this._chainDispose, type = typeof(d); - if (type !== "undefined") { - this.dispose = d; - this._chainDispose = null; - if (type === "function") { - this.dispose(); - } - } -} -var $removeHandler = Sys.UI.DomEvent.removeHandler = function Sys$UI$DomEvent$removeHandler(element, eventName, handler) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element"}, - {name: "eventName", type: String}, - {name: "handler", type: Function} - ]); - if (e) throw e; - Sys.UI.DomEvent._removeHandler(element, eventName, handler); -} -Sys.UI.DomEvent._removeHandler = function Sys$UI$DomEvent$_removeHandler(element, eventName, handler) { - Sys.UI.DomEvent._ensureDomNode(element); - var browserHandler = null; - if ((typeof(element._events) !== 'object') || !element._events) throw Error.invalidOperation(Sys.Res.eventHandlerInvalid); - var cache = element._events[eventName]; - if (!(cache instanceof Array)) throw Error.invalidOperation(Sys.Res.eventHandlerInvalid); - for (var i = 0, l = cache.length; i < l; i++) { - if (cache[i].handler === handler) { - browserHandler = cache[i].browserHandler; - break; - } - } - if (typeof(browserHandler) !== 'function') throw Error.invalidOperation(Sys.Res.eventHandlerInvalid); - if (element.removeEventListener) { - element.removeEventListener(eventName, browserHandler, false); - } - else if (element.detachEvent) { - element.detachEvent('on' + eventName, browserHandler); - } - cache.splice(i, 1); -} -Sys.UI.DomEvent._ensureDomNode = function Sys$UI$DomEvent$_ensureDomNode(element) { - if (element.tagName && (element.tagName.toUpperCase() === "SCRIPT")) return; - - var doc = element.ownerDocument || element.document || element; - if ((typeof(element.document) !== 'object') && (element != doc) && (typeof(element.nodeType) !== 'number')) { - throw Error.argument("element", Sys.Res.argumentDomNode); - } -} - -Sys.UI.DomElement = function Sys$UI$DomElement() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); -} -Sys.UI.DomElement.registerClass('Sys.UI.DomElement'); -Sys.UI.DomElement.addCssClass = function Sys$UI$DomElement$addCssClass(element, className) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true}, - {name: "className", type: String} - ]); - if (e) throw e; - if (!Sys.UI.DomElement.containsCssClass(element, className)) { - if (element.className === '') { - element.className = className; - } - else { - element.className += ' ' + className; - } - } -} -Sys.UI.DomElement.containsCssClass = function Sys$UI$DomElement$containsCssClass(element, className) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true}, - {name: "className", type: String} - ]); - if (e) throw e; - return Array.contains(element.className.split(' '), className); -} -Sys.UI.DomElement.getBounds = function Sys$UI$DomElement$getBounds(element) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true} - ]); - if (e) throw e; - var offset = Sys.UI.DomElement.getLocation(element); - return new Sys.UI.Bounds(offset.x, offset.y, element.offsetWidth || 0, element.offsetHeight || 0); -} -var $get = Sys.UI.DomElement.getElementById = function Sys$UI$DomElement$getElementById(id, element) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "id", type: String}, - {name: "element", mayBeNull: true, domElement: true, optional: true} - ]); - if (e) throw e; - if (!element) return document.getElementById(id); - if (element.getElementById) return element.getElementById(id); - var nodeQueue = []; - var childNodes = element.childNodes; - for (var i = 0; i < childNodes.length; i++) { - var node = childNodes[i]; - if (node.nodeType == 1) { - nodeQueue[nodeQueue.length] = node; - } - } - while (nodeQueue.length) { - node = nodeQueue.shift(); - if (node.id == id) { - return node; - } - childNodes = node.childNodes; - for (i = 0; i < childNodes.length; i++) { - node = childNodes[i]; - if (node.nodeType == 1) { - nodeQueue[nodeQueue.length] = node; - } - } - } - return null; -} -if (document.documentElement.getBoundingClientRect) { - Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true} - ]); - if (e) throw e; - if (element.self || element.nodeType === 9) return new Sys.UI.Point(0,0); - var clientRect = element.getBoundingClientRect(); - if (!clientRect) { - return new Sys.UI.Point(0,0); - } - var documentElement = element.ownerDocument.documentElement, - offsetX = Math.floor(clientRect.left + 0.5) + documentElement.scrollLeft, - offsetY = Math.floor(clientRect.top + 0.5) + documentElement.scrollTop; - if (Sys.Browser.agent === Sys.Browser.InternetExplorer) { - try { - var f = element.ownerDocument.parentWindow.frameElement || null; - if (f) { - var offset = (f.frameBorder === "0" || f.frameBorder === "no") ? 2 : 0; - offsetX += offset; - offsetY += offset; - } - } - catch(ex) { - } - if (Sys.Browser.version <= 7) { - - var multiplier, before, rect, d = document.createElement("div"); - d.style.cssText = "position:absolute !important;left:0px !important;right:0px !important;height:0px !important;width:1px !important;display:hidden !important"; - try { - before = document.body.childNodes[0]; - document.body.insertBefore(d, before); - rect = d.getBoundingClientRect(); - document.body.removeChild(d); - multiplier = (rect.right - rect.left); - } - catch (e) { - } - if (multiplier && (multiplier !== 1)) { - offsetX = Math.floor(offsetX / multiplier); - offsetY = Math.floor(offsetY / multiplier); - } - } - if ((document.documentMode || 0) < 8) { - offsetX -= 2; - offsetY -= 2; - } - } - return new Sys.UI.Point(offsetX, offsetY); - } -} -else if (Sys.Browser.agent === Sys.Browser.Safari) { - Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true} - ]); - if (e) throw e; - if ((element.window && (element.window === element)) || element.nodeType === 9) return new Sys.UI.Point(0,0); - var offsetX = 0, offsetY = 0, - parent, - previous = null, - previousStyle = null, - currentStyle; - for (parent = element; parent; previous = parent, previousStyle = currentStyle, parent = parent.offsetParent) { - currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); - var tagName = parent.tagName ? parent.tagName.toUpperCase() : null; - if ((parent.offsetLeft || parent.offsetTop) && - ((tagName !== "BODY") || (!previousStyle || previousStyle.position !== "absolute"))) { - offsetX += parent.offsetLeft; - offsetY += parent.offsetTop; - } - if (previous && Sys.Browser.version >= 3) { - offsetX += parseInt(currentStyle.borderLeftWidth); - offsetY += parseInt(currentStyle.borderTopWidth); - } - } - currentStyle = Sys.UI.DomElement._getCurrentStyle(element); - var elementPosition = currentStyle ? currentStyle.position : null; - if (!elementPosition || (elementPosition !== "absolute")) { - for (parent = element.parentNode; parent; parent = parent.parentNode) { - tagName = parent.tagName ? parent.tagName.toUpperCase() : null; - if ((tagName !== "BODY") && (tagName !== "HTML") && (parent.scrollLeft || parent.scrollTop)) { - offsetX -= (parent.scrollLeft || 0); - offsetY -= (parent.scrollTop || 0); - } - currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); - var parentPosition = currentStyle ? currentStyle.position : null; - if (parentPosition && (parentPosition === "absolute")) break; - } - } - return new Sys.UI.Point(offsetX, offsetY); - } -} -else { - Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true} - ]); - if (e) throw e; - if ((element.window && (element.window === element)) || element.nodeType === 9) return new Sys.UI.Point(0,0); - var offsetX = 0, offsetY = 0, - parent, - previous = null, - previousStyle = null, - currentStyle = null; - for (parent = element; parent; previous = parent, previousStyle = currentStyle, parent = parent.offsetParent) { - var tagName = parent.tagName ? parent.tagName.toUpperCase() : null; - currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); - if ((parent.offsetLeft || parent.offsetTop) && - !((tagName === "BODY") && - (!previousStyle || previousStyle.position !== "absolute"))) { - offsetX += parent.offsetLeft; - offsetY += parent.offsetTop; - } - if (previous !== null && currentStyle) { - if ((tagName !== "TABLE") && (tagName !== "TD") && (tagName !== "HTML")) { - offsetX += parseInt(currentStyle.borderLeftWidth) || 0; - offsetY += parseInt(currentStyle.borderTopWidth) || 0; - } - if (tagName === "TABLE" && - (currentStyle.position === "relative" || currentStyle.position === "absolute")) { - offsetX += parseInt(currentStyle.marginLeft) || 0; - offsetY += parseInt(currentStyle.marginTop) || 0; - } - } - } - currentStyle = Sys.UI.DomElement._getCurrentStyle(element); - var elementPosition = currentStyle ? currentStyle.position : null; - if (!elementPosition || (elementPosition !== "absolute")) { - for (parent = element.parentNode; parent; parent = parent.parentNode) { - tagName = parent.tagName ? parent.tagName.toUpperCase() : null; - if ((tagName !== "BODY") && (tagName !== "HTML") && (parent.scrollLeft || parent.scrollTop)) { - offsetX -= (parent.scrollLeft || 0); - offsetY -= (parent.scrollTop || 0); - currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); - if (currentStyle) { - offsetX += parseInt(currentStyle.borderLeftWidth) || 0; - offsetY += parseInt(currentStyle.borderTopWidth) || 0; - } - } - } - } - return new Sys.UI.Point(offsetX, offsetY); - } -} -Sys.UI.DomElement.isDomElement = function Sys$UI$DomElement$isDomElement(obj) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "obj"} - ]); - if (e) throw e; - return Sys._isDomElement(obj); -} -Sys.UI.DomElement.removeCssClass = function Sys$UI$DomElement$removeCssClass(element, className) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true}, - {name: "className", type: String} - ]); - if (e) throw e; - var currentClassName = ' ' + element.className + ' '; - var index = currentClassName.indexOf(' ' + className + ' '); - if (index >= 0) { - element.className = (currentClassName.substr(0, index) + ' ' + - currentClassName.substring(index + className.length + 1, currentClassName.length)).trim(); - } -} -Sys.UI.DomElement.resolveElement = function Sys$UI$DomElement$resolveElement(elementOrElementId, containerElement) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "elementOrElementId", mayBeNull: true}, - {name: "containerElement", mayBeNull: true, domElement: true, optional: true} - ]); - if (e) throw e; - var el = elementOrElementId; - if (!el) return null; - if (typeof(el) === "string") { - el = Sys.UI.DomElement.getElementById(el, containerElement); - if (!el) { - throw Error.argument("elementOrElementId", String.format(Sys.Res.elementNotFound, elementOrElementId)); - } - } - else if(!Sys.UI.DomElement.isDomElement(el)) { - throw Error.argument("elementOrElementId", Sys.Res.expectedElementOrId); - } - return el; -} -Sys.UI.DomElement.raiseBubbleEvent = function Sys$UI$DomElement$raiseBubbleEvent(source, args) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "source", domElement: true}, - {name: "args", type: Sys.EventArgs} - ]); - if (e) throw e; - var target = source; - while (target) { - var control = target.control; - if (control && control.onBubbleEvent && control.raiseBubbleEvent) { - Sys.UI.DomElement._raiseBubbleEventFromControl(control, source, args); - return; - } - target = target.parentNode; - } -} -Sys.UI.DomElement._raiseBubbleEventFromControl = function Sys$UI$DomElement$_raiseBubbleEventFromControl(control, source, args) { - if (!control.onBubbleEvent(source, args)) { - control._raiseBubbleEvent(source, args); - } -} -Sys.UI.DomElement.setLocation = function Sys$UI$DomElement$setLocation(element, x, y) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true}, - {name: "x", type: Number, integer: true}, - {name: "y", type: Number, integer: true} - ]); - if (e) throw e; - var style = element.style; - style.position = 'absolute'; - style.left = x + "px"; - style.top = y + "px"; -} -Sys.UI.DomElement.toggleCssClass = function Sys$UI$DomElement$toggleCssClass(element, className) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true}, - {name: "className", type: String} - ]); - if (e) throw e; - if (Sys.UI.DomElement.containsCssClass(element, className)) { - Sys.UI.DomElement.removeCssClass(element, className); - } - else { - Sys.UI.DomElement.addCssClass(element, className); - } -} -Sys.UI.DomElement.getVisibilityMode = function Sys$UI$DomElement$getVisibilityMode(element) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true} - ]); - if (e) throw e; - return (element._visibilityMode === Sys.UI.VisibilityMode.hide) ? - Sys.UI.VisibilityMode.hide : - Sys.UI.VisibilityMode.collapse; -} -Sys.UI.DomElement.setVisibilityMode = function Sys$UI$DomElement$setVisibilityMode(element, value) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true}, - {name: "value", type: Sys.UI.VisibilityMode} - ]); - if (e) throw e; - Sys.UI.DomElement._ensureOldDisplayMode(element); - if (element._visibilityMode !== value) { - element._visibilityMode = value; - if (Sys.UI.DomElement.getVisible(element) === false) { - if (element._visibilityMode === Sys.UI.VisibilityMode.hide) { - element.style.display = element._oldDisplayMode; - } - else { - element.style.display = 'none'; - } - } - element._visibilityMode = value; - } -} -Sys.UI.DomElement.getVisible = function Sys$UI$DomElement$getVisible(element) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true} - ]); - if (e) throw e; - var style = element.currentStyle || Sys.UI.DomElement._getCurrentStyle(element); - if (!style) return true; - return (style.visibility !== 'hidden') && (style.display !== 'none'); -} -Sys.UI.DomElement.setVisible = function Sys$UI$DomElement$setVisible(element, value) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true}, - {name: "value", type: Boolean} - ]); - if (e) throw e; - if (value !== Sys.UI.DomElement.getVisible(element)) { - Sys.UI.DomElement._ensureOldDisplayMode(element); - element.style.visibility = value ? 'visible' : 'hidden'; - if (value || (element._visibilityMode === Sys.UI.VisibilityMode.hide)) { - element.style.display = element._oldDisplayMode; - } - else { - element.style.display = 'none'; - } - } -} -Sys.UI.DomElement._ensureOldDisplayMode = function Sys$UI$DomElement$_ensureOldDisplayMode(element) { - if (!element._oldDisplayMode) { - var style = element.currentStyle || Sys.UI.DomElement._getCurrentStyle(element); - element._oldDisplayMode = style ? style.display : null; - if (!element._oldDisplayMode || element._oldDisplayMode === 'none') { - switch(element.tagName.toUpperCase()) { - case 'DIV': case 'P': case 'ADDRESS': case 'BLOCKQUOTE': case 'BODY': case 'COL': - case 'COLGROUP': case 'DD': case 'DL': case 'DT': case 'FIELDSET': case 'FORM': - case 'H1': case 'H2': case 'H3': case 'H4': case 'H5': case 'H6': case 'HR': - case 'IFRAME': case 'LEGEND': case 'OL': case 'PRE': case 'TABLE': case 'TD': - case 'TH': case 'TR': case 'UL': - element._oldDisplayMode = 'block'; - break; - case 'LI': - element._oldDisplayMode = 'list-item'; - break; - default: - element._oldDisplayMode = 'inline'; - } - } - } -} -Sys.UI.DomElement._getWindow = function Sys$UI$DomElement$_getWindow(element) { - var doc = element.ownerDocument || element.document || element; - return doc.defaultView || doc.parentWindow; -} -Sys.UI.DomElement._getCurrentStyle = function Sys$UI$DomElement$_getCurrentStyle(element) { - if (element.nodeType === 3) return null; - var w = Sys.UI.DomElement._getWindow(element); - if (element.documentElement) element = element.documentElement; - var computedStyle = (w && (element !== w) && w.getComputedStyle) ? - w.getComputedStyle(element, null) : - element.currentStyle || element.style; - if (!computedStyle && (Sys.Browser.agent === Sys.Browser.Safari) && element.style) { - var oldDisplay = element.style.display; - var oldPosition = element.style.position; - element.style.position = 'absolute'; - element.style.display = 'block'; - var style = w.getComputedStyle(element, null); - element.style.display = oldDisplay; - element.style.position = oldPosition; - computedStyle = {}; - for (var n in style) { - computedStyle[n] = style[n]; - } - computedStyle.display = 'none'; - } - return computedStyle; -} - -Sys.IContainer = function Sys$IContainer() { - throw Error.notImplemented(); -} - function Sys$IContainer$addComponent(component) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "component", type: Sys.Component} - ]); - if (e) throw e; - throw Error.notImplemented(); - } - function Sys$IContainer$removeComponent(component) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "component", type: Sys.Component} - ]); - if (e) throw e; - throw Error.notImplemented(); - } - function Sys$IContainer$findComponent(id) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "id", type: String} - ]); - if (e) throw e; - throw Error.notImplemented(); - } - function Sys$IContainer$getComponents() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); - } -Sys.IContainer.prototype = { - addComponent: Sys$IContainer$addComponent, - removeComponent: Sys$IContainer$removeComponent, - findComponent: Sys$IContainer$findComponent, - getComponents: Sys$IContainer$getComponents -} -Sys.IContainer.registerInterface("Sys.IContainer"); - -Sys.ApplicationLoadEventArgs = function Sys$ApplicationLoadEventArgs(components, isPartialLoad) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "components", type: Array, elementType: Sys.Component}, - {name: "isPartialLoad", type: Boolean} - ]); - if (e) throw e; - Sys.ApplicationLoadEventArgs.initializeBase(this); - this._components = components; - this._isPartialLoad = isPartialLoad; -} - - function Sys$ApplicationLoadEventArgs$get_components() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._components; - } - function Sys$ApplicationLoadEventArgs$get_isPartialLoad() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._isPartialLoad; - } -Sys.ApplicationLoadEventArgs.prototype = { - get_components: Sys$ApplicationLoadEventArgs$get_components, - get_isPartialLoad: Sys$ApplicationLoadEventArgs$get_isPartialLoad -} -Sys.ApplicationLoadEventArgs.registerClass('Sys.ApplicationLoadEventArgs', Sys.EventArgs); - -Sys._Application = function Sys$_Application() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - Sys._Application.initializeBase(this); - this._disposableObjects = []; - this._components = {}; - this._createdComponents = []; - this._secondPassComponents = []; - this._unloadHandlerDelegate = Function.createDelegate(this, this._unloadHandler); - Sys.UI.DomEvent.addHandler(window, "unload", this._unloadHandlerDelegate); - this._domReady(); -} - function Sys$_Application$get_isCreatingComponents() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._creatingComponents; - } - function Sys$_Application$get_isDisposing() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._disposing; - } - function Sys$_Application$add_init(handler) { - /// - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - if (this._initialized) { - handler(this, Sys.EventArgs.Empty); - } - else { - this.get_events().addHandler("init", handler); - } - } - function Sys$_Application$remove_init(handler) { - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this.get_events().removeHandler("init", handler); - } - function Sys$_Application$add_load(handler) { - /// - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this.get_events().addHandler("load", handler); - } - function Sys$_Application$remove_load(handler) { - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this.get_events().removeHandler("load", handler); - } - function Sys$_Application$add_unload(handler) { - /// - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this.get_events().addHandler("unload", handler); - } - function Sys$_Application$remove_unload(handler) { - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this.get_events().removeHandler("unload", handler); - } - function Sys$_Application$addComponent(component) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "component", type: Sys.Component} - ]); - if (e) throw e; - var id = component.get_id(); - if (!id) throw Error.invalidOperation(Sys.Res.cantAddWithoutId); - if (typeof(this._components[id]) !== 'undefined') throw Error.invalidOperation(String.format(Sys.Res.appDuplicateComponent, id)); - this._components[id] = component; - } - function Sys$_Application$beginCreateComponents() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - this._creatingComponents = true; - } - function Sys$_Application$dispose() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (!this._disposing) { - this._disposing = true; - if (this._timerCookie) { - window.clearTimeout(this._timerCookie); - delete this._timerCookie; - } - if (this._endRequestHandler) { - Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(this._endRequestHandler); - delete this._endRequestHandler; - } - if (this._beginRequestHandler) { - Sys.WebForms.PageRequestManager.getInstance().remove_beginRequest(this._beginRequestHandler); - delete this._beginRequestHandler; - } - if (window.pageUnload) { - window.pageUnload(this, Sys.EventArgs.Empty); - } - var unloadHandler = this.get_events().getHandler("unload"); - if (unloadHandler) { - unloadHandler(this, Sys.EventArgs.Empty); - } - var disposableObjects = Array.clone(this._disposableObjects); - for (var i = 0, l = disposableObjects.length; i < l; i++) { - var object = disposableObjects[i]; - if (typeof(object) !== "undefined") { - object.dispose(); - } - } - Array.clear(this._disposableObjects); - Sys.UI.DomEvent.removeHandler(window, "unload", this._unloadHandlerDelegate); - if (Sys._ScriptLoader) { - var sl = Sys._ScriptLoader.getInstance(); - if(sl) { - sl.dispose(); - } - } - Sys._Application.callBaseMethod(this, 'dispose'); - } - } - function Sys$_Application$disposeElement(element, childNodesOnly) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element"}, - {name: "childNodesOnly", type: Boolean} - ]); - if (e) throw e; - if (element.nodeType === 1) { - var children = element.getElementsByTagName("*"); - for (var i = children.length - 1; i >= 0; i--) { - this._disposeElementInternal(children[i]); - } - if (!childNodesOnly) { - this._disposeElementInternal(element); - } - } - } - function Sys$_Application$endCreateComponents() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - var components = this._secondPassComponents; - for (var i = 0, l = components.length; i < l; i++) { - var component = components[i].component; - Sys$Component$_setReferences(component, components[i].references); - component.endUpdate(); - } - this._secondPassComponents = []; - this._creatingComponents = false; - } - function Sys$_Application$findComponent(id, parent) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "id", type: String}, - {name: "parent", mayBeNull: true, optional: true} - ]); - if (e) throw e; - return (parent ? - ((Sys.IContainer.isInstanceOfType(parent)) ? - parent.findComponent(id) : - parent[id] || null) : - Sys.Application._components[id] || null); - } - function Sys$_Application$getComponents() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - var res = []; - var components = this._components; - for (var name in components) { - res[res.length] = components[name]; - } - return res; - } - function Sys$_Application$initialize() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if(!this.get_isInitialized() && !this._disposing) { - Sys._Application.callBaseMethod(this, 'initialize'); - this._raiseInit(); - if (this.get_stateString) { - if (Sys.WebForms && Sys.WebForms.PageRequestManager) { - this._beginRequestHandler = Function.createDelegate(this, this._onPageRequestManagerBeginRequest); - Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(this._beginRequestHandler); - this._endRequestHandler = Function.createDelegate(this, this._onPageRequestManagerEndRequest); - Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this._endRequestHandler); - } - var loadedEntry = this.get_stateString(); - if (loadedEntry !== this._currentEntry) { - this._navigate(loadedEntry); - } - else { - this._ensureHistory(); - } - } - this.raiseLoad(); - } - } - function Sys$_Application$notifyScriptLoaded() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - } - function Sys$_Application$registerDisposableObject(object) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "object", type: Sys.IDisposable} - ]); - if (e) throw e; - if (!this._disposing) { - var objects = this._disposableObjects, - i = objects.length; - objects[i] = object; - object.__msdisposeindex = i; - } - } - function Sys$_Application$raiseLoad() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - var h = this.get_events().getHandler("load"); - var args = new Sys.ApplicationLoadEventArgs(Array.clone(this._createdComponents), !!this._loaded); - this._loaded = true; - if (h) { - h(this, args); - } - if (window.pageLoad) { - window.pageLoad(this, args); - } - this._createdComponents = []; - } - function Sys$_Application$removeComponent(component) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "component", type: Sys.Component} - ]); - if (e) throw e; - var id = component.get_id(); - if (id) delete this._components[id]; - } - function Sys$_Application$unregisterDisposableObject(object) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "object", type: Sys.IDisposable} - ]); - if (e) throw e; - if (!this._disposing) { - var i = object.__msdisposeindex; - if (typeof(i) === "number") { - var disposableObjects = this._disposableObjects; - delete disposableObjects[i]; - delete object.__msdisposeindex; - if (++this._deleteCount > 1000) { - var newArray = []; - for (var j = 0, l = disposableObjects.length; j < l; j++) { - object = disposableObjects[j]; - if (typeof(object) !== "undefined") { - object.__msdisposeindex = newArray.length; - newArray.push(object); - } - } - this._disposableObjects = newArray; - this._deleteCount = 0; - } - } - } - } - function Sys$_Application$_addComponentToSecondPass(component, references) { - this._secondPassComponents[this._secondPassComponents.length] = {component: component, references: references}; - } - function Sys$_Application$_disposeComponents(list) { - if (list) { - for (var i = list.length - 1; i >= 0; i--) { - var item = list[i]; - if (typeof(item.dispose) === "function") { - item.dispose(); - } - } - } - } - function Sys$_Application$_disposeElementInternal(element) { - var d = element.dispose; - if (d && typeof(d) === "function") { - element.dispose(); - } - else { - var c = element.control; - if (c && typeof(c.dispose) === "function") { - c.dispose(); - } - } - var list = element._behaviors; - if (list) { - this._disposeComponents(list); - } - list = element._components; - if (list) { - this._disposeComponents(list); - element._components = null; - } - } - function Sys$_Application$_domReady() { - var check, er, app = this; - function init() { app.initialize(); } - var onload = function() { - Sys.UI.DomEvent.removeHandler(window, "load", onload); - init(); - } - Sys.UI.DomEvent.addHandler(window, "load", onload); - - if (document.addEventListener) { - try { - document.addEventListener("DOMContentLoaded", check = function() { - document.removeEventListener("DOMContentLoaded", check, false); - init(); - }, false); - } - catch (er) { } - } - else if (document.attachEvent) { - if ((window == window.top) && document.documentElement.doScroll) { - var timeout, el = document.createElement("div"); - check = function() { - try { - el.doScroll("left"); - } - catch (er) { - timeout = window.setTimeout(check, 0); - return; - } - el = null; - init(); - } - check(); - } - else { - document.attachEvent("onreadystatechange", check = function() { - if (document.readyState === "complete") { - document.detachEvent("onreadystatechange", check); - init(); - } - }); - } - } - } - function Sys$_Application$_raiseInit() { - var handler = this.get_events().getHandler("init"); - if (handler) { - this.beginCreateComponents(); - handler(this, Sys.EventArgs.Empty); - this.endCreateComponents(); - } - } - function Sys$_Application$_unloadHandler(event) { - this.dispose(); - } -Sys._Application.prototype = { - _creatingComponents: false, - _disposing: false, - _deleteCount: 0, - get_isCreatingComponents: Sys$_Application$get_isCreatingComponents, - get_isDisposing: Sys$_Application$get_isDisposing, - add_init: Sys$_Application$add_init, - remove_init: Sys$_Application$remove_init, - add_load: Sys$_Application$add_load, - remove_load: Sys$_Application$remove_load, - add_unload: Sys$_Application$add_unload, - remove_unload: Sys$_Application$remove_unload, - addComponent: Sys$_Application$addComponent, - beginCreateComponents: Sys$_Application$beginCreateComponents, - dispose: Sys$_Application$dispose, - disposeElement: Sys$_Application$disposeElement, - endCreateComponents: Sys$_Application$endCreateComponents, - findComponent: Sys$_Application$findComponent, - getComponents: Sys$_Application$getComponents, - initialize: Sys$_Application$initialize, - notifyScriptLoaded: Sys$_Application$notifyScriptLoaded, - registerDisposableObject: Sys$_Application$registerDisposableObject, - raiseLoad: Sys$_Application$raiseLoad, - removeComponent: Sys$_Application$removeComponent, - unregisterDisposableObject: Sys$_Application$unregisterDisposableObject, - _addComponentToSecondPass: Sys$_Application$_addComponentToSecondPass, - _disposeComponents: Sys$_Application$_disposeComponents, - _disposeElementInternal: Sys$_Application$_disposeElementInternal, - _domReady: Sys$_Application$_domReady, - _raiseInit: Sys$_Application$_raiseInit, - _unloadHandler: Sys$_Application$_unloadHandler -} -Sys._Application.registerClass('Sys._Application', Sys.Component, Sys.IContainer); -Sys.Application = new Sys._Application(); -var $find = Sys.Application.findComponent; - -Sys.UI.Behavior = function Sys$UI$Behavior(element) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true} - ]); - if (e) throw e; - Sys.UI.Behavior.initializeBase(this); - this._element = element; - var behaviors = element._behaviors; - if (!behaviors) { - element._behaviors = [this]; - } - else { - behaviors[behaviors.length] = this; - } -} - function Sys$UI$Behavior$get_element() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._element; - } - function Sys$UI$Behavior$get_id() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - var baseId = Sys.UI.Behavior.callBaseMethod(this, 'get_id'); - if (baseId) return baseId; - if (!this._element || !this._element.id) return ''; - return this._element.id + '$' + this.get_name(); - } - function Sys$UI$Behavior$get_name() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (this._name) return this._name; - var name = Object.getTypeName(this); - var i = name.lastIndexOf('.'); - if (i !== -1) name = name.substr(i + 1); - if (!this.get_isInitialized()) this._name = name; - return name; - } - function Sys$UI$Behavior$set_name(value) { - var e = Function._validateParams(arguments, [{name: "value", type: String}]); - if (e) throw e; - if ((value === '') || (value.charAt(0) === ' ') || (value.charAt(value.length - 1) === ' ')) - throw Error.argument('value', Sys.Res.invalidId); - if (typeof(this._element[value]) !== 'undefined') - throw Error.invalidOperation(String.format(Sys.Res.behaviorDuplicateName, value)); - if (this.get_isInitialized()) throw Error.invalidOperation(Sys.Res.cantSetNameAfterInit); - this._name = value; - } - function Sys$UI$Behavior$initialize() { - Sys.UI.Behavior.callBaseMethod(this, 'initialize'); - var name = this.get_name(); - if (name) this._element[name] = this; - } - function Sys$UI$Behavior$dispose() { - Sys.UI.Behavior.callBaseMethod(this, 'dispose'); - var e = this._element; - if (e) { - var name = this.get_name(); - if (name) { - e[name] = null; - } - var behaviors = e._behaviors; - Array.remove(behaviors, this); - if (behaviors.length === 0) { - e._behaviors = null; - } - delete this._element; - } - } -Sys.UI.Behavior.prototype = { - _name: null, - get_element: Sys$UI$Behavior$get_element, - get_id: Sys$UI$Behavior$get_id, - get_name: Sys$UI$Behavior$get_name, - set_name: Sys$UI$Behavior$set_name, - initialize: Sys$UI$Behavior$initialize, - dispose: Sys$UI$Behavior$dispose -} -Sys.UI.Behavior.registerClass('Sys.UI.Behavior', Sys.Component); -Sys.UI.Behavior.getBehaviorByName = function Sys$UI$Behavior$getBehaviorByName(element, name) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true}, - {name: "name", type: String} - ]); - if (e) throw e; - var b = element[name]; - return (b && Sys.UI.Behavior.isInstanceOfType(b)) ? b : null; -} -Sys.UI.Behavior.getBehaviors = function Sys$UI$Behavior$getBehaviors(element) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true} - ]); - if (e) throw e; - if (!element._behaviors) return []; - return Array.clone(element._behaviors); -} -Sys.UI.Behavior.getBehaviorsByType = function Sys$UI$Behavior$getBehaviorsByType(element, type) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true}, - {name: "type", type: Type} - ]); - if (e) throw e; - var behaviors = element._behaviors; - var results = []; - if (behaviors) { - for (var i = 0, l = behaviors.length; i < l; i++) { - if (type.isInstanceOfType(behaviors[i])) { - results[results.length] = behaviors[i]; - } - } - } - return results; -} - -Sys.UI.VisibilityMode = function Sys$UI$VisibilityMode() { - /// - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); -} -Sys.UI.VisibilityMode.prototype = { - hide: 0, - collapse: 1 -} -Sys.UI.VisibilityMode.registerEnum("Sys.UI.VisibilityMode"); - -Sys.UI.Control = function Sys$UI$Control(element) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "element", domElement: true} - ]); - if (e) throw e; - if (typeof(element.control) !== 'undefined') throw Error.invalidOperation(Sys.Res.controlAlreadyDefined); - Sys.UI.Control.initializeBase(this); - this._element = element; - element.control = this; - var role = this.get_role(); - if (role) { - element.setAttribute("role", role); - } -} - function Sys$UI$Control$get_element() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._element; - } - function Sys$UI$Control$get_id() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (!this._element) return ''; - return this._element.id; - } - function Sys$UI$Control$set_id(value) { - var e = Function._validateParams(arguments, [{name: "value", type: String}]); - if (e) throw e; - throw Error.invalidOperation(Sys.Res.cantSetId); - } - function Sys$UI$Control$get_parent() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (this._parent) return this._parent; - if (!this._element) return null; - - var parentElement = this._element.parentNode; - while (parentElement) { - if (parentElement.control) { - return parentElement.control; - } - parentElement = parentElement.parentNode; - } - return null; - } - function Sys$UI$Control$set_parent(value) { - var e = Function._validateParams(arguments, [{name: "value", type: Sys.UI.Control}]); - if (e) throw e; - if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); - var parents = [this]; - var current = value; - while (current) { - if (Array.contains(parents, current)) throw Error.invalidOperation(Sys.Res.circularParentChain); - parents[parents.length] = current; - current = current.get_parent(); - } - this._parent = value; - } - function Sys$UI$Control$get_role() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return null; - } - function Sys$UI$Control$get_visibilityMode() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); - return Sys.UI.DomElement.getVisibilityMode(this._element); - } - function Sys$UI$Control$set_visibilityMode(value) { - var e = Function._validateParams(arguments, [{name: "value", type: Sys.UI.VisibilityMode}]); - if (e) throw e; - if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); - Sys.UI.DomElement.setVisibilityMode(this._element, value); - } - function Sys$UI$Control$get_visible() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); - return Sys.UI.DomElement.getVisible(this._element); - } - function Sys$UI$Control$set_visible(value) { - var e = Function._validateParams(arguments, [{name: "value", type: Boolean}]); - if (e) throw e; - if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); - Sys.UI.DomElement.setVisible(this._element, value) - } - function Sys$UI$Control$addCssClass(className) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "className", type: String} - ]); - if (e) throw e; - if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); - Sys.UI.DomElement.addCssClass(this._element, className); - } - function Sys$UI$Control$dispose() { - Sys.UI.Control.callBaseMethod(this, 'dispose'); - if (this._element) { - this._element.control = null; - delete this._element; - } - if (this._parent) delete this._parent; - } - function Sys$UI$Control$onBubbleEvent(source, args) { - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "source"}, - {name: "args", type: Sys.EventArgs} - ]); - if (e) throw e; - return false; - } - function Sys$UI$Control$raiseBubbleEvent(source, args) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "source"}, - {name: "args", type: Sys.EventArgs} - ]); - if (e) throw e; - this._raiseBubbleEvent(source, args); - } - function Sys$UI$Control$_raiseBubbleEvent(source, args) { - var currentTarget = this.get_parent(); - while (currentTarget) { - if (currentTarget.onBubbleEvent(source, args)) { - return; - } - currentTarget = currentTarget.get_parent(); - } - } - function Sys$UI$Control$removeCssClass(className) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "className", type: String} - ]); - if (e) throw e; - if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); - Sys.UI.DomElement.removeCssClass(this._element, className); - } - function Sys$UI$Control$toggleCssClass(className) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "className", type: String} - ]); - if (e) throw e; - if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); - Sys.UI.DomElement.toggleCssClass(this._element, className); - } -Sys.UI.Control.prototype = { - _parent: null, - _visibilityMode: Sys.UI.VisibilityMode.hide, - get_element: Sys$UI$Control$get_element, - get_id: Sys$UI$Control$get_id, - set_id: Sys$UI$Control$set_id, - get_parent: Sys$UI$Control$get_parent, - set_parent: Sys$UI$Control$set_parent, - get_role: Sys$UI$Control$get_role, - get_visibilityMode: Sys$UI$Control$get_visibilityMode, - set_visibilityMode: Sys$UI$Control$set_visibilityMode, - get_visible: Sys$UI$Control$get_visible, - set_visible: Sys$UI$Control$set_visible, - addCssClass: Sys$UI$Control$addCssClass, - dispose: Sys$UI$Control$dispose, - onBubbleEvent: Sys$UI$Control$onBubbleEvent, - raiseBubbleEvent: Sys$UI$Control$raiseBubbleEvent, - _raiseBubbleEvent: Sys$UI$Control$_raiseBubbleEvent, - removeCssClass: Sys$UI$Control$removeCssClass, - toggleCssClass: Sys$UI$Control$toggleCssClass -} -Sys.UI.Control.registerClass('Sys.UI.Control', Sys.Component); -Sys.HistoryEventArgs = function Sys$HistoryEventArgs(state) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "state", type: Object} - ]); - if (e) throw e; - Sys.HistoryEventArgs.initializeBase(this); - this._state = state; -} - function Sys$HistoryEventArgs$get_state() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._state; - } -Sys.HistoryEventArgs.prototype = { - get_state: Sys$HistoryEventArgs$get_state -} -Sys.HistoryEventArgs.registerClass('Sys.HistoryEventArgs', Sys.EventArgs); -Sys.Application._appLoadHandler = null; -Sys.Application._beginRequestHandler = null; -Sys.Application._clientId = null; -Sys.Application._currentEntry = ''; -Sys.Application._endRequestHandler = null; -Sys.Application._history = null; -Sys.Application._enableHistory = false; -Sys.Application._historyEnabledInScriptManager = false; -Sys.Application._historyFrame = null; -Sys.Application._historyInitialized = false; -Sys.Application._historyPointIsNew = false; -Sys.Application._ignoreTimer = false; -Sys.Application._initialState = null; -Sys.Application._state = {}; -Sys.Application._timerCookie = 0; -Sys.Application._timerHandler = null; -Sys.Application._uniqueId = null; -Sys._Application.prototype.get_stateString = function Sys$_Application$get_stateString() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - var hash = null; - - if (Sys.Browser.agent === Sys.Browser.Firefox) { - var href = window.location.href; - var hashIndex = href.indexOf('#'); - if (hashIndex !== -1) { - hash = href.substring(hashIndex + 1); - } - else { - hash = ""; - } - return hash; - } - else { - hash = window.location.hash; - } - - if ((hash.length > 0) && (hash.charAt(0) === '#')) { - hash = hash.substring(1); - } - return hash; -}; -Sys._Application.prototype.get_enableHistory = function Sys$_Application$get_enableHistory() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._enableHistory; -}; -Sys._Application.prototype.set_enableHistory = function Sys$_Application$set_enableHistory(value) { - if (this._initialized && !this._initializing) { - throw Error.invalidOperation(Sys.Res.historyCannotEnableHistory); - } - else if (this._historyEnabledInScriptManager && !value) { - throw Error.invalidOperation(Sys.Res.invalidHistorySettingCombination); - } - this._enableHistory = value; -}; -Sys._Application.prototype.add_navigate = function Sys$_Application$add_navigate(handler) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "handler", type: Function} - ]); - if (e) throw e; - this.get_events().addHandler("navigate", handler); -}; -Sys._Application.prototype.remove_navigate = function Sys$_Application$remove_navigate(handler) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "handler", type: Function} - ]); - if (e) throw e; - this.get_events().removeHandler("navigate", handler); -}; -Sys._Application.prototype.addHistoryPoint = function Sys$_Application$addHistoryPoint(state, title) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "state", type: Object}, - {name: "title", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - if (!this._enableHistory) throw Error.invalidOperation(Sys.Res.historyCannotAddHistoryPointWithHistoryDisabled); - for (var n in state) { - var v = state[n]; - var t = typeof(v); - if ((v !== null) && ((t === 'object') || (t === 'function') || (t === 'undefined'))) { - throw Error.argument('state', Sys.Res.stateMustBeStringDictionary); - } - } - this._ensureHistory(); - var initialState = this._state; - for (var key in state) { - var value = state[key]; - if (value === null) { - if (typeof(initialState[key]) !== 'undefined') { - delete initialState[key]; - } - } - else { - initialState[key] = value; - } - } - var entry = this._serializeState(initialState); - this._historyPointIsNew = true; - this._setState(entry, title); - this._raiseNavigate(); -}; -Sys._Application.prototype.setServerId = function Sys$_Application$setServerId(clientId, uniqueId) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "clientId", type: String}, - {name: "uniqueId", type: String} - ]); - if (e) throw e; - this._clientId = clientId; - this._uniqueId = uniqueId; -}; -Sys._Application.prototype.setServerState = function Sys$_Application$setServerState(value) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "value", type: String} - ]); - if (e) throw e; - this._ensureHistory(); - this._state.__s = value; - this._updateHiddenField(value); -}; -Sys._Application.prototype._deserializeState = function Sys$_Application$_deserializeState(entry) { - var result = {}; - entry = entry || ''; - var serverSeparator = entry.indexOf('&&'); - if ((serverSeparator !== -1) && (serverSeparator + 2 < entry.length)) { - result.__s = entry.substr(serverSeparator + 2); - entry = entry.substr(0, serverSeparator); - } - var tokens = entry.split('&'); - for (var i = 0, l = tokens.length; i < l; i++) { - var token = tokens[i]; - var equal = token.indexOf('='); - if ((equal !== -1) && (equal + 1 < token.length)) { - var name = token.substr(0, equal); - var value = token.substr(equal + 1); - result[name] = decodeURIComponent(value); - } - } - return result; -}; -Sys._Application.prototype._enableHistoryInScriptManager = function Sys$_Application$_enableHistoryInScriptManager() { - this._enableHistory = true; - this._historyEnabledInScriptManager = true; -}; -Sys._Application.prototype._ensureHistory = function Sys$_Application$_ensureHistory() { - if (!this._historyInitialized && this._enableHistory) { - if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.documentMode < 8)) { - this._historyFrame = document.getElementById('__historyFrame'); - if (!this._historyFrame) throw Error.invalidOperation(Sys.Res.historyMissingFrame); - this._ignoreIFrame = true; - } - this._timerHandler = Function.createDelegate(this, this._onIdle); - this._timerCookie = window.setTimeout(this._timerHandler, 100); - - try { - this._initialState = this._deserializeState(this.get_stateString()); - } catch(e) {} - - this._historyInitialized = true; - } -}; -Sys._Application.prototype._navigate = function Sys$_Application$_navigate(entry) { - this._ensureHistory(); - var state = this._deserializeState(entry); - - if (this._uniqueId) { - var oldServerEntry = this._state.__s || ''; - var newServerEntry = state.__s || ''; - if (newServerEntry !== oldServerEntry) { - this._updateHiddenField(newServerEntry); - __doPostBack(this._uniqueId, newServerEntry); - this._state = state; - return; - } - } - this._setState(entry); - this._state = state; - this._raiseNavigate(); -}; -Sys._Application.prototype._onIdle = function Sys$_Application$_onIdle() { - delete this._timerCookie; - - var entry = this.get_stateString(); - if (entry !== this._currentEntry) { - if (!this._ignoreTimer) { - this._historyPointIsNew = false; - this._navigate(entry); - } - } - else { - this._ignoreTimer = false; - } - this._timerCookie = window.setTimeout(this._timerHandler, 100); -}; -Sys._Application.prototype._onIFrameLoad = function Sys$_Application$_onIFrameLoad(entry) { - this._ensureHistory(); - if (!this._ignoreIFrame) { - this._historyPointIsNew = false; - this._navigate(entry); - } - this._ignoreIFrame = false; -}; -Sys._Application.prototype._onPageRequestManagerBeginRequest = function Sys$_Application$_onPageRequestManagerBeginRequest(sender, args) { - this._ignoreTimer = true; -}; -Sys._Application.prototype._onPageRequestManagerEndRequest = function Sys$_Application$_onPageRequestManagerEndRequest(sender, args) { - var dataItem = args.get_dataItems()[this._clientId]; - var eventTarget = document.getElementById("__EVENTTARGET"); - if (eventTarget && eventTarget.value === this._uniqueId) { - eventTarget.value = ''; - } - if (typeof(dataItem) !== 'undefined') { - this.setServerState(dataItem); - this._historyPointIsNew = true; - } - else { - this._ignoreTimer = false; - } - var entry = this._serializeState(this._state); - if (entry !== this._currentEntry) { - this._ignoreTimer = true; - this._setState(entry); - this._raiseNavigate(); - } -}; -Sys._Application.prototype._raiseNavigate = function Sys$_Application$_raiseNavigate() { - var h = this.get_events().getHandler("navigate"); - var stateClone = {}; - for (var key in this._state) { - if (key !== '__s') { - stateClone[key] = this._state[key]; - } - } - var args = new Sys.HistoryEventArgs(stateClone); - if (h) { - h(this, args); - } - var err; - try { - if ((Sys.Browser.agent === Sys.Browser.Firefox) && window.location.hash && - (!window.frameElement || window.top.location.hash)) { - window.history.go(0); - } - } - catch(err) { - } -}; -Sys._Application.prototype._serializeState = function Sys$_Application$_serializeState(state) { - var serialized = []; - for (var key in state) { - var value = state[key]; - if (key === '__s') { - var serverState = value; - } - else { - if (key.indexOf('=') !== -1) throw Error.argument('state', Sys.Res.stateFieldNameInvalid); - serialized[serialized.length] = key + '=' + encodeURIComponent(value); - } - } - return serialized.join('&') + (serverState ? '&&' + serverState : ''); -}; -Sys._Application.prototype._setState = function Sys$_Application$_setState(entry, title) { - if (this._enableHistory) { - entry = entry || ''; - if (entry !== this._currentEntry) { - if (window.theForm) { - var action = window.theForm.action; - var hashIndex = action.indexOf('#'); - window.theForm.action = ((hashIndex !== -1) ? action.substring(0, hashIndex) : action) + '#' + entry; - } - - if (this._historyFrame && this._historyPointIsNew) { - this._ignoreIFrame = true; - var frameDoc = this._historyFrame.contentWindow.document; - frameDoc.open("javascript:''"); - frameDoc.write("" + (title || document.title) + - "parent.Sys.Application._onIFrameLoad(" + - Sys.Serialization.JavaScriptSerializer.serialize(entry) + - ");"); - frameDoc.close(); - } - this._ignoreTimer = false; - this._currentEntry = entry; - if (this._historyFrame || this._historyPointIsNew) { - var currentHash = this.get_stateString(); - if (entry !== currentHash) { - var loc = document.location; - if (loc.href.length - loc.hash.length + entry.length > 1024) { - throw Error.invalidOperation(Sys.Res.urlMustBeLessThan1024chars); - } - window.location.hash = entry; - this._currentEntry = this.get_stateString(); - if ((typeof(title) !== 'undefined') && (title !== null)) { - document.title = title; - } - } - } - this._historyPointIsNew = false; - } - } -}; -Sys._Application.prototype._updateHiddenField = function Sys$_Application$_updateHiddenField(value) { - if (this._clientId) { - var serverStateField = document.getElementById(this._clientId); - if (serverStateField) { - serverStateField.value = value; - } - } -}; - -if (!window.XMLHttpRequest) { - window.XMLHttpRequest = function window$XMLHttpRequest() { - var progIDs = [ 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP' ]; - for (var i = 0, l = progIDs.length; i < l; i++) { - try { - return new ActiveXObject(progIDs[i]); - } - catch (ex) { - } - } - return null; - } -} -Type.registerNamespace('Sys.Net'); - -Sys.Net.WebRequestExecutor = function Sys$Net$WebRequestExecutor() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - this._webRequest = null; - this._resultObject = null; -} - function Sys$Net$WebRequestExecutor$get_webRequest() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._webRequest; - } - function Sys$Net$WebRequestExecutor$_set_webRequest(value) { - if (this.get_started()) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallOnceStarted, 'set_webRequest')); - } - this._webRequest = value; - } - function Sys$Net$WebRequestExecutor$get_started() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); - } - function Sys$Net$WebRequestExecutor$get_responseAvailable() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); - } - function Sys$Net$WebRequestExecutor$get_timedOut() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); - } - function Sys$Net$WebRequestExecutor$get_aborted() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); - } - function Sys$Net$WebRequestExecutor$get_responseData() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); - } - function Sys$Net$WebRequestExecutor$get_statusCode() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); - } - function Sys$Net$WebRequestExecutor$get_statusText() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); - } - function Sys$Net$WebRequestExecutor$get_xml() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); - } - function Sys$Net$WebRequestExecutor$get_object() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (!this._resultObject) { - this._resultObject = Sys.Serialization.JavaScriptSerializer.deserialize(this.get_responseData()); - } - return this._resultObject; - } - function Sys$Net$WebRequestExecutor$executeRequest() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); - } - function Sys$Net$WebRequestExecutor$abort() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); - } - function Sys$Net$WebRequestExecutor$getResponseHeader(header) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "header", type: String} - ]); - if (e) throw e; - throw Error.notImplemented(); - } - function Sys$Net$WebRequestExecutor$getAllResponseHeaders() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - throw Error.notImplemented(); - } -Sys.Net.WebRequestExecutor.prototype = { - get_webRequest: Sys$Net$WebRequestExecutor$get_webRequest, - _set_webRequest: Sys$Net$WebRequestExecutor$_set_webRequest, - get_started: Sys$Net$WebRequestExecutor$get_started, - get_responseAvailable: Sys$Net$WebRequestExecutor$get_responseAvailable, - get_timedOut: Sys$Net$WebRequestExecutor$get_timedOut, - get_aborted: Sys$Net$WebRequestExecutor$get_aborted, - get_responseData: Sys$Net$WebRequestExecutor$get_responseData, - get_statusCode: Sys$Net$WebRequestExecutor$get_statusCode, - get_statusText: Sys$Net$WebRequestExecutor$get_statusText, - get_xml: Sys$Net$WebRequestExecutor$get_xml, - get_object: Sys$Net$WebRequestExecutor$get_object, - executeRequest: Sys$Net$WebRequestExecutor$executeRequest, - abort: Sys$Net$WebRequestExecutor$abort, - getResponseHeader: Sys$Net$WebRequestExecutor$getResponseHeader, - getAllResponseHeaders: Sys$Net$WebRequestExecutor$getAllResponseHeaders -} -Sys.Net.WebRequestExecutor.registerClass('Sys.Net.WebRequestExecutor'); - -Sys.Net.XMLDOM = function Sys$Net$XMLDOM(markup) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "markup", type: String} - ]); - if (e) throw e; - if (!window.DOMParser) { - var progIDs = [ 'Msxml2.DOMDocument.3.0', 'Msxml2.DOMDocument' ]; - for (var i = 0, l = progIDs.length; i < l; i++) { - try { - var xmlDOM = new ActiveXObject(progIDs[i]); - xmlDOM.async = false; - xmlDOM.loadXML(markup); - xmlDOM.setProperty('SelectionLanguage', 'XPath'); - return xmlDOM; - } - catch (ex) { - } - } - } - else { - try { - var domParser = new window.DOMParser(); - return domParser.parseFromString(markup, 'text/xml'); - } - catch (ex) { - } - } - return null; -} -Sys.Net.XMLHttpExecutor = function Sys$Net$XMLHttpExecutor() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - Sys.Net.XMLHttpExecutor.initializeBase(this); - var _this = this; - this._xmlHttpRequest = null; - this._webRequest = null; - this._responseAvailable = false; - this._timedOut = false; - this._timer = null; - this._aborted = false; - this._started = false; - this._onReadyStateChange = (function () { - - if (_this._xmlHttpRequest.readyState === 4 ) { - try { - if (typeof(_this._xmlHttpRequest.status) === "undefined") { - return; - } - } - catch(ex) { - return; - } - - _this._clearTimer(); - _this._responseAvailable = true; - _this._webRequest.completed(Sys.EventArgs.Empty); - if (_this._xmlHttpRequest != null) { - _this._xmlHttpRequest.onreadystatechange = Function.emptyMethod; - _this._xmlHttpRequest = null; - } - } - }); - this._clearTimer = (function() { - if (_this._timer != null) { - window.clearTimeout(_this._timer); - _this._timer = null; - } - }); - this._onTimeout = (function() { - if (!_this._responseAvailable) { - _this._clearTimer(); - _this._timedOut = true; - _this._xmlHttpRequest.onreadystatechange = Function.emptyMethod; - _this._xmlHttpRequest.abort(); - _this._webRequest.completed(Sys.EventArgs.Empty); - _this._xmlHttpRequest = null; - } - }); -} - function Sys$Net$XMLHttpExecutor$get_timedOut() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._timedOut; - } - function Sys$Net$XMLHttpExecutor$get_started() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._started; - } - function Sys$Net$XMLHttpExecutor$get_responseAvailable() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._responseAvailable; - } - function Sys$Net$XMLHttpExecutor$get_aborted() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._aborted; - } - function Sys$Net$XMLHttpExecutor$executeRequest() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - this._webRequest = this.get_webRequest(); - if (this._started) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallOnceStarted, 'executeRequest')); - } - if (this._webRequest === null) { - throw Error.invalidOperation(Sys.Res.nullWebRequest); - } - var body = this._webRequest.get_body(); - var headers = this._webRequest.get_headers(); - this._xmlHttpRequest = new XMLHttpRequest(); - this._xmlHttpRequest.onreadystatechange = this._onReadyStateChange; - var verb = this._webRequest.get_httpVerb(); - this._xmlHttpRequest.open(verb, this._webRequest.getResolvedUrl(), true ); - this._xmlHttpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest"); - if (headers) { - for (var header in headers) { - var val = headers[header]; - if (typeof(val) !== "function") - this._xmlHttpRequest.setRequestHeader(header, val); - } - } - if (verb.toLowerCase() === "post") { - if ((headers === null) || !headers['Content-Type']) { - this._xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8'); - } - if (!body) { - body = ""; - } - } - var timeout = this._webRequest.get_timeout(); - if (timeout > 0) { - this._timer = window.setTimeout(Function.createDelegate(this, this._onTimeout), timeout); - } - this._xmlHttpRequest.send(body); - this._started = true; - } - function Sys$Net$XMLHttpExecutor$getResponseHeader(header) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "header", type: String} - ]); - if (e) throw e; - if (!this._responseAvailable) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'getResponseHeader')); - } - if (!this._xmlHttpRequest) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'getResponseHeader')); - } - var result; - try { - result = this._xmlHttpRequest.getResponseHeader(header); - } catch (e) { - } - if (!result) result = ""; - return result; - } - function Sys$Net$XMLHttpExecutor$getAllResponseHeaders() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (!this._responseAvailable) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'getAllResponseHeaders')); - } - if (!this._xmlHttpRequest) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'getAllResponseHeaders')); - } - return this._xmlHttpRequest.getAllResponseHeaders(); - } - function Sys$Net$XMLHttpExecutor$get_responseData() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (!this._responseAvailable) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_responseData')); - } - if (!this._xmlHttpRequest) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_responseData')); - } - return this._xmlHttpRequest.responseText; - } - function Sys$Net$XMLHttpExecutor$get_statusCode() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (!this._responseAvailable) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_statusCode')); - } - if (!this._xmlHttpRequest) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_statusCode')); - } - var result = 0; - try { - result = this._xmlHttpRequest.status; - } - catch(ex) { - } - return result; - } - function Sys$Net$XMLHttpExecutor$get_statusText() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (!this._responseAvailable) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_statusText')); - } - if (!this._xmlHttpRequest) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_statusText')); - } - return this._xmlHttpRequest.statusText; - } - function Sys$Net$XMLHttpExecutor$get_xml() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (!this._responseAvailable) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_xml')); - } - if (!this._xmlHttpRequest) { - throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_xml')); - } - var xml = this._xmlHttpRequest.responseXML; - if (!xml || !xml.documentElement) { - xml = Sys.Net.XMLDOM(this._xmlHttpRequest.responseText); - if (!xml || !xml.documentElement) - return null; - } - else if (navigator.userAgent.indexOf('MSIE') !== -1) { - xml.setProperty('SelectionLanguage', 'XPath'); - } - if (xml.documentElement.namespaceURI === "http://www.mozilla.org/newlayout/xml/parsererror.xml" && - xml.documentElement.tagName === "parsererror") { - return null; - } - - if (xml.documentElement.firstChild && xml.documentElement.firstChild.tagName === "parsererror") { - return null; - } - - return xml; - } - function Sys$Net$XMLHttpExecutor$abort() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (!this._started) { - throw Error.invalidOperation(Sys.Res.cannotAbortBeforeStart); - } - if (this._aborted || this._responseAvailable || this._timedOut) - return; - this._aborted = true; - this._clearTimer(); - if (this._xmlHttpRequest && !this._responseAvailable) { - this._xmlHttpRequest.onreadystatechange = Function.emptyMethod; - this._xmlHttpRequest.abort(); - - this._xmlHttpRequest = null; - this._webRequest.completed(Sys.EventArgs.Empty); - } - } -Sys.Net.XMLHttpExecutor.prototype = { - get_timedOut: Sys$Net$XMLHttpExecutor$get_timedOut, - get_started: Sys$Net$XMLHttpExecutor$get_started, - get_responseAvailable: Sys$Net$XMLHttpExecutor$get_responseAvailable, - get_aborted: Sys$Net$XMLHttpExecutor$get_aborted, - executeRequest: Sys$Net$XMLHttpExecutor$executeRequest, - getResponseHeader: Sys$Net$XMLHttpExecutor$getResponseHeader, - getAllResponseHeaders: Sys$Net$XMLHttpExecutor$getAllResponseHeaders, - get_responseData: Sys$Net$XMLHttpExecutor$get_responseData, - get_statusCode: Sys$Net$XMLHttpExecutor$get_statusCode, - get_statusText: Sys$Net$XMLHttpExecutor$get_statusText, - get_xml: Sys$Net$XMLHttpExecutor$get_xml, - abort: Sys$Net$XMLHttpExecutor$abort -} -Sys.Net.XMLHttpExecutor.registerClass('Sys.Net.XMLHttpExecutor', Sys.Net.WebRequestExecutor); - -Sys.Net._WebRequestManager = function Sys$Net$_WebRequestManager() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - this._defaultTimeout = 0; - this._defaultExecutorType = "Sys.Net.XMLHttpExecutor"; -} - function Sys$Net$_WebRequestManager$add_invokingRequest(handler) { - /// - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this._get_eventHandlerList().addHandler("invokingRequest", handler); - } - function Sys$Net$_WebRequestManager$remove_invokingRequest(handler) { - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this._get_eventHandlerList().removeHandler("invokingRequest", handler); - } - function Sys$Net$_WebRequestManager$add_completedRequest(handler) { - /// - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this._get_eventHandlerList().addHandler("completedRequest", handler); - } - function Sys$Net$_WebRequestManager$remove_completedRequest(handler) { - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this._get_eventHandlerList().removeHandler("completedRequest", handler); - } - function Sys$Net$_WebRequestManager$_get_eventHandlerList() { - if (!this._events) { - this._events = new Sys.EventHandlerList(); - } - return this._events; - } - function Sys$Net$_WebRequestManager$get_defaultTimeout() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._defaultTimeout; - } - function Sys$Net$_WebRequestManager$set_defaultTimeout(value) { - var e = Function._validateParams(arguments, [{name: "value", type: Number}]); - if (e) throw e; - if (value < 0) { - throw Error.argumentOutOfRange("value", value, Sys.Res.invalidTimeout); - } - this._defaultTimeout = value; - } - function Sys$Net$_WebRequestManager$get_defaultExecutorType() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._defaultExecutorType; - } - function Sys$Net$_WebRequestManager$set_defaultExecutorType(value) { - var e = Function._validateParams(arguments, [{name: "value", type: String}]); - if (e) throw e; - this._defaultExecutorType = value; - } - function Sys$Net$_WebRequestManager$executeRequest(webRequest) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "webRequest", type: Sys.Net.WebRequest} - ]); - if (e) throw e; - var executor = webRequest.get_executor(); - if (!executor) { - var failed = false; - try { - var executorType = eval(this._defaultExecutorType); - executor = new executorType(); - } catch (e) { - failed = true; - } - if (failed || !Sys.Net.WebRequestExecutor.isInstanceOfType(executor) || !executor) { - throw Error.argument("defaultExecutorType", String.format(Sys.Res.invalidExecutorType, this._defaultExecutorType)); - } - webRequest.set_executor(executor); - } - if (executor.get_aborted()) { - return; - } - var evArgs = new Sys.Net.NetworkRequestEventArgs(webRequest); - var handler = this._get_eventHandlerList().getHandler("invokingRequest"); - if (handler) { - handler(this, evArgs); - } - if (!evArgs.get_cancel()) { - executor.executeRequest(); - } - } -Sys.Net._WebRequestManager.prototype = { - add_invokingRequest: Sys$Net$_WebRequestManager$add_invokingRequest, - remove_invokingRequest: Sys$Net$_WebRequestManager$remove_invokingRequest, - add_completedRequest: Sys$Net$_WebRequestManager$add_completedRequest, - remove_completedRequest: Sys$Net$_WebRequestManager$remove_completedRequest, - _get_eventHandlerList: Sys$Net$_WebRequestManager$_get_eventHandlerList, - get_defaultTimeout: Sys$Net$_WebRequestManager$get_defaultTimeout, - set_defaultTimeout: Sys$Net$_WebRequestManager$set_defaultTimeout, - get_defaultExecutorType: Sys$Net$_WebRequestManager$get_defaultExecutorType, - set_defaultExecutorType: Sys$Net$_WebRequestManager$set_defaultExecutorType, - executeRequest: Sys$Net$_WebRequestManager$executeRequest -} -Sys.Net._WebRequestManager.registerClass('Sys.Net._WebRequestManager'); -Sys.Net.WebRequestManager = new Sys.Net._WebRequestManager(); - -Sys.Net.NetworkRequestEventArgs = function Sys$Net$NetworkRequestEventArgs(webRequest) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "webRequest", type: Sys.Net.WebRequest} - ]); - if (e) throw e; - Sys.Net.NetworkRequestEventArgs.initializeBase(this); - this._webRequest = webRequest; -} - function Sys$Net$NetworkRequestEventArgs$get_webRequest() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._webRequest; - } -Sys.Net.NetworkRequestEventArgs.prototype = { - get_webRequest: Sys$Net$NetworkRequestEventArgs$get_webRequest -} -Sys.Net.NetworkRequestEventArgs.registerClass('Sys.Net.NetworkRequestEventArgs', Sys.CancelEventArgs); - -Sys.Net.WebRequest = function Sys$Net$WebRequest() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - this._url = ""; - this._headers = { }; - this._body = null; - this._userContext = null; - this._httpVerb = null; - this._executor = null; - this._invokeCalled = false; - this._timeout = 0; -} - function Sys$Net$WebRequest$add_completed(handler) { - /// - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this._get_eventHandlerList().addHandler("completed", handler); - } - function Sys$Net$WebRequest$remove_completed(handler) { - var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); - if (e) throw e; - this._get_eventHandlerList().removeHandler("completed", handler); - } - function Sys$Net$WebRequest$completed(eventArgs) { - /// - /// - var e = Function._validateParams(arguments, [ - {name: "eventArgs", type: Sys.EventArgs} - ]); - if (e) throw e; - var handler = Sys.Net.WebRequestManager._get_eventHandlerList().getHandler("completedRequest"); - if (handler) { - handler(this._executor, eventArgs); - } - handler = this._get_eventHandlerList().getHandler("completed"); - if (handler) { - handler(this._executor, eventArgs); - } - } - function Sys$Net$WebRequest$_get_eventHandlerList() { - if (!this._events) { - this._events = new Sys.EventHandlerList(); - } - return this._events; - } - function Sys$Net$WebRequest$get_url() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._url; - } - function Sys$Net$WebRequest$set_url(value) { - var e = Function._validateParams(arguments, [{name: "value", type: String}]); - if (e) throw e; - this._url = value; - } - function Sys$Net$WebRequest$get_headers() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._headers; - } - function Sys$Net$WebRequest$get_httpVerb() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (this._httpVerb === null) { - if (this._body === null) { - return "GET"; - } - return "POST"; - } - return this._httpVerb; - } - function Sys$Net$WebRequest$set_httpVerb(value) { - var e = Function._validateParams(arguments, [{name: "value", type: String}]); - if (e) throw e; - if (value.length === 0) { - throw Error.argument('value', Sys.Res.invalidHttpVerb); - } - this._httpVerb = value; - } - function Sys$Net$WebRequest$get_body() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._body; - } - function Sys$Net$WebRequest$set_body(value) { - var e = Function._validateParams(arguments, [{name: "value", mayBeNull: true}]); - if (e) throw e; - this._body = value; - } - function Sys$Net$WebRequest$get_userContext() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._userContext; - } - function Sys$Net$WebRequest$set_userContext(value) { - var e = Function._validateParams(arguments, [{name: "value", mayBeNull: true}]); - if (e) throw e; - this._userContext = value; - } - function Sys$Net$WebRequest$get_executor() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._executor; - } - function Sys$Net$WebRequest$set_executor(value) { - var e = Function._validateParams(arguments, [{name: "value", type: Sys.Net.WebRequestExecutor}]); - if (e) throw e; - if (this._executor !== null && this._executor.get_started()) { - throw Error.invalidOperation(Sys.Res.setExecutorAfterActive); - } - this._executor = value; - this._executor._set_webRequest(this); - } - function Sys$Net$WebRequest$get_timeout() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (this._timeout === 0) { - return Sys.Net.WebRequestManager.get_defaultTimeout(); - } - return this._timeout; - } - function Sys$Net$WebRequest$set_timeout(value) { - var e = Function._validateParams(arguments, [{name: "value", type: Number}]); - if (e) throw e; - if (value < 0) { - throw Error.argumentOutOfRange("value", value, Sys.Res.invalidTimeout); - } - this._timeout = value; - } - function Sys$Net$WebRequest$getResolvedUrl() { - /// - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return Sys.Net.WebRequest._resolveUrl(this._url); - } - function Sys$Net$WebRequest$invoke() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - if (this._invokeCalled) { - throw Error.invalidOperation(Sys.Res.invokeCalledTwice); - } - Sys.Net.WebRequestManager.executeRequest(this); - this._invokeCalled = true; - } -Sys.Net.WebRequest.prototype = { - add_completed: Sys$Net$WebRequest$add_completed, - remove_completed: Sys$Net$WebRequest$remove_completed, - completed: Sys$Net$WebRequest$completed, - _get_eventHandlerList: Sys$Net$WebRequest$_get_eventHandlerList, - get_url: Sys$Net$WebRequest$get_url, - set_url: Sys$Net$WebRequest$set_url, - get_headers: Sys$Net$WebRequest$get_headers, - get_httpVerb: Sys$Net$WebRequest$get_httpVerb, - set_httpVerb: Sys$Net$WebRequest$set_httpVerb, - get_body: Sys$Net$WebRequest$get_body, - set_body: Sys$Net$WebRequest$set_body, - get_userContext: Sys$Net$WebRequest$get_userContext, - set_userContext: Sys$Net$WebRequest$set_userContext, - get_executor: Sys$Net$WebRequest$get_executor, - set_executor: Sys$Net$WebRequest$set_executor, - get_timeout: Sys$Net$WebRequest$get_timeout, - set_timeout: Sys$Net$WebRequest$set_timeout, - getResolvedUrl: Sys$Net$WebRequest$getResolvedUrl, - invoke: Sys$Net$WebRequest$invoke -} -Sys.Net.WebRequest._resolveUrl = function Sys$Net$WebRequest$_resolveUrl(url, baseUrl) { - if (url && url.indexOf('://') !== -1) { - return url; - } - if (!baseUrl || baseUrl.length === 0) { - var baseElement = document.getElementsByTagName('base')[0]; - if (baseElement && baseElement.href && baseElement.href.length > 0) { - baseUrl = baseElement.href; - } - else { - baseUrl = document.URL; - } - } - var qsStart = baseUrl.indexOf('?'); - if (qsStart !== -1) { - baseUrl = baseUrl.substr(0, qsStart); - } - qsStart = baseUrl.indexOf('#'); - if (qsStart !== -1) { - baseUrl = baseUrl.substr(0, qsStart); - } - baseUrl = baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1); - if (!url || url.length === 0) { - return baseUrl; - } - if (url.charAt(0) === '/') { - var slashslash = baseUrl.indexOf('://'); - if (slashslash === -1) { - throw Error.argument("baseUrl", Sys.Res.badBaseUrl1); - } - var nextSlash = baseUrl.indexOf('/', slashslash + 3); - if (nextSlash === -1) { - throw Error.argument("baseUrl", Sys.Res.badBaseUrl2); - } - return baseUrl.substr(0, nextSlash) + url; - } - else { - var lastSlash = baseUrl.lastIndexOf('/'); - if (lastSlash === -1) { - throw Error.argument("baseUrl", Sys.Res.badBaseUrl3); - } - return baseUrl.substr(0, lastSlash+1) + url; - } -} -Sys.Net.WebRequest._createQueryString = function Sys$Net$WebRequest$_createQueryString(queryString, encodeMethod, addParams) { - encodeMethod = encodeMethod || encodeURIComponent; - var i = 0, obj, val, arg, sb = new Sys.StringBuilder(); - if (queryString) { - for (arg in queryString) { - obj = queryString[arg]; - if (typeof(obj) === "function") continue; - val = Sys.Serialization.JavaScriptSerializer.serialize(obj); - if (i++) { - sb.append('&'); - } - sb.append(arg); - sb.append('='); - sb.append(encodeMethod(val)); - } - } - if (addParams) { - if (i) { - sb.append('&'); - } - sb.append(addParams); - } - return sb.toString(); -} -Sys.Net.WebRequest._createUrl = function Sys$Net$WebRequest$_createUrl(url, queryString, addParams) { - if (!queryString && !addParams) { - return url; - } - var qs = Sys.Net.WebRequest._createQueryString(queryString, null, addParams); - return qs.length - ? url + ((url && url.indexOf('?') >= 0) ? "&" : "?") + qs - : url; -} -Sys.Net.WebRequest.registerClass('Sys.Net.WebRequest'); - -Sys._ScriptLoaderTask = function Sys$_ScriptLoaderTask(scriptElement, completedCallback) { - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "scriptElement", domElement: true}, - {name: "completedCallback", type: Function} - ]); - if (e) throw e; - this._scriptElement = scriptElement; - this._completedCallback = completedCallback; -} - function Sys$_ScriptLoaderTask$get_scriptElement() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._scriptElement; - } - function Sys$_ScriptLoaderTask$dispose() { - if(this._disposed) { - return; - } - this._disposed = true; - this._removeScriptElementHandlers(); - Sys._ScriptLoaderTask._clearScript(this._scriptElement); - this._scriptElement = null; - } - function Sys$_ScriptLoaderTask$execute() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - this._addScriptElementHandlers(); - var headElements = document.getElementsByTagName('head'); - if (headElements.length === 0) { - throw new Error.invalidOperation(Sys.Res.scriptLoadFailedNoHead); - } - else { - headElements[0].appendChild(this._scriptElement); - } - } - function Sys$_ScriptLoaderTask$_addScriptElementHandlers() { - this._scriptLoadDelegate = Function.createDelegate(this, this._scriptLoadHandler); - - if (Sys.Browser.agent !== Sys.Browser.InternetExplorer) { - this._scriptElement.readyState = 'loaded'; - $addHandler(this._scriptElement, 'load', this._scriptLoadDelegate); - } - else { - $addHandler(this._scriptElement, 'readystatechange', this._scriptLoadDelegate); - } - if (this._scriptElement.addEventListener) { - this._scriptErrorDelegate = Function.createDelegate(this, this._scriptErrorHandler); - this._scriptElement.addEventListener('error', this._scriptErrorDelegate, false); - } - } - function Sys$_ScriptLoaderTask$_removeScriptElementHandlers() { - if(this._scriptLoadDelegate) { - var scriptElement = this.get_scriptElement(); - if (Sys.Browser.agent !== Sys.Browser.InternetExplorer) { - $removeHandler(scriptElement, 'load', this._scriptLoadDelegate); - } - else { - $removeHandler(scriptElement, 'readystatechange', this._scriptLoadDelegate); - } - if (this._scriptErrorDelegate) { - this._scriptElement.removeEventListener('error', this._scriptErrorDelegate, false); - this._scriptErrorDelegate = null; - } - this._scriptLoadDelegate = null; - } - } - function Sys$_ScriptLoaderTask$_scriptErrorHandler() { - if(this._disposed) { - return; - } - - this._completedCallback(this.get_scriptElement(), false); - } - function Sys$_ScriptLoaderTask$_scriptLoadHandler() { - if(this._disposed) { - return; - } - var scriptElement = this.get_scriptElement(); - if ((scriptElement.readyState !== 'loaded') && - (scriptElement.readyState !== 'complete')) { - return; - } - - this._completedCallback(scriptElement, true); - } -Sys._ScriptLoaderTask.prototype = { - get_scriptElement: Sys$_ScriptLoaderTask$get_scriptElement, - dispose: Sys$_ScriptLoaderTask$dispose, - execute: Sys$_ScriptLoaderTask$execute, - _addScriptElementHandlers: Sys$_ScriptLoaderTask$_addScriptElementHandlers, - _removeScriptElementHandlers: Sys$_ScriptLoaderTask$_removeScriptElementHandlers, - _scriptErrorHandler: Sys$_ScriptLoaderTask$_scriptErrorHandler, - _scriptLoadHandler: Sys$_ScriptLoaderTask$_scriptLoadHandler -} -Sys._ScriptLoaderTask.registerClass("Sys._ScriptLoaderTask", null, Sys.IDisposable); -Sys._ScriptLoaderTask._clearScript = function Sys$_ScriptLoaderTask$_clearScript(scriptElement) { - if (!Sys.Debug.isDebug) { - scriptElement.parentNode.removeChild(scriptElement); - } -} -Type.registerNamespace('Sys.Net'); - -Sys.Net.WebServiceProxy = function Sys$Net$WebServiceProxy() { -} - function Sys$Net$WebServiceProxy$get_timeout() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._timeout || 0; - } - function Sys$Net$WebServiceProxy$set_timeout(value) { - var e = Function._validateParams(arguments, [{name: "value", type: Number}]); - if (e) throw e; - if (value < 0) { throw Error.argumentOutOfRange('value', value, Sys.Res.invalidTimeout); } - this._timeout = value; - } - function Sys$Net$WebServiceProxy$get_defaultUserContext() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return (typeof(this._userContext) === "undefined") ? null : this._userContext; - } - function Sys$Net$WebServiceProxy$set_defaultUserContext(value) { - var e = Function._validateParams(arguments, [{name: "value", mayBeNull: true}]); - if (e) throw e; - this._userContext = value; - } - function Sys$Net$WebServiceProxy$get_defaultSucceededCallback() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._succeeded || null; - } - function Sys$Net$WebServiceProxy$set_defaultSucceededCallback(value) { - var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); - if (e) throw e; - this._succeeded = value; - } - function Sys$Net$WebServiceProxy$get_defaultFailedCallback() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._failed || null; - } - function Sys$Net$WebServiceProxy$set_defaultFailedCallback(value) { - var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); - if (e) throw e; - this._failed = value; - } - function Sys$Net$WebServiceProxy$get_enableJsonp() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return !!this._jsonp; - } - function Sys$Net$WebServiceProxy$set_enableJsonp(value) { - var e = Function._validateParams(arguments, [{name: "value", type: Boolean}]); - if (e) throw e; - this._jsonp = value; - } - function Sys$Net$WebServiceProxy$get_path() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._path || null; - } - function Sys$Net$WebServiceProxy$set_path(value) { - var e = Function._validateParams(arguments, [{name: "value", type: String}]); - if (e) throw e; - this._path = value; - } - function Sys$Net$WebServiceProxy$get_jsonpCallbackParameter() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._callbackParameter || "callback"; - } - function Sys$Net$WebServiceProxy$set_jsonpCallbackParameter(value) { - var e = Function._validateParams(arguments, [{name: "value", type: String}]); - if (e) throw e; - this._callbackParameter = value; - } - function Sys$Net$WebServiceProxy$_invoke(servicePath, methodName, useGet, params, onSuccess, onFailure, userContext) { - /// - /// - /// - /// - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "servicePath", type: String}, - {name: "methodName", type: String}, - {name: "useGet", type: Boolean}, - {name: "params"}, - {name: "onSuccess", type: Function, mayBeNull: true, optional: true}, - {name: "onFailure", type: Function, mayBeNull: true, optional: true}, - {name: "userContext", mayBeNull: true, optional: true} - ]); - if (e) throw e; - onSuccess = onSuccess || this.get_defaultSucceededCallback(); - onFailure = onFailure || this.get_defaultFailedCallback(); - if (userContext === null || typeof userContext === 'undefined') userContext = this.get_defaultUserContext(); - return Sys.Net.WebServiceProxy.invoke(servicePath, methodName, useGet, params, onSuccess, onFailure, userContext, this.get_timeout(), this.get_enableJsonp(), this.get_jsonpCallbackParameter()); - } -Sys.Net.WebServiceProxy.prototype = { - get_timeout: Sys$Net$WebServiceProxy$get_timeout, - set_timeout: Sys$Net$WebServiceProxy$set_timeout, - get_defaultUserContext: Sys$Net$WebServiceProxy$get_defaultUserContext, - set_defaultUserContext: Sys$Net$WebServiceProxy$set_defaultUserContext, - get_defaultSucceededCallback: Sys$Net$WebServiceProxy$get_defaultSucceededCallback, - set_defaultSucceededCallback: Sys$Net$WebServiceProxy$set_defaultSucceededCallback, - get_defaultFailedCallback: Sys$Net$WebServiceProxy$get_defaultFailedCallback, - set_defaultFailedCallback: Sys$Net$WebServiceProxy$set_defaultFailedCallback, - get_enableJsonp: Sys$Net$WebServiceProxy$get_enableJsonp, - set_enableJsonp: Sys$Net$WebServiceProxy$set_enableJsonp, - get_path: Sys$Net$WebServiceProxy$get_path, - set_path: Sys$Net$WebServiceProxy$set_path, - get_jsonpCallbackParameter: Sys$Net$WebServiceProxy$get_jsonpCallbackParameter, - set_jsonpCallbackParameter: Sys$Net$WebServiceProxy$set_jsonpCallbackParameter, - _invoke: Sys$Net$WebServiceProxy$_invoke -} -Sys.Net.WebServiceProxy.registerClass('Sys.Net.WebServiceProxy'); -Sys.Net.WebServiceProxy.invoke = function Sys$Net$WebServiceProxy$invoke(servicePath, methodName, useGet, params, onSuccess, onFailure, userContext, timeout, enableJsonp, jsonpCallbackParameter) { - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "servicePath", type: String}, - {name: "methodName", type: String, mayBeNull: true, optional: true}, - {name: "useGet", type: Boolean, optional: true}, - {name: "params", mayBeNull: true, optional: true}, - {name: "onSuccess", type: Function, mayBeNull: true, optional: true}, - {name: "onFailure", type: Function, mayBeNull: true, optional: true}, - {name: "userContext", mayBeNull: true, optional: true}, - {name: "timeout", type: Number, optional: true}, - {name: "enableJsonp", type: Boolean, mayBeNull: true, optional: true}, - {name: "jsonpCallbackParameter", type: String, mayBeNull: true, optional: true} - ]); - if (e) throw e; - var schemeHost = (enableJsonp !== false) ? Sys.Net.WebServiceProxy._xdomain.exec(servicePath) : null, - tempCallback, jsonp = schemeHost && (schemeHost.length === 3) && - ((schemeHost[1] !== location.protocol) || (schemeHost[2] !== location.host)); - useGet = jsonp || useGet; - if (jsonp) { - jsonpCallbackParameter = jsonpCallbackParameter || "callback"; - tempCallback = "_jsonp" + Sys._jsonp++; - } - if (!params) params = {}; - var urlParams = params; - if (!useGet || !urlParams) urlParams = {}; - var script, error, timeoutcookie = null, loader, body = null, - url = Sys.Net.WebRequest._createUrl(methodName - ? (servicePath+"/"+encodeURIComponent(methodName)) - : servicePath, urlParams, jsonp ? (jsonpCallbackParameter + "=Sys." + tempCallback) : null); - if (jsonp) { - script = document.createElement("script"); - script.src = url; - loader = new Sys._ScriptLoaderTask(script, function(script, loaded) { - if (!loaded || tempCallback) { - jsonpComplete({ Message: String.format(Sys.Res.webServiceFailedNoMsg, methodName) }, -1); - } - }); - function jsonpComplete(data, statusCode) { - if (timeoutcookie !== null) { - window.clearTimeout(timeoutcookie); - timeoutcookie = null; - } - loader.dispose(); - delete Sys[tempCallback]; - tempCallback = null; - if ((typeof(statusCode) !== "undefined") && (statusCode !== 200)) { - if (onFailure) { - error = new Sys.Net.WebServiceError(false, - data.Message || String.format(Sys.Res.webServiceFailedNoMsg, methodName), - data.StackTrace || null, - data.ExceptionType || null, - data); - error._statusCode = statusCode; - onFailure(error, userContext, methodName); - } - else { - if (data.StackTrace && data.Message) { - error = data.StackTrace + "-- " + data.Message; - } - else { - error = data.StackTrace || data.Message; - } - error = String.format(error ? Sys.Res.webServiceFailed : Sys.Res.webServiceFailedNoMsg, methodName, error); - throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error)); - } - } - else if (onSuccess) { - onSuccess(data, userContext, methodName); - } - } - Sys[tempCallback] = jsonpComplete; - loader.execute(); - return null; - } - var request = new Sys.Net.WebRequest(); - request.set_url(url); - request.get_headers()['Content-Type'] = 'application/json; charset=utf-8'; - if (!useGet) { - body = Sys.Serialization.JavaScriptSerializer.serialize(params); - if (body === "{}") body = ""; - } - request.set_body(body); - request.add_completed(onComplete); - if (timeout && timeout > 0) request.set_timeout(timeout); - request.invoke(); - - function onComplete(response, eventArgs) { - if (response.get_responseAvailable()) { - var statusCode = response.get_statusCode(); - var result = null; - - try { - var contentType = response.getResponseHeader("Content-Type"); - if (contentType.startsWith("application/json")) { - result = response.get_object(); - } - else if (contentType.startsWith("text/xml")) { - result = response.get_xml(); - } - else { - result = response.get_responseData(); - } - } catch (ex) { - } - var error = response.getResponseHeader("jsonerror"); - var errorObj = (error === "true"); - if (errorObj) { - if (result) { - result = new Sys.Net.WebServiceError(false, result.Message, result.StackTrace, result.ExceptionType, result); - } - } - else if (contentType.startsWith("application/json")) { - result = (!result || (typeof(result.d) === "undefined")) ? result : result.d; - } - if (((statusCode < 200) || (statusCode >= 300)) || errorObj) { - if (onFailure) { - if (!result || !errorObj) { - result = new Sys.Net.WebServiceError(false , String.format(Sys.Res.webServiceFailedNoMsg, methodName)); - } - result._statusCode = statusCode; - onFailure(result, userContext, methodName); - } - else { - if (result && errorObj) { - error = result.get_exceptionType() + "-- " + result.get_message(); - } - else { - error = response.get_responseData(); - } - throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error)); - } - } - else if (onSuccess) { - onSuccess(result, userContext, methodName); - } - } - else { - var msg; - if (response.get_timedOut()) { - msg = String.format(Sys.Res.webServiceTimedOut, methodName); - } - else { - msg = String.format(Sys.Res.webServiceFailedNoMsg, methodName) - } - if (onFailure) { - onFailure(new Sys.Net.WebServiceError(response.get_timedOut(), msg, "", ""), userContext, methodName); - } - else { - throw Sys.Net.WebServiceProxy._createFailedError(methodName, msg); - } - } - } - return request; -} -Sys.Net.WebServiceProxy._createFailedError = function Sys$Net$WebServiceProxy$_createFailedError(methodName, errorMessage) { - var displayMessage = "Sys.Net.WebServiceFailedException: " + errorMessage; - var e = Error.create(displayMessage, { 'name': 'Sys.Net.WebServiceFailedException', 'methodName': methodName }); - e.popStackFrame(); - return e; -} -Sys.Net.WebServiceProxy._defaultFailedCallback = function Sys$Net$WebServiceProxy$_defaultFailedCallback(err, methodName) { - var error = err.get_exceptionType() + "-- " + err.get_message(); - throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error)); -} -Sys.Net.WebServiceProxy._generateTypedConstructor = function Sys$Net$WebServiceProxy$_generateTypedConstructor(type) { - return function(properties) { - if (properties) { - for (var name in properties) { - this[name] = properties[name]; - } - } - this.__type = type; - } -} -Sys._jsonp = 0; -Sys.Net.WebServiceProxy._xdomain = /^\s*([a-zA-Z0-9\+\-\.]+\:)\/\/([^?#\/]+)/; - -Sys.Net.WebServiceError = function Sys$Net$WebServiceError(timedOut, message, stackTrace, exceptionType, errorObject) { - /// - /// - /// - /// - /// - /// - var e = Function._validateParams(arguments, [ - {name: "timedOut", type: Boolean}, - {name: "message", type: String, mayBeNull: true}, - {name: "stackTrace", type: String, mayBeNull: true, optional: true}, - {name: "exceptionType", type: String, mayBeNull: true, optional: true}, - {name: "errorObject", type: Object, mayBeNull: true, optional: true} - ]); - if (e) throw e; - this._timedOut = timedOut; - this._message = message; - this._stackTrace = stackTrace; - this._exceptionType = exceptionType; - this._errorObject = errorObject; - this._statusCode = -1; -} - function Sys$Net$WebServiceError$get_timedOut() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._timedOut; - } - function Sys$Net$WebServiceError$get_statusCode() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._statusCode; - } - function Sys$Net$WebServiceError$get_message() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._message; - } - function Sys$Net$WebServiceError$get_stackTrace() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._stackTrace || ""; - } - function Sys$Net$WebServiceError$get_exceptionType() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._exceptionType || ""; - } - function Sys$Net$WebServiceError$get_errorObject() { - /// - if (arguments.length !== 0) throw Error.parameterCount(); - return this._errorObject || null; - } -Sys.Net.WebServiceError.prototype = { - get_timedOut: Sys$Net$WebServiceError$get_timedOut, - get_statusCode: Sys$Net$WebServiceError$get_statusCode, - get_message: Sys$Net$WebServiceError$get_message, - get_stackTrace: Sys$Net$WebServiceError$get_stackTrace, - get_exceptionType: Sys$Net$WebServiceError$get_exceptionType, - get_errorObject: Sys$Net$WebServiceError$get_errorObject -} -Sys.Net.WebServiceError.registerClass('Sys.Net.WebServiceError'); - - -Type.registerNamespace('Sys'); - -Sys.Res={ -'urlMustBeLessThan1024chars':'The history state must be small enough to not make the url larger than 1024 characters.', -'argumentTypeName':'Value is not the name of an existing type.', -'cantBeCalledAfterDispose':'Can\'t be called after dispose.', -'componentCantSetIdAfterAddedToApp':'The id property of a component can\'t be set after it\'s been added to the Application object.', -'behaviorDuplicateName':'A behavior with name \'{0}\' already exists or it is the name of an existing property on the target element.', -'notATypeName':'Value is not a valid type name.', -'elementNotFound':'An element with id \'{0}\' could not be found.', -'stateMustBeStringDictionary':'The state object can only have null and string fields.', -'boolTrueOrFalse':'Value must be \'true\' or \'false\'.', -'scriptLoadFailedNoHead':'ScriptLoader requires pages to contain a element.', -'stringFormatInvalid':'The format string is invalid.', -'referenceNotFound':'Component \'{0}\' was not found.', -'enumReservedName':'\'{0}\' is a reserved name that can\'t be used as an enum value name.', -'circularParentChain':'The chain of control parents can\'t have circular references.', -'namespaceContainsNonObject':'Object {0} already exists and is not an object.', -'undefinedEvent':'\'{0}\' is not an event.', -'propertyUndefined':'\'{0}\' is not a property or an existing field.', -'observableConflict':'Object already contains a member with the name \'{0}\'.', -'historyCannotEnableHistory':'Cannot set enableHistory after initialization.', -'eventHandlerInvalid':'Handler was not added through the Sys.UI.DomEvent.addHandler method.', -'scriptLoadFailedDebug':'The script \'{0}\' failed to load. Check for:\r\n Inaccessible path.\r\n Script errors. (IE) Enable \'Display a notification about every script error\' under advanced settings.', -'propertyNotWritable':'\'{0}\' is not a writable property.', -'enumInvalidValueName':'\'{0}\' is not a valid name for an enum value.', -'controlAlreadyDefined':'A control is already associated with the element.', -'addHandlerCantBeUsedForError':'Can\'t add a handler for the error event using this method. Please set the window.onerror property instead.', -'cantAddNonFunctionhandler':'Can\'t add a handler that is not a function.', -'invalidNameSpace':'Value is not a valid namespace identifier.', -'notAnInterface':'Value is not a valid interface.', -'eventHandlerNotFunction':'Handler must be a function.', -'propertyNotAnArray':'\'{0}\' is not an Array property.', -'namespaceContainsClass':'Object {0} already exists as a class, enum, or interface.', -'typeRegisteredTwice':'Type {0} has already been registered. The type may be defined multiple times or the script file that defines it may have already been loaded. A possible cause is a change of settings during a partial update.', -'cantSetNameAfterInit':'The name property can\'t be set on this object after initialization.', -'historyMissingFrame':'For the history feature to work in IE, the page must have an iFrame element with id \'__historyFrame\' pointed to a page that gets its title from the \'title\' query string parameter and calls Sys.Application._onIFrameLoad() on the parent window. This can be done by setting EnableHistory to true on ScriptManager.', -'appDuplicateComponent':'Two components with the same id \'{0}\' can\'t be added to the application.', -'historyCannotAddHistoryPointWithHistoryDisabled':'A history point can only be added if enableHistory is set to true.', -'baseNotAClass':'Value is not a class.', -'expectedElementOrId':'Value must be a DOM element or DOM element Id.', -'methodNotFound':'No method found with name \'{0}\'.', -'arrayParseBadFormat':'Value must be a valid string representation for an array. It must start with a \'[\' and end with a \']\'.', -'stateFieldNameInvalid':'State field names must not contain any \'=\' characters.', -'cantSetId':'The id property can\'t be set on this object.', -'stringFormatBraceMismatch':'The format string contains an unmatched opening or closing brace.', -'enumValueNotInteger':'An enumeration definition can only contain integer values.', -'propertyNullOrUndefined':'Cannot set the properties of \'{0}\' because it returned a null value.', -'argumentDomNode':'Value must be a DOM element or a text node.', -'componentCantSetIdTwice':'The id property of a component can\'t be set more than once.', -'createComponentOnDom':'Value must be null for Components that are not Controls or Behaviors.', -'createNotComponent':'{0} does not derive from Sys.Component.', -'createNoDom':'Value must not be null for Controls and Behaviors.', -'cantAddWithoutId':'Can\'t add a component that doesn\'t have an id.', -'notObservable':'Instances of type \'{0}\' cannot be observed.', -'badTypeName':'Value is not the name of the type being registered or the name is a reserved word.', -'argumentInteger':'Value must be an integer.', -'invokeCalledTwice':'Cannot call invoke more than once.', -'webServiceFailed':'The server method \'{0}\' failed with the following error: {1}', -'argumentType':'Object cannot be converted to the required type.', -'argumentNull':'Value cannot be null.', -'scriptAlreadyLoaded':'The script \'{0}\' has been referenced multiple times. If referencing Microsoft AJAX scripts explicitly, set the MicrosoftAjaxMode property of the ScriptManager to Explicit.', -'scriptDependencyNotFound':'The script \'{0}\' failed to load because it is dependent on script \'{1}\'.', -'formatBadFormatSpecifier':'Format specifier was invalid.', -'requiredScriptReferenceNotIncluded':'\'{0}\' requires that you have included a script reference to \'{1}\'.', -'webServiceFailedNoMsg':'The server method \'{0}\' failed.', -'argumentDomElement':'Value must be a DOM element.', -'invalidExecutorType':'Could not create a valid Sys.Net.WebRequestExecutor from: {0}.', -'cannotCallBeforeResponse':'Cannot call {0} when responseAvailable is false.', -'actualValue':'Actual value was {0}.', -'enumInvalidValue':'\'{0}\' is not a valid value for enum {1}.', -'scriptLoadFailed':'The script \'{0}\' could not be loaded.', -'parameterCount':'Parameter count mismatch.', -'cannotDeserializeEmptyString':'Cannot deserialize empty string.', -'formatInvalidString':'Input string was not in a correct format.', -'invalidTimeout':'Value must be greater than or equal to zero.', -'cannotAbortBeforeStart':'Cannot abort when executor has not started.', -'argument':'Value does not fall within the expected range.', -'cannotDeserializeInvalidJson':'Cannot deserialize. The data does not correspond to valid JSON.', -'invalidHttpVerb':'httpVerb cannot be set to an empty or null string.', -'nullWebRequest':'Cannot call executeRequest with a null webRequest.', -'eventHandlerInvalid':'Handler was not added through the Sys.UI.DomEvent.addHandler method.', -'cannotSerializeNonFiniteNumbers':'Cannot serialize non finite numbers.', -'argumentUndefined':'Value cannot be undefined.', -'webServiceInvalidReturnType':'The server method \'{0}\' returned an invalid type. Expected type: {1}', -'servicePathNotSet':'The path to the web service has not been set.', -'argumentTypeWithTypes':'Object of type \'{0}\' cannot be converted to type \'{1}\'.', -'cannotCallOnceStarted':'Cannot call {0} once started.', -'badBaseUrl1':'Base URL does not contain ://.', -'badBaseUrl2':'Base URL does not contain another /.', -'badBaseUrl3':'Cannot find last / in base URL.', -'setExecutorAfterActive':'Cannot set executor after it has become active.', -'paramName':'Parameter name: {0}', -'nullReferenceInPath':'Null reference while evaluating data path: \'{0}\'.', -'cannotCallOutsideHandler':'Cannot call {0} outside of a completed event handler.', -'cannotSerializeObjectWithCycle':'Cannot serialize object with cyclic reference within child properties.', -'format':'One of the identified items was in an invalid format.', -'assertFailedCaller':'Assertion Failed: {0}\r\nat {1}', -'argumentOutOfRange':'Specified argument was out of the range of valid values.', -'webServiceTimedOut':'The server method \'{0}\' timed out.', -'notImplemented':'The method or operation is not implemented.', -'assertFailed':'Assertion Failed: {0}', -'invalidOperation':'Operation is not valid due to the current state of the object.', -'breakIntoDebugger':'{0}\r\n\r\nBreak into debugger?' -}; diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftAjax.js b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftAjax.js deleted file mode 100644 index 9994d1b..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftAjax.js +++ /dev/null @@ -1,6 +0,0 @@ -//---------------------------------------------------------- -// Copyright (C) Microsoft Corporation. All rights reserved. -//---------------------------------------------------------- -// MicrosoftAjax.js -Function.__typeName="Function";Function.__class=true;Function.createCallback=function(b,a){return function(){var e=arguments.length;if(e>0){var d=[];for(var c=0;c=d)break;a=Function._validateParameter(g[b],f,h);if(a){a.popStackFrame();return a}}return null};Function._validateParameterCount=function(j,d,i){var a,c,b=d.length,e=j.length;if(eb){c=true;for(a=0;a0&&(d=0};Array.dequeue=function(a){return a.shift()};Array.forEach=function(b,e,d){for(var a=0,f=b.length;a=0)b.splice(a,1);return a>=0};Array.removeAt=function(a,b){a.splice(b,1)};Sys._indexOf=function(d,e,a){if(typeof e==="undefined")return -1;var c=d.length;if(c!==0){a=a-0;if(isNaN(a))a=0;else{if(isFinite(a))a=a-a%1;if(a<0)a=Math.max(0,c+a)}for(var b=a;b-1){Sys.Browser.agent=Sys.Browser.InternetExplorer;Sys.Browser.version=parseFloat(navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1]);if(Sys.Browser.version>=8)if(document.documentMode>=7)Sys.Browser.documentMode=document.documentMode;Sys.Browser.hasDebuggerStatement=true}else if(navigator.userAgent.indexOf(" Firefox/")>-1){Sys.Browser.agent=Sys.Browser.Firefox;Sys.Browser.version=parseFloat(navigator.userAgent.match(/Firefox\/(\d+\.\d+)/)[1]);Sys.Browser.name="Firefox";Sys.Browser.hasDebuggerStatement=true}else if(navigator.userAgent.indexOf(" AppleWebKit/")>-1){Sys.Browser.agent=Sys.Browser.Safari;Sys.Browser.version=parseFloat(navigator.userAgent.match(/AppleWebKit\/(\d+(\.\d+)?)/)[1]);Sys.Browser.name="Safari"}else if(navigator.userAgent.indexOf("Opera/")>-1)Sys.Browser.agent=Sys.Browser.Opera;Sys.EventArgs=function(){};Sys.EventArgs.registerClass("Sys.EventArgs");Sys.EventArgs.Empty=new Sys.EventArgs;Sys.CancelEventArgs=function(){Sys.CancelEventArgs.initializeBase(this);this._cancel=false};Sys.CancelEventArgs.prototype={get_cancel:function(){return this._cancel},set_cancel:function(a){this._cancel=a}};Sys.CancelEventArgs.registerClass("Sys.CancelEventArgs",Sys.EventArgs);Type.registerNamespace("Sys.UI");Sys._Debug=function(){};Sys._Debug.prototype={_appendConsole:function(a){if(typeof Debug!=="undefined"&&Debug.writeln)Debug.writeln(a);if(window.console&&window.console.log)window.console.log(a);if(window.opera)window.opera.postError(a);if(window.debugService)window.debugService.trace(a)},_appendTrace:function(b){var a=document.getElementById("TraceConsole");if(a&&a.tagName.toUpperCase()==="TEXTAREA")a.value+=b+"\n"},assert:function(c,a,b){if(!c){a=b&&this.assert.caller?String.format(Sys.Res.assertFailedCaller,a,this.assert.caller):String.format(Sys.Res.assertFailed,a);if(confirm(String.format(Sys.Res.breakIntoDebugger,a)))this.fail(a)}},clearTrace:function(){var a=document.getElementById("TraceConsole");if(a&&a.tagName.toUpperCase()==="TEXTAREA")a.value=""},fail:function(message){this._appendConsole(message);if(Sys.Browser.hasDebuggerStatement)eval("debugger")},trace:function(a){this._appendConsole(a);this._appendTrace(a)},traceDump:function(a,b){var c=this._traceDump(a,b,true)},_traceDump:function(a,c,f,b,d){c=c?c:"traceDump";b=b?b:"";if(a===null){this.trace(b+c+": null");return}switch(typeof a){case "undefined":this.trace(b+c+": Undefined");break;case "number":case "string":case "boolean":this.trace(b+c+": "+a);break;default:if(Date.isInstanceOfType(a)||RegExp.isInstanceOfType(a)){this.trace(b+c+": "+a.toString());break}if(!d)d=[];else if(Array.contains(d,a)){this.trace(b+c+": ...");return}Array.add(d,a);if(a==window||a===document||window.HTMLElement&&a instanceof HTMLElement||typeof a.nodeName==="string"){var k=a.tagName?a.tagName:"DomElement";if(a.id)k+=" - "+a.id;this.trace(b+c+" {"+k+"}")}else{var i=Object.getTypeName(a);this.trace(b+c+(typeof i==="string"?" {"+i+"}":""));if(b===""||f){b+=" ";var e,j,l,g,h;if(Array.isInstanceOfType(a)){j=a.length;for(e=0;e=0;d--){var k=h[d].trim();b=a[k];if(typeof b!=="number")throw Error.argument("value",String.format(Sys.Res.enumInvalidValue,c.split(",")[d].trim(),this.__typeName));j|=b}return j}}function Sys$Enum$toString(c){if(typeof c==="undefined"||c===null)return this.__string;var d=this.prototype,a;if(!this.__flags||c===0){for(a in d)if(d[a]===c)return a}else{var b=this.__sortedValues;if(!b){b=[];for(a in d)b[b.length]={key:a,value:d[a]};b.sort(function(a,b){return a.value-b.value});this.__sortedValues=b}var e=[],g=c;for(a=b.length-1;a>=0;a--){var h=b[a],f=h.value;if(f===0)continue;if((f&c)===f){e[e.length]=h.key;g-=f;if(g===0)break}}if(e.length&&g===0)return e.reverse().join(", ")}return ""}Type.prototype.registerEnum=function(b,c){Sys.__upperCaseTypes[b.toUpperCase()]=this;for(var a in this.prototype)this[a]=this.prototype[a];this.__typeName=b;this.parse=Sys$Enum$parse;this.__string=this.toString();this.toString=Sys$Enum$toString;this.__flags=c;this.__enum=true};Type.isEnum=function(a){if(typeof a==="undefined"||a===null)return false;return !!a.__enum};Type.isFlags=function(a){if(typeof a==="undefined"||a===null)return false;return !!a.__flags};Sys.CollectionChange=function(e,a,c,b,d){this.action=e;if(a)if(!(a instanceof Array))a=[a];this.newItems=a||null;if(typeof c!=="number")c=-1;this.newStartingIndex=c;if(b)if(!(b instanceof Array))b=[b];this.oldItems=b||null;if(typeof d!=="number")d=-1;this.oldStartingIndex=d};Sys.CollectionChange.registerClass("Sys.CollectionChange");Sys.NotifyCollectionChangedAction=function(){throw Error.notImplemented()};Sys.NotifyCollectionChangedAction.prototype={add:0,remove:1,reset:2};Sys.NotifyCollectionChangedAction.registerEnum("Sys.NotifyCollectionChangedAction");Sys.NotifyCollectionChangedEventArgs=function(a){this._changes=a;Sys.NotifyCollectionChangedEventArgs.initializeBase(this)};Sys.NotifyCollectionChangedEventArgs.prototype={get_changes:function(){return this._changes||[]}};Sys.NotifyCollectionChangedEventArgs.registerClass("Sys.NotifyCollectionChangedEventArgs",Sys.EventArgs);Sys.Observer=function(){};Sys.Observer.registerClass("Sys.Observer");Sys.Observer.makeObservable=function(a){var c=a instanceof Array,b=Sys.Observer;if(a.setValue===b._observeMethods.setValue)return a;b._addMethods(a,b._observeMethods);if(c)b._addMethods(a,b._arrayMethods);return a};Sys.Observer._addMethods=function(c,b){for(var a in b)c[a]=b[a]};Sys.Observer._addEventHandler=function(c,a,b){Sys.Observer._getContext(c,true).events._addHandler(a,b)};Sys.Observer.addEventHandler=function(c,a,b){Sys.Observer._addEventHandler(c,a,b)};Sys.Observer._removeEventHandler=function(c,a,b){Sys.Observer._getContext(c,true).events._removeHandler(a,b)};Sys.Observer.removeEventHandler=function(c,a,b){Sys.Observer._removeEventHandler(c,a,b)};Sys.Observer.raiseEvent=function(b,e,d){var c=Sys.Observer._getContext(b);if(!c)return;var a=c.events.getHandler(e);if(a)a(b,d)};Sys.Observer.addPropertyChanged=function(b,a){Sys.Observer._addEventHandler(b,"propertyChanged",a)};Sys.Observer.removePropertyChanged=function(b,a){Sys.Observer._removeEventHandler(b,"propertyChanged",a)};Sys.Observer.beginUpdate=function(a){Sys.Observer._getContext(a,true).updating=true};Sys.Observer.endUpdate=function(b){var a=Sys.Observer._getContext(b);if(!a||!a.updating)return;a.updating=false;var d=a.dirty;a.dirty=false;if(d){if(b instanceof Array){var c=a.changes;a.changes=null;Sys.Observer.raiseCollectionChanged(b,c)}Sys.Observer.raisePropertyChanged(b,"")}};Sys.Observer.isUpdating=function(b){var a=Sys.Observer._getContext(b);return a?a.updating:false};Sys.Observer._setValue=function(a,j,g){var b,f,k=a,d=j.split(".");for(var i=0,m=d.length-1;i-1&&ac.Calendar.TwoDigitYearMax)a-=100}return a};Date._getEra=function(e,c){if(!c)return 0;var b,d=e.getTime();for(var a=0,f=c.length;a=b)return a}return 0};Date._getEraYear=function(d,b,e,c){var a=d.getFullYear();if(!c&&b.eras)a-=b.eras[e+3];return a};Date._getParseRegExp=function(b,e){if(!b._parseRegExp)b._parseRegExp={};else if(b._parseRegExp[e])return b._parseRegExp[e];var c=Date._expandFormat(b,e);c=c.replace(/([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g,"\\\\$1");var a=new Sys.StringBuilder("^"),j=[],f=0,i=0,h=Date._getTokenRegExp(),d;while((d=h.exec(c))!==null){var l=c.slice(f,d.index);f=h.lastIndex;i+=Date._appendPreOrPostMatch(l,a);if(i%2===1){a.append(d[0]);continue}switch(d[0]){case "dddd":case "ddd":case "MMMM":case "MMM":case "gg":case "g":a.append("(\\D+)");break;case "tt":case "t":a.append("(\\D*)");break;case "yyyy":a.append("(\\d{4})");break;case "fff":a.append("(\\d{3})");break;case "ff":a.append("(\\d{2})");break;case "f":a.append("(\\d)");break;case "dd":case "d":case "MM":case "M":case "yy":case "y":case "HH":case "H":case "hh":case "h":case "mm":case "m":case "ss":case "s":a.append("(\\d\\d?)");break;case "zzz":a.append("([+-]?\\d\\d?:\\d{2})");break;case "zz":case "z":a.append("([+-]?\\d\\d?)");break;case "/":a.append("(\\"+b.DateSeparator+")")}Array.add(j,d[0])}Date._appendPreOrPostMatch(c.slice(f),a);a.append("$");var k=a.toString().replace(/\s+/g,"\\s+"),g={"regExp":k,"groups":j};b._parseRegExp[e]=g;return g};Date._getTokenRegExp=function(){return /\/|dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z|gg|g/g};Date.parseLocale=function(a){return Date._parse(a,Sys.CultureInfo.CurrentCulture,arguments)};Date.parseInvariant=function(a){return Date._parse(a,Sys.CultureInfo.InvariantCulture,arguments)};Date._parse=function(h,d,i){var a,c,b,f,e,g=false;for(a=1,c=i.length;a31)return null;break;case "MMMM":c=k._getMonthIndex(a);if(c<0||c>11)return null;break;case "MMM":c=k._getAbbrMonthIndex(a);if(c<0||c>11)return null;break;case "M":case "MM":c=parseInt(a,10)-1;if(c<0||c>11)return null;break;case "y":case "yy":e=Date._expandYear(g,parseInt(a,10));if(e<0||e>9999)return null;break;case "yyyy":e=parseInt(a,10);if(e<0||e>9999)return null;break;case "h":case "hh":d=parseInt(a,10);if(d===12)d=0;if(d<0||d>11)return null;break;case "H":case "HH":d=parseInt(a,10);if(d<0||d>23)return null;break;case "m":case "mm":q=parseInt(a,10);if(q<0||q>59)return null;break;case "s":case "ss":r=parseInt(a,10);if(r<0||r>59)return null;break;case "tt":case "t":var z=a.toUpperCase();v=z===g.PMDesignator.toUpperCase();if(!v&&z!==g.AMDesignator.toUpperCase())return null;break;case "f":f=parseInt(a,10)*100;if(f<0||f>999)return null;break;case "ff":f=parseInt(a,10)*10;if(f<0||f>999)return null;break;case "fff":f=parseInt(a,10);if(f<0||f>999)return null;break;case "dddd":i=k._getDayIndex(a);if(i<0||i>6)return null;break;case "ddd":i=k._getAbbrDayIndex(a);if(i<0||i>6)return null;break;case "zzz":var u=a.split(/:/);if(u.length!==2)return null;h=parseInt(u[0],10);if(h<-12||h>13)return null;var o=parseInt(u[1],10);if(o<0||o>59)return null;n=h*60+(a.startsWith("-")?-o:o);break;case "z":case "zz":h=parseInt(a,10);if(h<-12||h>13)return null;n=h*60;break;case "g":case "gg":var p=a;if(!p||!g.eras)return null;p=p.toLowerCase().trim();for(var s=0,F=g.eras.length;s0)return this.toLocaleString();else return this.toString();var o=["n %","n%","%n"],n=["-n %","-n%","-%n"],p=["(n)","-n","- n","n-","n -"],m=["$n","n$","$ n","n $"],l=["($n)","-$n","$-n","$n-","(n$)","-n$","n-$","n$-","-n $","-$ n","n $-","$ n-","$ -n","n- $","($ n)","(n $)"];function g(a,c,d){for(var b=a.length;b1?parseInt(e[1]):0;e=b.split(".");b=e[0];a=e.length>1?e[1]:"";var q;if(c>0){a=g(a,c,false);b+=a.slice(0,c);a=a.substr(c)}else if(c<0){c=-c;b=g(b,c+1,true);a=b.slice(-c,b.length)+a;b=b.slice(0,-c)}if(i>0){if(a.length>i)a=a.slice(0,i);else a=g(a,i,false);a=p+a}else a="";var d=b.length-1,f="";while(d>=0){if(h===0||h>d)if(f.length>0)return b.slice(0,d+1)+n+f+a;else return b.slice(0,d+1)+a;if(f.length>0)f=b.slice(d-h+1,d+1)+n+f;else f=b.slice(d-h+1,d+1);d-=h;if(k1)b=parseInt(e.slice(1),10);var c;switch(e.charAt(0)){case "d":case "D":c="n";if(b!==-1)d=g(""+d,b,true);if(this<0)d=-d;break;case "c":case "C":if(this<0)c=l[a.CurrencyNegativePattern];else c=m[a.CurrencyPositivePattern];if(b===-1)b=a.CurrencyDecimalDigits;d=i(Math.abs(this),b,a.CurrencyGroupSizes,a.CurrencyGroupSeparator,a.CurrencyDecimalSeparator);break;case "n":case "N":if(this<0)c=p[a.NumberNegativePattern];else c="n";if(b===-1)b=a.NumberDecimalDigits;d=i(Math.abs(this),b,a.NumberGroupSizes,a.NumberGroupSeparator,a.NumberDecimalSeparator);break;case "p":case "P":if(this<0)c=n[a.PercentNegativePattern];else c=o[a.PercentPositivePattern];if(b===-1)b=a.PercentDecimalDigits;d=i(Math.abs(this)*100,b,a.PercentGroupSizes,a.PercentGroupSeparator,a.PercentDecimalSeparator);break;default:throw Error.format(Sys.Res.formatBadFormatSpecifier)}var k=/n|\$|-|%/g,f="";for(;true;){var q=k.lastIndex,h=k.exec(c);f+=c.slice(q,h?h.index:c.length);if(!h)break;switch(h[0]){case "n":f+=d;break;case "$":f+=a.CurrencySymbol;break;case "-":if(/[1-9]/.test(d))f+=a.NegativeSign;break;case "%":f+=a.PercentSymbol}}return f};Sys.CultureInfo=function(c,b,a){this.name=c;this.numberFormat=b;this.dateTimeFormat=a};Sys.CultureInfo.prototype={_getDateTimeFormats:function(){if(!this._dateTimeFormats){var a=this.dateTimeFormat;this._dateTimeFormats=[a.MonthDayPattern,a.YearMonthPattern,a.ShortDatePattern,a.ShortTimePattern,a.LongDatePattern,a.LongTimePattern,a.FullDateTimePattern,a.RFC1123Pattern,a.SortableDateTimePattern,a.UniversalSortableDateTimePattern]}return this._dateTimeFormats},_getIndex:function(c,d,e){var b=this._toUpper(c),a=Array.indexOf(d,b);if(a===-1)a=Array.indexOf(e,b);return a},_getMonthIndex:function(a){if(!this._upperMonths){this._upperMonths=this._toUpperArray(this.dateTimeFormat.MonthNames);this._upperMonthsGenitive=this._toUpperArray(this.dateTimeFormat.MonthGenitiveNames)}return this._getIndex(a,this._upperMonths,this._upperMonthsGenitive)},_getAbbrMonthIndex:function(a){if(!this._upperAbbrMonths){this._upperAbbrMonths=this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);this._upperAbbrMonthsGenitive=this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthGenitiveNames)}return this._getIndex(a,this._upperAbbrMonths,this._upperAbbrMonthsGenitive)},_getDayIndex:function(a){if(!this._upperDays)this._upperDays=this._toUpperArray(this.dateTimeFormat.DayNames);return Array.indexOf(this._upperDays,this._toUpper(a))},_getAbbrDayIndex:function(a){if(!this._upperAbbrDays)this._upperAbbrDays=this._toUpperArray(this.dateTimeFormat.AbbreviatedDayNames);return Array.indexOf(this._upperAbbrDays,this._toUpper(a))},_toUpperArray:function(c){var b=[];for(var a=0,d=c.length;a0)a.append(",");Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(b[c],a,false,g)}a.append("]")}else{if(Date.isInstanceOfType(b)){a.append('"\\/Date(');a.append(b.getTime());a.append(')\\/"');break}var d=[],f=0;for(var e in b){if(e.startsWith("$"))continue;if(e===Sys.Serialization.JavaScriptSerializer._serverTypeFieldName&&f!==0){d[f++]=d[0];d[0]=e}else d[f++]=e}if(i)d.sort();a.append("{");var j=false;for(c=0;c=0;c--){var f=d[c];if(!g||f.autoRemove)$removeHandler(a,b,f.handler)}}a._events=null}};Sys.UI.DomEvent._disposeHandlers=function(){Sys.UI.DomEvent._clearHandlers(this,true);var b=this._chainDispose,a=typeof b;if(a!=="undefined"){this.dispose=b;this._chainDispose=null;if(a==="function")this.dispose()}};var $removeHandler=Sys.UI.DomEvent.removeHandler=function(b,a,c){Sys.UI.DomEvent._removeHandler(b,a,c)};Sys.UI.DomEvent._removeHandler=function(a,e,f){var d=null,c=a._events[e];for(var b=0,g=c.length;b=3){d+=parseInt(b.borderLeftWidth);e+=parseInt(b.borderTopWidth)}}b=Sys.UI.DomElement._getCurrentStyle(c);var h=b?b.position:null;if(!h||h!=="absolute")for(a=c.parentNode;a;a=a.parentNode){f=a.tagName?a.tagName.toUpperCase():null;if(f!=="BODY"&&f!=="HTML"&&(a.scrollLeft||a.scrollTop)){d-=a.scrollLeft||0;e-=a.scrollTop||0}b=Sys.UI.DomElement._getCurrentStyle(a);var i=b?b.position:null;if(i&&i==="absolute")break}return new Sys.UI.Point(d,e)};else Sys.UI.DomElement.getLocation=function(d){if(d.window&&d.window===d||d.nodeType===9)return new Sys.UI.Point(0,0);var e=0,f=0,a,i=null,g=null,b=null;for(a=d;a;i=a,(g=b,a=a.offsetParent)){var c=a.tagName?a.tagName.toUpperCase():null;b=Sys.UI.DomElement._getCurrentStyle(a);if((a.offsetLeft||a.offsetTop)&&!(c==="BODY"&&(!g||g.position!=="absolute"))){e+=a.offsetLeft;f+=a.offsetTop}if(i!==null&&b){if(c!=="TABLE"&&c!=="TD"&&c!=="HTML"){e+=parseInt(b.borderLeftWidth)||0;f+=parseInt(b.borderTopWidth)||0}if(c==="TABLE"&&(b.position==="relative"||b.position==="absolute")){e+=parseInt(b.marginLeft)||0;f+=parseInt(b.marginTop)||0}}}b=Sys.UI.DomElement._getCurrentStyle(d);var h=b?b.position:null;if(!h||h!=="absolute")for(a=d.parentNode;a;a=a.parentNode){c=a.tagName?a.tagName.toUpperCase():null;if(c!=="BODY"&&c!=="HTML"&&(a.scrollLeft||a.scrollTop)){e-=a.scrollLeft||0;f-=a.scrollTop||0;b=Sys.UI.DomElement._getCurrentStyle(a);if(b){e+=parseInt(b.borderLeftWidth)||0;f+=parseInt(b.borderTopWidth)||0}}}return new Sys.UI.Point(e,f)};Sys.UI.DomElement.isDomElement=function(a){return Sys._isDomElement(a)};Sys.UI.DomElement.removeCssClass=function(d,c){var a=" "+d.className+" ",b=a.indexOf(" "+c+" ");if(b>=0)d.className=(a.substr(0,b)+" "+a.substring(b+c.length+1,a.length)).trim()};Sys.UI.DomElement.resolveElement=function(b,c){var a=b;if(!a)return null;if(typeof a==="string")a=Sys.UI.DomElement.getElementById(a,c);return a};Sys.UI.DomElement.raiseBubbleEvent=function(c,d){var b=c;while(b){var a=b.control;if(a&&a.onBubbleEvent&&a.raiseBubbleEvent){Sys.UI.DomElement._raiseBubbleEventFromControl(a,c,d);return}b=b.parentNode}};Sys.UI.DomElement._raiseBubbleEventFromControl=function(a,b,c){if(!a.onBubbleEvent(b,c))a._raiseBubbleEvent(b,c)};Sys.UI.DomElement.setLocation=function(b,c,d){var a=b.style;a.position="absolute";a.left=c+"px";a.top=d+"px"};Sys.UI.DomElement.toggleCssClass=function(b,a){if(Sys.UI.DomElement.containsCssClass(b,a))Sys.UI.DomElement.removeCssClass(b,a);else Sys.UI.DomElement.addCssClass(b,a)};Sys.UI.DomElement.getVisibilityMode=function(a){return a._visibilityMode===Sys.UI.VisibilityMode.hide?Sys.UI.VisibilityMode.hide:Sys.UI.VisibilityMode.collapse};Sys.UI.DomElement.setVisibilityMode=function(a,b){Sys.UI.DomElement._ensureOldDisplayMode(a);if(a._visibilityMode!==b){a._visibilityMode=b;if(Sys.UI.DomElement.getVisible(a)===false)if(a._visibilityMode===Sys.UI.VisibilityMode.hide)a.style.display=a._oldDisplayMode;else a.style.display="none";a._visibilityMode=b}};Sys.UI.DomElement.getVisible=function(b){var a=b.currentStyle||Sys.UI.DomElement._getCurrentStyle(b);if(!a)return true;return a.visibility!=="hidden"&&a.display!=="none"};Sys.UI.DomElement.setVisible=function(a,b){if(b!==Sys.UI.DomElement.getVisible(a)){Sys.UI.DomElement._ensureOldDisplayMode(a);a.style.visibility=b?"visible":"hidden";if(b||a._visibilityMode===Sys.UI.VisibilityMode.hide)a.style.display=a._oldDisplayMode;else a.style.display="none"}};Sys.UI.DomElement._ensureOldDisplayMode=function(a){if(!a._oldDisplayMode){var b=a.currentStyle||Sys.UI.DomElement._getCurrentStyle(a);a._oldDisplayMode=b?b.display:null;if(!a._oldDisplayMode||a._oldDisplayMode==="none")switch(a.tagName.toUpperCase()){case "DIV":case "P":case "ADDRESS":case "BLOCKQUOTE":case "BODY":case "COL":case "COLGROUP":case "DD":case "DL":case "DT":case "FIELDSET":case "FORM":case "H1":case "H2":case "H3":case "H4":case "H5":case "H6":case "HR":case "IFRAME":case "LEGEND":case "OL":case "PRE":case "TABLE":case "TD":case "TH":case "TR":case "UL":a._oldDisplayMode="block";break;case "LI":a._oldDisplayMode="list-item";break;default:a._oldDisplayMode="inline"}}};Sys.UI.DomElement._getWindow=function(a){var b=a.ownerDocument||a.document||a;return b.defaultView||b.parentWindow};Sys.UI.DomElement._getCurrentStyle=function(a){if(a.nodeType===3)return null;var c=Sys.UI.DomElement._getWindow(a);if(a.documentElement)a=a.documentElement;var b=c&&a!==c&&c.getComputedStyle?c.getComputedStyle(a,null):a.currentStyle||a.style;if(!b&&Sys.Browser.agent===Sys.Browser.Safari&&a.style){var g=a.style.display,f=a.style.position;a.style.position="absolute";a.style.display="block";var e=c.getComputedStyle(a,null);a.style.display=g;a.style.position=f;b={};for(var d in e)b[d]=e[d];b.display="none"}return b};Sys.IContainer=function(){};Sys.IContainer.prototype={};Sys.IContainer.registerInterface("Sys.IContainer");Sys.ApplicationLoadEventArgs=function(b,a){Sys.ApplicationLoadEventArgs.initializeBase(this);this._components=b;this._isPartialLoad=a};Sys.ApplicationLoadEventArgs.prototype={get_components:function(){return this._components},get_isPartialLoad:function(){return this._isPartialLoad}};Sys.ApplicationLoadEventArgs.registerClass("Sys.ApplicationLoadEventArgs",Sys.EventArgs);Sys._Application=function(){Sys._Application.initializeBase(this);this._disposableObjects=[];this._components={};this._createdComponents=[];this._secondPassComponents=[];this._unloadHandlerDelegate=Function.createDelegate(this,this._unloadHandler);Sys.UI.DomEvent.addHandler(window,"unload",this._unloadHandlerDelegate);this._domReady()};Sys._Application.prototype={_creatingComponents:false,_disposing:false,_deleteCount:0,get_isCreatingComponents:function(){return this._creatingComponents},get_isDisposing:function(){return this._disposing},add_init:function(a){if(this._initialized)a(this,Sys.EventArgs.Empty);else this.get_events().addHandler("init",a)},remove_init:function(a){this.get_events().removeHandler("init",a)},add_load:function(a){this.get_events().addHandler("load",a)},remove_load:function(a){this.get_events().removeHandler("load",a)},add_unload:function(a){this.get_events().addHandler("unload",a)},remove_unload:function(a){this.get_events().removeHandler("unload",a)},addComponent:function(a){this._components[a.get_id()]=a},beginCreateComponents:function(){this._creatingComponents=true},dispose:function(){if(!this._disposing){this._disposing=true;if(this._timerCookie){window.clearTimeout(this._timerCookie);delete this._timerCookie}if(this._endRequestHandler){Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(this._endRequestHandler);delete this._endRequestHandler}if(this._beginRequestHandler){Sys.WebForms.PageRequestManager.getInstance().remove_beginRequest(this._beginRequestHandler);delete this._beginRequestHandler}if(window.pageUnload)window.pageUnload(this,Sys.EventArgs.Empty);var c=this.get_events().getHandler("unload");if(c)c(this,Sys.EventArgs.Empty);var b=Array.clone(this._disposableObjects);for(var a=0,f=b.length;a=0;b--)this._disposeElementInternal(c[b]);if(!d)this._disposeElementInternal(a)}},endCreateComponents:function(){var b=this._secondPassComponents;for(var a=0,d=b.length;a1000){var c=[];for(var d=0,f=b.length;d=0;b--){var c=a[b];if(typeof c.dispose==="function")c.dispose()}},_disposeElementInternal:function(a){var d=a.dispose;if(d&&typeof d==="function")a.dispose();else{var c=a.control;if(c&&typeof c.dispose==="function")c.dispose()}var b=a._behaviors;if(b)this._disposeComponents(b);b=a._components;if(b){this._disposeComponents(b);a._components=null}},_domReady:function(){var a,g,f=this;function b(){f.initialize()}var c=function(){Sys.UI.DomEvent.removeHandler(window,"load",c);b()};Sys.UI.DomEvent.addHandler(window,"load",c);if(document.addEventListener)try{document.addEventListener("DOMContentLoaded",a=function(){document.removeEventListener("DOMContentLoaded",a,false);b()},false)}catch(h){}else if(document.attachEvent)if(window==window.top&&document.documentElement.doScroll){var e,d=document.createElement("div");a=function(){try{d.doScroll("left")}catch(c){e=window.setTimeout(a,0);return}d=null;b()};a()}else document.attachEvent("onreadystatechange",a=function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",a);b()}})},_raiseInit:function(){var a=this.get_events().getHandler("init");if(a){this.beginCreateComponents();a(this,Sys.EventArgs.Empty);this.endCreateComponents()}},_unloadHandler:function(){this.dispose()}};Sys._Application.registerClass("Sys._Application",Sys.Component,Sys.IContainer);Sys.Application=new Sys._Application;var $find=Sys.Application.findComponent;Sys.UI.Behavior=function(b){Sys.UI.Behavior.initializeBase(this);this._element=b;var a=b._behaviors;if(!a)b._behaviors=[this];else a[a.length]=this};Sys.UI.Behavior.prototype={_name:null,get_element:function(){return this._element},get_id:function(){var a=Sys.UI.Behavior.callBaseMethod(this,"get_id");if(a)return a;if(!this._element||!this._element.id)return "";return this._element.id+"$"+this.get_name()},get_name:function(){if(this._name)return this._name;var a=Object.getTypeName(this),b=a.lastIndexOf(".");if(b!==-1)a=a.substr(b+1);if(!this.get_isInitialized())this._name=a;return a},set_name:function(a){this._name=a},initialize:function(){Sys.UI.Behavior.callBaseMethod(this,"initialize");var a=this.get_name();if(a)this._element[a]=this},dispose:function(){Sys.UI.Behavior.callBaseMethod(this,"dispose");var a=this._element;if(a){var c=this.get_name();if(c)a[c]=null;var b=a._behaviors;Array.remove(b,this);if(b.length===0)a._behaviors=null;delete this._element}}};Sys.UI.Behavior.registerClass("Sys.UI.Behavior",Sys.Component);Sys.UI.Behavior.getBehaviorByName=function(b,c){var a=b[c];return a&&Sys.UI.Behavior.isInstanceOfType(a)?a:null};Sys.UI.Behavior.getBehaviors=function(a){if(!a._behaviors)return [];return Array.clone(a._behaviors)};Sys.UI.Behavior.getBehaviorsByType=function(d,e){var a=d._behaviors,c=[];if(a)for(var b=0,f=a.length;b0&&a.charAt(0)==="#")a=a.substring(1);return a};Sys._Application.prototype.get_enableHistory=function(){return this._enableHistory};Sys._Application.prototype.set_enableHistory=function(a){this._enableHistory=a};Sys._Application.prototype.add_navigate=function(a){this.get_events().addHandler("navigate",a)};Sys._Application.prototype.remove_navigate=function(a){this.get_events().removeHandler("navigate",a)};Sys._Application.prototype.addHistoryPoint=function(c,f){this._ensureHistory();var b=this._state;for(var a in c){var d=c[a];if(d===null){if(typeof b[a]!=="undefined")delete b[a]}else b[a]=d}var e=this._serializeState(b);this._historyPointIsNew=true;this._setState(e,f);this._raiseNavigate()};Sys._Application.prototype.setServerId=function(a,b){this._clientId=a;this._uniqueId=b};Sys._Application.prototype.setServerState=function(a){this._ensureHistory();this._state.__s=a;this._updateHiddenField(a)};Sys._Application.prototype._deserializeState=function(a){var e={};a=a||"";var b=a.indexOf("&&");if(b!==-1&&b+2'");c.write(""+(b||document.title)+"parent.Sys.Application._onIFrameLoad('+Sys.Serialization.JavaScriptSerializer.serialize(a)+");");c.close()}this._ignoreTimer=false;this._currentEntry=a;if(this._historyFrame||this._historyPointIsNew){var f=this.get_stateString();if(a!==f){window.location.hash=a;this._currentEntry=this.get_stateString();if(typeof b!=="undefined"&&b!==null)document.title=b}}this._historyPointIsNew=false}}};Sys._Application.prototype._updateHiddenField=function(b){if(this._clientId){var a=document.getElementById(this._clientId);if(a)a.value=b}};if(!window.XMLHttpRequest)window.XMLHttpRequest=function(){var b=["Msxml2.XMLHTTP.3.0","Msxml2.XMLHTTP"];for(var a=0,c=b.length;a0)this._timer=window.setTimeout(Function.createDelegate(this,this._onTimeout),d);this._xmlHttpRequest.send(c);this._started=true},getResponseHeader:function(b){var a;try{a=this._xmlHttpRequest.getResponseHeader(b)}catch(c){}if(!a)a="";return a},getAllResponseHeaders:function(){return this._xmlHttpRequest.getAllResponseHeaders()},get_responseData:function(){return this._xmlHttpRequest.responseText},get_statusCode:function(){var a=0;try{a=this._xmlHttpRequest.status}catch(b){}return a},get_statusText:function(){return this._xmlHttpRequest.statusText},get_xml:function(){var a=this._xmlHttpRequest.responseXML;if(!a||!a.documentElement){a=Sys.Net.XMLDOM(this._xmlHttpRequest.responseText);if(!a||!a.documentElement)return null}else if(navigator.userAgent.indexOf("MSIE")!==-1)a.setProperty("SelectionLanguage","XPath");if(a.documentElement.namespaceURI==="http://www.mozilla.org/newlayout/xml/parsererror.xml"&&a.documentElement.tagName==="parsererror")return null;if(a.documentElement.firstChild&&a.documentElement.firstChild.tagName==="parsererror")return null;return a},abort:function(){if(this._aborted||this._responseAvailable||this._timedOut)return;this._aborted=true;this._clearTimer();if(this._xmlHttpRequest&&!this._responseAvailable){this._xmlHttpRequest.onreadystatechange=Function.emptyMethod;this._xmlHttpRequest.abort();this._xmlHttpRequest=null;this._webRequest.completed(Sys.EventArgs.Empty)}}};Sys.Net.XMLHttpExecutor.registerClass("Sys.Net.XMLHttpExecutor",Sys.Net.WebRequestExecutor);Sys.Net._WebRequestManager=function(){this._defaultTimeout=0;this._defaultExecutorType="Sys.Net.XMLHttpExecutor"};Sys.Net._WebRequestManager.prototype={add_invokingRequest:function(a){this._get_eventHandlerList().addHandler("invokingRequest",a)},remove_invokingRequest:function(a){this._get_eventHandlerList().removeHandler("invokingRequest",a)},add_completedRequest:function(a){this._get_eventHandlerList().addHandler("completedRequest",a)},remove_completedRequest:function(a){this._get_eventHandlerList().removeHandler("completedRequest",a)},_get_eventHandlerList:function(){if(!this._events)this._events=new Sys.EventHandlerList;return this._events},get_defaultTimeout:function(){return this._defaultTimeout},set_defaultTimeout:function(a){this._defaultTimeout=a},get_defaultExecutorType:function(){return this._defaultExecutorType},set_defaultExecutorType:function(a){this._defaultExecutorType=a},executeRequest:function(webRequest){var executor=webRequest.get_executor();if(!executor){var failed=false;try{var executorType=eval(this._defaultExecutorType);executor=new executorType}catch(a){failed=true}webRequest.set_executor(executor)}if(executor.get_aborted())return;var evArgs=new Sys.Net.NetworkRequestEventArgs(webRequest),handler=this._get_eventHandlerList().getHandler("invokingRequest");if(handler)handler(this,evArgs);if(!evArgs.get_cancel())executor.executeRequest()}};Sys.Net._WebRequestManager.registerClass("Sys.Net._WebRequestManager");Sys.Net.WebRequestManager=new Sys.Net._WebRequestManager;Sys.Net.NetworkRequestEventArgs=function(a){Sys.Net.NetworkRequestEventArgs.initializeBase(this);this._webRequest=a};Sys.Net.NetworkRequestEventArgs.prototype={get_webRequest:function(){return this._webRequest}};Sys.Net.NetworkRequestEventArgs.registerClass("Sys.Net.NetworkRequestEventArgs",Sys.CancelEventArgs);Sys.Net.WebRequest=function(){this._url="";this._headers={};this._body=null;this._userContext=null;this._httpVerb=null;this._executor=null;this._invokeCalled=false;this._timeout=0};Sys.Net.WebRequest.prototype={add_completed:function(a){this._get_eventHandlerList().addHandler("completed",a)},remove_completed:function(a){this._get_eventHandlerList().removeHandler("completed",a)},completed:function(b){var a=Sys.Net.WebRequestManager._get_eventHandlerList().getHandler("completedRequest");if(a)a(this._executor,b);a=this._get_eventHandlerList().getHandler("completed");if(a)a(this._executor,b)},_get_eventHandlerList:function(){if(!this._events)this._events=new Sys.EventHandlerList;return this._events},get_url:function(){return this._url},set_url:function(a){this._url=a},get_headers:function(){return this._headers},get_httpVerb:function(){if(this._httpVerb===null){if(this._body===null)return "GET";return "POST"}return this._httpVerb},set_httpVerb:function(a){this._httpVerb=a},get_body:function(){return this._body},set_body:function(a){this._body=a},get_userContext:function(){return this._userContext},set_userContext:function(a){this._userContext=a},get_executor:function(){return this._executor},set_executor:function(a){this._executor=a;this._executor._set_webRequest(this)},get_timeout:function(){if(this._timeout===0)return Sys.Net.WebRequestManager.get_defaultTimeout();return this._timeout},set_timeout:function(a){this._timeout=a},getResolvedUrl:function(){return Sys.Net.WebRequest._resolveUrl(this._url)},invoke:function(){Sys.Net.WebRequestManager.executeRequest(this);this._invokeCalled=true}};Sys.Net.WebRequest._resolveUrl=function(b,a){if(b&&b.indexOf("://")!==-1)return b;if(!a||a.length===0){var d=document.getElementsByTagName("base")[0];if(d&&d.href&&d.href.length>0)a=d.href;else a=document.URL}var c=a.indexOf("?");if(c!==-1)a=a.substr(0,c);c=a.indexOf("#");if(c!==-1)a=a.substr(0,c);a=a.substr(0,a.lastIndexOf("/")+1);if(!b||b.length===0)return a;if(b.charAt(0)==="/"){var e=a.indexOf("://"),g=a.indexOf("/",e+3);return a.substr(0,g)+b}else{var f=a.lastIndexOf("/");return a.substr(0,f+1)+b}};Sys.Net.WebRequest._createQueryString=function(c,b,f){b=b||encodeURIComponent;var h=0,e,g,d,a=new Sys.StringBuilder;if(c)for(d in c){e=c[d];if(typeof e==="function")continue;g=Sys.Serialization.JavaScriptSerializer.serialize(e);if(h++)a.append("&");a.append(d);a.append("=");a.append(b(g))}if(f){if(h)a.append("&");a.append(f)}return a.toString()};Sys.Net.WebRequest._createUrl=function(a,b,c){if(!b&&!c)return a;var d=Sys.Net.WebRequest._createQueryString(b,null,c);return d.length?a+(a&&a.indexOf("?")>=0?"&":"?")+d:a};Sys.Net.WebRequest.registerClass("Sys.Net.WebRequest");Sys._ScriptLoaderTask=function(b,a){this._scriptElement=b;this._completedCallback=a};Sys._ScriptLoaderTask.prototype={get_scriptElement:function(){return this._scriptElement},dispose:function(){if(this._disposed)return;this._disposed=true;this._removeScriptElementHandlers();Sys._ScriptLoaderTask._clearScript(this._scriptElement);this._scriptElement=null},execute:function(){this._addScriptElementHandlers();document.getElementsByTagName("head")[0].appendChild(this._scriptElement)},_addScriptElementHandlers:function(){this._scriptLoadDelegate=Function.createDelegate(this,this._scriptLoadHandler);if(Sys.Browser.agent!==Sys.Browser.InternetExplorer){this._scriptElement.readyState="loaded";$addHandler(this._scriptElement,"load",this._scriptLoadDelegate)}else $addHandler(this._scriptElement,"readystatechange",this._scriptLoadDelegate);if(this._scriptElement.addEventListener){this._scriptErrorDelegate=Function.createDelegate(this,this._scriptErrorHandler);this._scriptElement.addEventListener("error",this._scriptErrorDelegate,false)}},_removeScriptElementHandlers:function(){if(this._scriptLoadDelegate){var a=this.get_scriptElement();if(Sys.Browser.agent!==Sys.Browser.InternetExplorer)$removeHandler(a,"load",this._scriptLoadDelegate);else $removeHandler(a,"readystatechange",this._scriptLoadDelegate);if(this._scriptErrorDelegate){this._scriptElement.removeEventListener("error",this._scriptErrorDelegate,false);this._scriptErrorDelegate=null}this._scriptLoadDelegate=null}},_scriptErrorHandler:function(){if(this._disposed)return;this._completedCallback(this.get_scriptElement(),false)},_scriptLoadHandler:function(){if(this._disposed)return;var a=this.get_scriptElement();if(a.readyState!=="loaded"&&a.readyState!=="complete")return;this._completedCallback(a,true)}};Sys._ScriptLoaderTask.registerClass("Sys._ScriptLoaderTask",null,Sys.IDisposable);Sys._ScriptLoaderTask._clearScript=function(a){if(!Sys.Debug.isDebug)a.parentNode.removeChild(a)};Type.registerNamespace("Sys.Net");Sys.Net.WebServiceProxy=function(){};Sys.Net.WebServiceProxy.prototype={get_timeout:function(){return this._timeout||0},set_timeout:function(a){if(a<0)throw Error.argumentOutOfRange("value",a,Sys.Res.invalidTimeout);this._timeout=a},get_defaultUserContext:function(){return typeof this._userContext==="undefined"?null:this._userContext},set_defaultUserContext:function(a){this._userContext=a},get_defaultSucceededCallback:function(){return this._succeeded||null},set_defaultSucceededCallback:function(a){this._succeeded=a},get_defaultFailedCallback:function(){return this._failed||null},set_defaultFailedCallback:function(a){this._failed=a},get_enableJsonp:function(){return !!this._jsonp},set_enableJsonp:function(a){this._jsonp=a},get_path:function(){return this._path||null},set_path:function(a){this._path=a},get_jsonpCallbackParameter:function(){return this._callbackParameter||"callback"},set_jsonpCallbackParameter:function(a){this._callbackParameter=a},_invoke:function(d,e,g,f,c,b,a){c=c||this.get_defaultSucceededCallback();b=b||this.get_defaultFailedCallback();if(a===null||typeof a==="undefined")a=this.get_defaultUserContext();return Sys.Net.WebServiceProxy.invoke(d,e,g,f,c,b,a,this.get_timeout(),this.get_enableJsonp(),this.get_jsonpCallbackParameter())}};Sys.Net.WebServiceProxy.registerClass("Sys.Net.WebServiceProxy");Sys.Net.WebServiceProxy.invoke=function(q,a,m,l,j,b,g,e,w,p){var i=w!==false?Sys.Net.WebServiceProxy._xdomain.exec(q):null,c,n=i&&i.length===3&&(i[1]!==location.protocol||i[2]!==location.host);m=n||m;if(n){p=p||"callback";c="_jsonp"+Sys._jsonp++}if(!l)l={};var r=l;if(!m||!r)r={};var s,h,f=null,k,o=null,u=Sys.Net.WebRequest._createUrl(a?q+"/"+encodeURIComponent(a):q,r,n?p+"=Sys."+c:null);if(n){s=document.createElement("script");s.src=u;k=new Sys._ScriptLoaderTask(s,function(d,b){if(!b||c)t({Message:String.format(Sys.Res.webServiceFailedNoMsg,a)},-1)});function v(){if(f===null)return;f=null;h=new Sys.Net.WebServiceError(true,String.format(Sys.Res.webServiceTimedOut,a));k.dispose();delete Sys[c];if(b)b(h,g,a)}function t(d,e){if(f!==null){window.clearTimeout(f);f=null}k.dispose();delete Sys[c];c=null;if(typeof e!=="undefined"&&e!==200){if(b){h=new Sys.Net.WebServiceError(false,d.Message||String.format(Sys.Res.webServiceFailedNoMsg,a),d.StackTrace||null,d.ExceptionType||null,d);h._statusCode=e;b(h,g,a)}}else if(j)j(d,g,a)}Sys[c]=t;e=e||Sys.Net.WebRequestManager.get_defaultTimeout();if(e>0)f=window.setTimeout(v,e);k.execute();return null}var d=new Sys.Net.WebRequest;d.set_url(u);d.get_headers()["Content-Type"]="application/json; charset=utf-8";if(!m){o=Sys.Serialization.JavaScriptSerializer.serialize(l);if(o==="{}")o=""}d.set_body(o);d.add_completed(x);if(e&&e>0)d.set_timeout(e);d.invoke();function x(d){if(d.get_responseAvailable()){var f=d.get_statusCode(),c=null;try{var e=d.getResponseHeader("Content-Type");if(e.startsWith("application/json"))c=d.get_object();else if(e.startsWith("text/xml"))c=d.get_xml();else c=d.get_responseData()}catch(m){}var k=d.getResponseHeader("jsonerror"),h=k==="true";if(h){if(c)c=new Sys.Net.WebServiceError(false,c.Message,c.StackTrace,c.ExceptionType,c)}else if(e.startsWith("application/json"))c=!c||typeof c.d==="undefined"?c:c.d;if(f<200||f>=300||h){if(b){if(!c||!h)c=new Sys.Net.WebServiceError(false,String.format(Sys.Res.webServiceFailedNoMsg,a));c._statusCode=f;b(c,g,a)}}else if(j)j(c,g,a)}else{var i;if(d.get_timedOut())i=String.format(Sys.Res.webServiceTimedOut,a);else i=String.format(Sys.Res.webServiceFailedNoMsg,a);if(b)b(new Sys.Net.WebServiceError(d.get_timedOut(),i,"",""),g,a)}}return d};Sys.Net.WebServiceProxy._generateTypedConstructor=function(a){return function(b){if(b)for(var c in b)this[c]=b[c];this.__type=a}};Sys._jsonp=0;Sys.Net.WebServiceProxy._xdomain=/^\s*([a-zA-Z0-9\+\-\.]+\:)\/\/([^?#\/]+)/;Sys.Net.WebServiceError=function(d,e,c,a,b){this._timedOut=d;this._message=e;this._stackTrace=c;this._exceptionType=a;this._errorObject=b;this._statusCode=-1};Sys.Net.WebServiceError.prototype={get_timedOut:function(){return this._timedOut},get_statusCode:function(){return this._statusCode},get_message:function(){return this._message},get_stackTrace:function(){return this._stackTrace||""},get_exceptionType:function(){return this._exceptionType||""},get_errorObject:function(){return this._errorObject||null}};Sys.Net.WebServiceError.registerClass("Sys.Net.WebServiceError"); -Type.registerNamespace('Sys');Sys.Res={'argumentInteger':'Value must be an integer.','invokeCalledTwice':'Cannot call invoke more than once.','webServiceFailed':'The server method \'{0}\' failed with the following error: {1}','argumentType':'Object cannot be converted to the required type.','argumentNull':'Value cannot be null.','scriptAlreadyLoaded':'The script \'{0}\' has been referenced multiple times. If referencing Microsoft AJAX scripts explicitly, set the MicrosoftAjaxMode property of the ScriptManager to Explicit.','scriptDependencyNotFound':'The script \'{0}\' failed to load because it is dependent on script \'{1}\'.','formatBadFormatSpecifier':'Format specifier was invalid.','requiredScriptReferenceNotIncluded':'\'{0}\' requires that you have included a script reference to \'{1}\'.','webServiceFailedNoMsg':'The server method \'{0}\' failed.','argumentDomElement':'Value must be a DOM element.','invalidExecutorType':'Could not create a valid Sys.Net.WebRequestExecutor from: {0}.','cannotCallBeforeResponse':'Cannot call {0} when responseAvailable is false.','actualValue':'Actual value was {0}.','enumInvalidValue':'\'{0}\' is not a valid value for enum {1}.','scriptLoadFailed':'The script \'{0}\' could not be loaded.','parameterCount':'Parameter count mismatch.','cannotDeserializeEmptyString':'Cannot deserialize empty string.','formatInvalidString':'Input string was not in a correct format.','invalidTimeout':'Value must be greater than or equal to zero.','cannotAbortBeforeStart':'Cannot abort when executor has not started.','argument':'Value does not fall within the expected range.','cannotDeserializeInvalidJson':'Cannot deserialize. The data does not correspond to valid JSON.','invalidHttpVerb':'httpVerb cannot be set to an empty or null string.','nullWebRequest':'Cannot call executeRequest with a null webRequest.','eventHandlerInvalid':'Handler was not added through the Sys.UI.DomEvent.addHandler method.','cannotSerializeNonFiniteNumbers':'Cannot serialize non finite numbers.','argumentUndefined':'Value cannot be undefined.','webServiceInvalidReturnType':'The server method \'{0}\' returned an invalid type. Expected type: {1}','servicePathNotSet':'The path to the web service has not been set.','argumentTypeWithTypes':'Object of type \'{0}\' cannot be converted to type \'{1}\'.','cannotCallOnceStarted':'Cannot call {0} once started.','badBaseUrl1':'Base URL does not contain ://.','badBaseUrl2':'Base URL does not contain another /.','badBaseUrl3':'Cannot find last / in base URL.','setExecutorAfterActive':'Cannot set executor after it has become active.','paramName':'Parameter name: {0}','nullReferenceInPath':'Null reference while evaluating data path: \'{0}\'.','cannotCallOutsideHandler':'Cannot call {0} outside of a completed event handler.','cannotSerializeObjectWithCycle':'Cannot serialize object with cyclic reference within child properties.','format':'One of the identified items was in an invalid format.','assertFailedCaller':'Assertion Failed: {0}\r\nat {1}','argumentOutOfRange':'Specified argument was out of the range of valid values.','webServiceTimedOut':'The server method \'{0}\' timed out.','notImplemented':'The method or operation is not implemented.','assertFailed':'Assertion Failed: {0}','invalidOperation':'Operation is not valid due to the current state of the object.','breakIntoDebugger':'{0}\r\n\r\nBreak into debugger?'}; diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftMvcAjax.debug.js b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftMvcAjax.debug.js deleted file mode 100644 index 3a39062..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftMvcAjax.debug.js +++ /dev/null @@ -1,408 +0,0 @@ -//!---------------------------------------------------------- -//! Copyright (C) Microsoft Corporation. All rights reserved. -//!---------------------------------------------------------- -//! MicrosoftMvcAjax.js - -Type.registerNamespace('Sys.Mvc'); - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.AjaxOptions - -Sys.Mvc.$create_AjaxOptions = function Sys_Mvc_AjaxOptions() { return {}; } - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.InsertionMode - -Sys.Mvc.InsertionMode = function() { - /// - /// - /// - /// - /// - /// -}; -Sys.Mvc.InsertionMode.prototype = { - replace: 0, - insertBefore: 1, - insertAfter: 2 -} -Sys.Mvc.InsertionMode.registerEnum('Sys.Mvc.InsertionMode', false); - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.AjaxContext - -Sys.Mvc.AjaxContext = function Sys_Mvc_AjaxContext(request, updateTarget, loadingElement, insertionMode) { - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - this._request = request; - this._updateTarget = updateTarget; - this._loadingElement = loadingElement; - this._insertionMode = insertionMode; -} -Sys.Mvc.AjaxContext.prototype = { - _insertionMode: 0, - _loadingElement: null, - _response: null, - _request: null, - _updateTarget: null, - - get_data: function Sys_Mvc_AjaxContext$get_data() { - /// - if (this._response) { - return this._response.get_responseData(); - } - else { - return null; - } - }, - - get_insertionMode: function Sys_Mvc_AjaxContext$get_insertionMode() { - /// - return this._insertionMode; - }, - - get_loadingElement: function Sys_Mvc_AjaxContext$get_loadingElement() { - /// - return this._loadingElement; - }, - - get_object: function Sys_Mvc_AjaxContext$get_object() { - /// - var executor = this.get_response(); - return (executor) ? executor.get_object() : null; - }, - - get_response: function Sys_Mvc_AjaxContext$get_response() { - /// - return this._response; - }, - set_response: function Sys_Mvc_AjaxContext$set_response(value) { - /// - this._response = value; - return value; - }, - - get_request: function Sys_Mvc_AjaxContext$get_request() { - /// - return this._request; - }, - - get_updateTarget: function Sys_Mvc_AjaxContext$get_updateTarget() { - /// - return this._updateTarget; - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.AsyncHyperlink - -Sys.Mvc.AsyncHyperlink = function Sys_Mvc_AsyncHyperlink() { -} -Sys.Mvc.AsyncHyperlink.handleClick = function Sys_Mvc_AsyncHyperlink$handleClick(anchor, evt, ajaxOptions) { - /// - /// - /// - /// - /// - /// - evt.preventDefault(); - Sys.Mvc.MvcHelpers._asyncRequest(anchor.href, 'post', '', anchor, ajaxOptions); -} - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.MvcHelpers - -Sys.Mvc.MvcHelpers = function Sys_Mvc_MvcHelpers() { -} -Sys.Mvc.MvcHelpers._serializeSubmitButton = function Sys_Mvc_MvcHelpers$_serializeSubmitButton(element, offsetX, offsetY) { - /// - /// - /// - /// - /// - /// - /// - if (element.disabled) { - return null; - } - var name = element.name; - if (name) { - var tagName = element.tagName.toUpperCase(); - var encodedName = encodeURIComponent(name); - var inputElement = element; - if (tagName === 'INPUT') { - var type = inputElement.type; - if (type === 'submit') { - return encodedName + '=' + encodeURIComponent(inputElement.value); - } - else if (type === 'image') { - return encodedName + '.x=' + offsetX + '&' + encodedName + '.y=' + offsetY; - } - } - else if ((tagName === 'BUTTON') && (name.length) && (inputElement.type === 'submit')) { - return encodedName + '=' + encodeURIComponent(inputElement.value); - } - } - return null; -} -Sys.Mvc.MvcHelpers._serializeForm = function Sys_Mvc_MvcHelpers$_serializeForm(form) { - /// - /// - /// - var formElements = form.elements; - var formBody = new Sys.StringBuilder(); - var count = formElements.length; - for (var i = 0; i < count; i++) { - var element = formElements[i]; - var name = element.name; - if (!name || !name.length) { - continue; - } - var tagName = element.tagName.toUpperCase(); - if (tagName === 'INPUT') { - var inputElement = element; - var type = inputElement.type; - if ((type === 'text') || (type === 'password') || (type === 'hidden') || (((type === 'checkbox') || (type === 'radio')) && element.checked)) { - formBody.append(encodeURIComponent(name)); - formBody.append('='); - formBody.append(encodeURIComponent(inputElement.value)); - formBody.append('&'); - } - } - else if (tagName === 'SELECT') { - var selectElement = element; - var optionCount = selectElement.options.length; - for (var j = 0; j < optionCount; j++) { - var optionElement = selectElement.options[j]; - if (optionElement.selected) { - formBody.append(encodeURIComponent(name)); - formBody.append('='); - formBody.append(encodeURIComponent(optionElement.value)); - formBody.append('&'); - } - } - } - else if (tagName === 'TEXTAREA') { - formBody.append(encodeURIComponent(name)); - formBody.append('='); - formBody.append(encodeURIComponent((element.value))); - formBody.append('&'); - } - } - var additionalInput = form._additionalInput; - if (additionalInput) { - formBody.append(additionalInput); - formBody.append('&'); - } - return formBody.toString(); -} -Sys.Mvc.MvcHelpers._asyncRequest = function Sys_Mvc_MvcHelpers$_asyncRequest(url, verb, body, triggerElement, ajaxOptions) { - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - if (ajaxOptions.confirm) { - if (!confirm(ajaxOptions.confirm)) { - return; - } - } - if (ajaxOptions.url) { - url = ajaxOptions.url; - } - if (ajaxOptions.httpMethod) { - verb = ajaxOptions.httpMethod; - } - if (body.length > 0 && !body.endsWith('&')) { - body += '&'; - } - body += 'X-Requested-With=XMLHttpRequest'; - var upperCaseVerb = verb.toUpperCase(); - var isGetOrPost = (upperCaseVerb === 'GET' || upperCaseVerb === 'POST'); - if (!isGetOrPost) { - body += '&'; - body += 'X-HTTP-Method-Override=' + upperCaseVerb; - } - var requestBody = ''; - if (upperCaseVerb === 'GET' || upperCaseVerb === 'DELETE') { - if (url.indexOf('?') > -1) { - if (!url.endsWith('&')) { - url += '&'; - } - url += body; - } - else { - url += '?'; - url += body; - } - } - else { - requestBody = body; - } - var request = new Sys.Net.WebRequest(); - request.set_url(url); - if (isGetOrPost) { - request.set_httpVerb(verb); - } - else { - request.set_httpVerb('POST'); - request.get_headers()['X-HTTP-Method-Override'] = upperCaseVerb; - } - request.set_body(requestBody); - if (verb.toUpperCase() === 'PUT') { - request.get_headers()['Content-Type'] = 'application/x-www-form-urlencoded;'; - } - request.get_headers()['X-Requested-With'] = 'XMLHttpRequest'; - var updateElement = null; - if (ajaxOptions.updateTargetId) { - updateElement = $get(ajaxOptions.updateTargetId); - } - var loadingElement = null; - if (ajaxOptions.loadingElementId) { - loadingElement = $get(ajaxOptions.loadingElementId); - } - var ajaxContext = new Sys.Mvc.AjaxContext(request, updateElement, loadingElement, ajaxOptions.insertionMode); - var continueRequest = true; - if (ajaxOptions.onBegin) { - continueRequest = ajaxOptions.onBegin(ajaxContext) !== false; - } - if (loadingElement) { - Sys.UI.DomElement.setVisible(ajaxContext.get_loadingElement(), true); - } - if (continueRequest) { - request.add_completed(Function.createDelegate(null, function(executor) { - Sys.Mvc.MvcHelpers._onComplete(request, ajaxOptions, ajaxContext); - })); - request.invoke(); - } -} -Sys.Mvc.MvcHelpers._onComplete = function Sys_Mvc_MvcHelpers$_onComplete(request, ajaxOptions, ajaxContext) { - /// - /// - /// - /// - /// - /// - ajaxContext.set_response(request.get_executor()); - if (ajaxOptions.onComplete && ajaxOptions.onComplete(ajaxContext) === false) { - return; - } - var statusCode = ajaxContext.get_response().get_statusCode(); - if ((statusCode >= 200 && statusCode < 300) || statusCode === 304 || statusCode === 1223) { - if (statusCode !== 204 && statusCode !== 304 && statusCode !== 1223) { - var contentType = ajaxContext.get_response().getResponseHeader('Content-Type'); - if ((contentType) && (contentType.indexOf('application/x-javascript') !== -1)) { - eval(ajaxContext.get_data()); - } - else { - Sys.Mvc.MvcHelpers.updateDomElement(ajaxContext.get_updateTarget(), ajaxContext.get_insertionMode(), ajaxContext.get_data()); - } - } - if (ajaxOptions.onSuccess) { - ajaxOptions.onSuccess(ajaxContext); - } - } - else { - if (ajaxOptions.onFailure) { - ajaxOptions.onFailure(ajaxContext); - } - } - if (ajaxContext.get_loadingElement()) { - Sys.UI.DomElement.setVisible(ajaxContext.get_loadingElement(), false); - } -} -Sys.Mvc.MvcHelpers.updateDomElement = function Sys_Mvc_MvcHelpers$updateDomElement(target, insertionMode, content) { - /// - /// - /// - /// - /// - /// - if (target) { - switch (insertionMode) { - case Sys.Mvc.InsertionMode.replace: - target.innerHTML = content; - break; - case Sys.Mvc.InsertionMode.insertBefore: - if (content && content.length > 0) { - target.innerHTML = content + target.innerHTML.trimStart(); - } - break; - case Sys.Mvc.InsertionMode.insertAfter: - if (content && content.length > 0) { - target.innerHTML = target.innerHTML.trimEnd() + content; - } - break; - } - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.AsyncForm - -Sys.Mvc.AsyncForm = function Sys_Mvc_AsyncForm() { -} -Sys.Mvc.AsyncForm.handleClick = function Sys_Mvc_AsyncForm$handleClick(form, evt) { - /// - /// - /// - /// - var additionalInput = Sys.Mvc.MvcHelpers._serializeSubmitButton(evt.target, evt.offsetX, evt.offsetY); - form._additionalInput = additionalInput; -} -Sys.Mvc.AsyncForm.handleSubmit = function Sys_Mvc_AsyncForm$handleSubmit(form, evt, ajaxOptions) { - /// - /// - /// - /// - /// - /// - evt.preventDefault(); - var validationCallbacks = form.validationCallbacks; - if (validationCallbacks) { - for (var i = 0; i < validationCallbacks.length; i++) { - var callback = validationCallbacks[i]; - if (!callback()) { - return; - } - } - } - var body = Sys.Mvc.MvcHelpers._serializeForm(form); - Sys.Mvc.MvcHelpers._asyncRequest(form.action, form.method || 'post', body, form, ajaxOptions); -} - - -Sys.Mvc.AjaxContext.registerClass('Sys.Mvc.AjaxContext'); -Sys.Mvc.AsyncHyperlink.registerClass('Sys.Mvc.AsyncHyperlink'); -Sys.Mvc.MvcHelpers.registerClass('Sys.Mvc.MvcHelpers'); -Sys.Mvc.AsyncForm.registerClass('Sys.Mvc.AsyncForm'); - -// ---- Do not remove this footer ---- -// Generated using Script# v0.5.0.0 (http://projects.nikhilk.net) -// ----------------------------------- diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftMvcAjax.js b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftMvcAjax.js deleted file mode 100644 index 275103c..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftMvcAjax.js +++ /dev/null @@ -1,25 +0,0 @@ -//---------------------------------------------------------- -// Copyright (C) Microsoft Corporation. All rights reserved. -//---------------------------------------------------------- -// MicrosoftMvcAjax.js - -Type.registerNamespace('Sys.Mvc');Sys.Mvc.$create_AjaxOptions=function(){return {};} -Sys.Mvc.InsertionMode=function(){};Sys.Mvc.InsertionMode.prototype = {replace:0,insertBefore:1,insertAfter:2} -Sys.Mvc.InsertionMode.registerEnum('Sys.Mvc.InsertionMode',false);Sys.Mvc.AjaxContext=function(request,updateTarget,loadingElement,insertionMode){this.$3=request;this.$4=updateTarget;this.$1=loadingElement;this.$0=insertionMode;} -Sys.Mvc.AjaxContext.prototype={$0:0,$1:null,$2:null,$3:null,$4:null,get_data:function(){if(this.$2){return this.$2.get_responseData();}else{return null;}},get_insertionMode:function(){return this.$0;},get_loadingElement:function(){return this.$1;},get_object:function(){var $0=this.get_response();return ($0)?$0.get_object():null;},get_response:function(){return this.$2;},set_response:function(value){this.$2=value;return value;},get_request:function(){return this.$3;},get_updateTarget:function(){return this.$4;}} -Sys.Mvc.AsyncHyperlink=function(){} -Sys.Mvc.AsyncHyperlink.handleClick=function(anchor,evt,ajaxOptions){evt.preventDefault();Sys.Mvc.MvcHelpers.$2(anchor.href,'post','',anchor,ajaxOptions);} -Sys.Mvc.MvcHelpers=function(){} -Sys.Mvc.MvcHelpers.$0=function($p0,$p1,$p2){if($p0.disabled){return null;}var $0=$p0.name;if($0){var $1=$p0.tagName.toUpperCase();var $2=encodeURIComponent($0);var $3=$p0;if($1==='INPUT'){var $4=$3.type;if($4==='submit'){return $2+'='+encodeURIComponent($3.value);}else if($4==='image'){return $2+'.x='+$p1+'&'+$2+'.y='+$p2;}}else if(($1==='BUTTON')&&($0.length)&&($3.type==='submit')){return $2+'='+encodeURIComponent($3.value);}}return null;} -Sys.Mvc.MvcHelpers.$1=function($p0){var $0=$p0.elements;var $1=new Sys.StringBuilder();var $2=$0.length;for(var $4=0;$4<$2;$4++){var $5=$0[$4];var $6=$5.name;if(!$6||!$6.length){continue;}var $7=$5.tagName.toUpperCase();if($7==='INPUT'){var $8=$5;var $9=$8.type;if(($9==='text')||($9==='password')||($9==='hidden')||((($9==='checkbox')||($9==='radio'))&&$5.checked)){$1.append(encodeURIComponent($6));$1.append('=');$1.append(encodeURIComponent($8.value));$1.append('&');}}else if($7==='SELECT'){var $A=$5;var $B=$A.options.length;for(var $C=0;$C<$B;$C++){var $D=$A.options[$C];if($D.selected){$1.append(encodeURIComponent($6));$1.append('=');$1.append(encodeURIComponent($D.value));$1.append('&');}}}else if($7==='TEXTAREA'){$1.append(encodeURIComponent($6));$1.append('=');$1.append(encodeURIComponent(($5.value)));$1.append('&');}}var $3=$p0._additionalInput;if($3){$1.append($3);$1.append('&');}return $1.toString();} -Sys.Mvc.MvcHelpers.$2=function($p0,$p1,$p2,$p3,$p4){if($p4.confirm){if(!confirm($p4.confirm)){return;}}if($p4.url){$p0=$p4.url;}if($p4.httpMethod){$p1=$p4.httpMethod;}if($p2.length>0&&!$p2.endsWith('&')){$p2+='&';}$p2+='X-Requested-With=XMLHttpRequest';var $0=$p1.toUpperCase();var $1=($0==='GET'||$0==='POST');if(!$1){$p2+='&';$p2+='X-HTTP-Method-Override='+$0;}var $2='';if($0==='GET'||$0==='DELETE'){if($p0.indexOf('?')>-1){if(!$p0.endsWith('&')){$p0+='&';}$p0+=$p2;}else{$p0+='?';$p0+=$p2;}}else{$2=$p2;}var $3=new Sys.Net.WebRequest();$3.set_url($p0);if($1){$3.set_httpVerb($p1);}else{$3.set_httpVerb('POST');$3.get_headers()['X-HTTP-Method-Override']=$0;}$3.set_body($2);if($p1.toUpperCase()==='PUT'){$3.get_headers()['Content-Type']='application/x-www-form-urlencoded;';}$3.get_headers()['X-Requested-With']='XMLHttpRequest';var $4=null;if($p4.updateTargetId){$4=$get($p4.updateTargetId);}var $5=null;if($p4.loadingElementId){$5=$get($p4.loadingElementId);}var $6=new Sys.Mvc.AjaxContext($3,$4,$5,$p4.insertionMode);var $7=true;if($p4.onBegin){$7=$p4.onBegin($6)!==false;}if($5){Sys.UI.DomElement.setVisible($6.get_loadingElement(),true);}if($7){$3.add_completed(Function.createDelegate(null,function($p1_0){ -Sys.Mvc.MvcHelpers.$3($3,$p4,$6);}));$3.invoke();}} -Sys.Mvc.MvcHelpers.$3=function($p0,$p1,$p2){$p2.set_response($p0.get_executor());if($p1.onComplete&&$p1.onComplete($p2)===false){return;}var $0=$p2.get_response().get_statusCode();if(($0>=200&&$0<300)||$0===304||$0===1223){if($0!==204&&$0!==304&&$0!==1223){var $1=$p2.get_response().getResponseHeader('Content-Type');if(($1)&&($1.indexOf('application/x-javascript')!==-1)){eval($p2.get_data());}else{Sys.Mvc.MvcHelpers.updateDomElement($p2.get_updateTarget(),$p2.get_insertionMode(),$p2.get_data());}}if($p1.onSuccess){$p1.onSuccess($p2);}}else{if($p1.onFailure){$p1.onFailure($p2);}}if($p2.get_loadingElement()){Sys.UI.DomElement.setVisible($p2.get_loadingElement(),false);}} -Sys.Mvc.MvcHelpers.updateDomElement=function(target,insertionMode,content){if(target){switch(insertionMode){case 0:target.innerHTML=content;break;case 1:if(content&&content.length>0){target.innerHTML=content+target.innerHTML.trimStart();}break;case 2:if(content&&content.length>0){target.innerHTML=target.innerHTML.trimEnd()+content;}break;}}} -Sys.Mvc.AsyncForm=function(){} -Sys.Mvc.AsyncForm.handleClick=function(form,evt){var $0=Sys.Mvc.MvcHelpers.$0(evt.target,evt.offsetX,evt.offsetY);form._additionalInput = $0;} -Sys.Mvc.AsyncForm.handleSubmit=function(form,evt,ajaxOptions){evt.preventDefault();var $0=form.validationCallbacks;if($0){for(var $2=0;$2<$0.length;$2++){var $3=$0[$2];if(!$3()){return;}}}var $1=Sys.Mvc.MvcHelpers.$1(form);Sys.Mvc.MvcHelpers.$2(form.action,form.method||'post',$1,form,ajaxOptions);} -Sys.Mvc.AjaxContext.registerClass('Sys.Mvc.AjaxContext');Sys.Mvc.AsyncHyperlink.registerClass('Sys.Mvc.AsyncHyperlink');Sys.Mvc.MvcHelpers.registerClass('Sys.Mvc.MvcHelpers');Sys.Mvc.AsyncForm.registerClass('Sys.Mvc.AsyncForm'); -// ---- Do not remove this footer ---- -// Generated using Script# v0.5.0.0 (http://projects.nikhilk.net) -// ----------------------------------- diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftMvcValidation.debug.js b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftMvcValidation.debug.js deleted file mode 100644 index 872f80b..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftMvcValidation.debug.js +++ /dev/null @@ -1,881 +0,0 @@ -//!---------------------------------------------------------- -//! Copyright (C) Microsoft Corporation. All rights reserved. -//!---------------------------------------------------------- -//! MicrosoftMvcValidation.js - - -Type.registerNamespace('Sys.Mvc'); - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.Validation - -Sys.Mvc.$create_Validation = function Sys_Mvc_Validation() { return {}; } - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.JsonValidationField - -Sys.Mvc.$create_JsonValidationField = function Sys_Mvc_JsonValidationField() { return {}; } - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.JsonValidationOptions - -Sys.Mvc.$create_JsonValidationOptions = function Sys_Mvc_JsonValidationOptions() { return {}; } - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.JsonValidationRule - -Sys.Mvc.$create_JsonValidationRule = function Sys_Mvc_JsonValidationRule() { return {}; } - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.ValidationContext - -Sys.Mvc.$create_ValidationContext = function Sys_Mvc_ValidationContext() { return {}; } - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.NumberValidator - -Sys.Mvc.NumberValidator = function Sys_Mvc_NumberValidator() { -} -Sys.Mvc.NumberValidator.create = function Sys_Mvc_NumberValidator$create(rule) { - /// - /// - /// - return Function.createDelegate(new Sys.Mvc.NumberValidator(), new Sys.Mvc.NumberValidator().validate); -} -Sys.Mvc.NumberValidator.prototype = { - - validate: function Sys_Mvc_NumberValidator$validate(value, context) { - /// - /// - /// - /// - /// - if (Sys.Mvc._validationUtil.stringIsNullOrEmpty(value)) { - return true; - } - var n = Number.parseLocale(value); - return (!isNaN(n)); - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.FormContext - -Sys.Mvc.FormContext = function Sys_Mvc_FormContext(formElement, validationSummaryElement) { - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - this._errors = []; - this.fields = new Array(0); - this._formElement = formElement; - this._validationSummaryElement = validationSummaryElement; - formElement[Sys.Mvc.FormContext._formValidationTag] = this; - if (validationSummaryElement) { - var ulElements = validationSummaryElement.getElementsByTagName('ul'); - if (ulElements.length > 0) { - this._validationSummaryULElement = ulElements[0]; - } - } - this._onClickHandler = Function.createDelegate(this, this._form_OnClick); - this._onSubmitHandler = Function.createDelegate(this, this._form_OnSubmit); -} -Sys.Mvc.FormContext._Application_Load = function Sys_Mvc_FormContext$_Application_Load() { - var allFormOptions = window.mvcClientValidationMetadata; - if (allFormOptions) { - while (allFormOptions.length > 0) { - var thisFormOptions = allFormOptions.pop(); - Sys.Mvc.FormContext._parseJsonOptions(thisFormOptions); - } - } -} -Sys.Mvc.FormContext._getFormElementsWithName = function Sys_Mvc_FormContext$_getFormElementsWithName(formElement, name) { - /// - /// - /// - /// - /// - var allElementsWithNameInForm = []; - var allElementsWithName = document.getElementsByName(name); - for (var i = 0; i < allElementsWithName.length; i++) { - var thisElement = allElementsWithName[i]; - if (Sys.Mvc.FormContext._isElementInHierarchy(formElement, thisElement)) { - Array.add(allElementsWithNameInForm, thisElement); - } - } - return allElementsWithNameInForm; -} -Sys.Mvc.FormContext.getValidationForForm = function Sys_Mvc_FormContext$getValidationForForm(formElement) { - /// - /// - /// - return formElement[Sys.Mvc.FormContext._formValidationTag]; -} -Sys.Mvc.FormContext._isElementInHierarchy = function Sys_Mvc_FormContext$_isElementInHierarchy(parent, child) { - /// - /// - /// - /// - /// - while (child) { - if (parent === child) { - return true; - } - child = child.parentNode; - } - return false; -} -Sys.Mvc.FormContext._parseJsonOptions = function Sys_Mvc_FormContext$_parseJsonOptions(options) { - /// - /// - /// - var formElement = $get(options.FormId); - var validationSummaryElement = (!Sys.Mvc._validationUtil.stringIsNullOrEmpty(options.ValidationSummaryId)) ? $get(options.ValidationSummaryId) : null; - var formContext = new Sys.Mvc.FormContext(formElement, validationSummaryElement); - formContext.enableDynamicValidation(); - formContext.replaceValidationSummary = options.ReplaceValidationSummary; - for (var i = 0; i < options.Fields.length; i++) { - var field = options.Fields[i]; - var fieldElements = Sys.Mvc.FormContext._getFormElementsWithName(formElement, field.FieldName); - var validationMessageElement = (!Sys.Mvc._validationUtil.stringIsNullOrEmpty(field.ValidationMessageId)) ? $get(field.ValidationMessageId) : null; - var fieldContext = new Sys.Mvc.FieldContext(formContext); - Array.addRange(fieldContext.elements, fieldElements); - fieldContext.validationMessageElement = validationMessageElement; - fieldContext.replaceValidationMessageContents = field.ReplaceValidationMessageContents; - for (var j = 0; j < field.ValidationRules.length; j++) { - var rule = field.ValidationRules[j]; - var validator = Sys.Mvc.ValidatorRegistry.getValidator(rule); - if (validator) { - var validation = Sys.Mvc.$create_Validation(); - validation.fieldErrorMessage = rule.ErrorMessage; - validation.validator = validator; - Array.add(fieldContext.validations, validation); - } - } - fieldContext.enableDynamicValidation(); - Array.add(formContext.fields, fieldContext); - } - var registeredValidatorCallbacks = formElement.validationCallbacks; - if (!registeredValidatorCallbacks) { - registeredValidatorCallbacks = []; - formElement.validationCallbacks = registeredValidatorCallbacks; - } - registeredValidatorCallbacks.push(Function.createDelegate(null, function() { - return Sys.Mvc._validationUtil.arrayIsNullOrEmpty(formContext.validate('submit')); - })); - return formContext; -} -Sys.Mvc.FormContext.prototype = { - _onClickHandler: null, - _onSubmitHandler: null, - _submitButtonClicked: null, - _validationSummaryElement: null, - _validationSummaryULElement: null, - _formElement: null, - replaceValidationSummary: false, - - addError: function Sys_Mvc_FormContext$addError(message) { - /// - /// - this.addErrors([ message ]); - }, - - addErrors: function Sys_Mvc_FormContext$addErrors(messages) { - /// - /// - if (!Sys.Mvc._validationUtil.arrayIsNullOrEmpty(messages)) { - Array.addRange(this._errors, messages); - this._onErrorCountChanged(); - } - }, - - clearErrors: function Sys_Mvc_FormContext$clearErrors() { - Array.clear(this._errors); - this._onErrorCountChanged(); - }, - - _displayError: function Sys_Mvc_FormContext$_displayError() { - if (this._validationSummaryElement) { - if (this._validationSummaryULElement) { - Sys.Mvc._validationUtil.removeAllChildren(this._validationSummaryULElement); - for (var i = 0; i < this._errors.length; i++) { - var liElement = document.createElement('li'); - Sys.Mvc._validationUtil.setInnerText(liElement, this._errors[i]); - this._validationSummaryULElement.appendChild(liElement); - } - } - Sys.UI.DomElement.removeCssClass(this._validationSummaryElement, Sys.Mvc.FormContext._validationSummaryValidCss); - Sys.UI.DomElement.addCssClass(this._validationSummaryElement, Sys.Mvc.FormContext._validationSummaryErrorCss); - } - }, - - _displaySuccess: function Sys_Mvc_FormContext$_displaySuccess() { - var validationSummaryElement = this._validationSummaryElement; - if (validationSummaryElement) { - var validationSummaryULElement = this._validationSummaryULElement; - if (validationSummaryULElement) { - validationSummaryULElement.innerHTML = ''; - } - Sys.UI.DomElement.removeCssClass(validationSummaryElement, Sys.Mvc.FormContext._validationSummaryErrorCss); - Sys.UI.DomElement.addCssClass(validationSummaryElement, Sys.Mvc.FormContext._validationSummaryValidCss); - } - }, - - enableDynamicValidation: function Sys_Mvc_FormContext$enableDynamicValidation() { - Sys.UI.DomEvent.addHandler(this._formElement, 'click', this._onClickHandler); - Sys.UI.DomEvent.addHandler(this._formElement, 'submit', this._onSubmitHandler); - }, - - _findSubmitButton: function Sys_Mvc_FormContext$_findSubmitButton(element) { - /// - /// - /// - if (element.disabled) { - return null; - } - var tagName = element.tagName.toUpperCase(); - var inputElement = element; - if (tagName === 'INPUT') { - var type = inputElement.type; - if (type === 'submit' || type === 'image') { - return inputElement; - } - } - else if ((tagName === 'BUTTON') && (inputElement.type === 'submit')) { - return inputElement; - } - return null; - }, - - _form_OnClick: function Sys_Mvc_FormContext$_form_OnClick(e) { - /// - /// - this._submitButtonClicked = this._findSubmitButton(e.target); - }, - - _form_OnSubmit: function Sys_Mvc_FormContext$_form_OnSubmit(e) { - /// - /// - var form = e.target; - var submitButton = this._submitButtonClicked; - if (submitButton && submitButton.disableValidation) { - return; - } - var errorMessages = this.validate('submit'); - if (!Sys.Mvc._validationUtil.arrayIsNullOrEmpty(errorMessages)) { - e.preventDefault(); - } - }, - - _onErrorCountChanged: function Sys_Mvc_FormContext$_onErrorCountChanged() { - if (!this._errors.length) { - this._displaySuccess(); - } - else { - this._displayError(); - } - }, - - validate: function Sys_Mvc_FormContext$validate(eventName) { - /// - /// - /// - var fields = this.fields; - var errors = []; - for (var i = 0; i < fields.length; i++) { - var field = fields[i]; - var thisErrors = field.validate(eventName); - if (thisErrors) { - Array.addRange(errors, thisErrors); - } - } - if (this.replaceValidationSummary) { - this.clearErrors(); - this.addErrors(errors); - } - return errors; - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.FieldContext - -Sys.Mvc.FieldContext = function Sys_Mvc_FieldContext(formContext) { - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - this._errors = []; - this.elements = new Array(0); - this.validations = new Array(0); - this.formContext = formContext; - this._onBlurHandler = Function.createDelegate(this, this._element_OnBlur); - this._onChangeHandler = Function.createDelegate(this, this._element_OnChange); - this._onInputHandler = Function.createDelegate(this, this._element_OnInput); - this._onPropertyChangeHandler = Function.createDelegate(this, this._element_OnPropertyChange); -} -Sys.Mvc.FieldContext.prototype = { - _onBlurHandler: null, - _onChangeHandler: null, - _onInputHandler: null, - _onPropertyChangeHandler: null, - defaultErrorMessage: null, - formContext: null, - replaceValidationMessageContents: false, - validationMessageElement: null, - - addError: function Sys_Mvc_FieldContext$addError(message) { - /// - /// - this.addErrors([ message ]); - }, - - addErrors: function Sys_Mvc_FieldContext$addErrors(messages) { - /// - /// - if (!Sys.Mvc._validationUtil.arrayIsNullOrEmpty(messages)) { - Array.addRange(this._errors, messages); - this._onErrorCountChanged(); - } - }, - - clearErrors: function Sys_Mvc_FieldContext$clearErrors() { - Array.clear(this._errors); - this._onErrorCountChanged(); - }, - - _displayError: function Sys_Mvc_FieldContext$_displayError() { - var validationMessageElement = this.validationMessageElement; - if (validationMessageElement) { - if (this.replaceValidationMessageContents) { - Sys.Mvc._validationUtil.setInnerText(validationMessageElement, this._errors[0]); - } - Sys.UI.DomElement.removeCssClass(validationMessageElement, Sys.Mvc.FieldContext._validationMessageValidCss); - Sys.UI.DomElement.addCssClass(validationMessageElement, Sys.Mvc.FieldContext._validationMessageErrorCss); - } - var elements = this.elements; - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - Sys.UI.DomElement.removeCssClass(element, Sys.Mvc.FieldContext._inputElementValidCss); - Sys.UI.DomElement.addCssClass(element, Sys.Mvc.FieldContext._inputElementErrorCss); - } - }, - - _displaySuccess: function Sys_Mvc_FieldContext$_displaySuccess() { - var validationMessageElement = this.validationMessageElement; - if (validationMessageElement) { - if (this.replaceValidationMessageContents) { - Sys.Mvc._validationUtil.setInnerText(validationMessageElement, ''); - } - Sys.UI.DomElement.removeCssClass(validationMessageElement, Sys.Mvc.FieldContext._validationMessageErrorCss); - Sys.UI.DomElement.addCssClass(validationMessageElement, Sys.Mvc.FieldContext._validationMessageValidCss); - } - var elements = this.elements; - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - Sys.UI.DomElement.removeCssClass(element, Sys.Mvc.FieldContext._inputElementErrorCss); - Sys.UI.DomElement.addCssClass(element, Sys.Mvc.FieldContext._inputElementValidCss); - } - }, - - _element_OnBlur: function Sys_Mvc_FieldContext$_element_OnBlur(e) { - /// - /// - if (e.target[Sys.Mvc.FieldContext._hasTextChangedTag] || e.target[Sys.Mvc.FieldContext._hasValidationFiredTag]) { - this.validate('blur'); - } - }, - - _element_OnChange: function Sys_Mvc_FieldContext$_element_OnChange(e) { - /// - /// - e.target[Sys.Mvc.FieldContext._hasTextChangedTag] = true; - }, - - _element_OnInput: function Sys_Mvc_FieldContext$_element_OnInput(e) { - /// - /// - e.target[Sys.Mvc.FieldContext._hasTextChangedTag] = true; - if (e.target[Sys.Mvc.FieldContext._hasValidationFiredTag]) { - this.validate('input'); - } - }, - - _element_OnPropertyChange: function Sys_Mvc_FieldContext$_element_OnPropertyChange(e) { - /// - /// - if (e.rawEvent.propertyName === 'value') { - e.target[Sys.Mvc.FieldContext._hasTextChangedTag] = true; - if (e.target[Sys.Mvc.FieldContext._hasValidationFiredTag]) { - this.validate('input'); - } - } - }, - - enableDynamicValidation: function Sys_Mvc_FieldContext$enableDynamicValidation() { - var elements = this.elements; - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - if (Sys.Mvc._validationUtil.elementSupportsEvent(element, 'onpropertychange')) { - var compatMode = document.documentMode; - if (compatMode && compatMode >= 8) { - Sys.UI.DomEvent.addHandler(element, 'propertychange', this._onPropertyChangeHandler); - } - } - else { - Sys.UI.DomEvent.addHandler(element, 'input', this._onInputHandler); - } - Sys.UI.DomEvent.addHandler(element, 'change', this._onChangeHandler); - Sys.UI.DomEvent.addHandler(element, 'blur', this._onBlurHandler); - } - }, - - _getErrorString: function Sys_Mvc_FieldContext$_getErrorString(validatorReturnValue, fieldErrorMessage) { - /// - /// - /// - /// - /// - var fallbackErrorMessage = fieldErrorMessage || this.defaultErrorMessage; - if (Boolean.isInstanceOfType(validatorReturnValue)) { - return (validatorReturnValue) ? null : fallbackErrorMessage; - } - if (String.isInstanceOfType(validatorReturnValue)) { - return ((validatorReturnValue).length) ? validatorReturnValue : fallbackErrorMessage; - } - return null; - }, - - _getStringValue: function Sys_Mvc_FieldContext$_getStringValue() { - /// - var elements = this.elements; - return (elements.length > 0) ? elements[0].value : null; - }, - - _markValidationFired: function Sys_Mvc_FieldContext$_markValidationFired() { - var elements = this.elements; - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - element[Sys.Mvc.FieldContext._hasValidationFiredTag] = true; - } - }, - - _onErrorCountChanged: function Sys_Mvc_FieldContext$_onErrorCountChanged() { - if (!this._errors.length) { - this._displaySuccess(); - } - else { - this._displayError(); - } - }, - - validate: function Sys_Mvc_FieldContext$validate(eventName) { - /// - /// - /// - var validations = this.validations; - var errors = []; - var value = this._getStringValue(); - for (var i = 0; i < validations.length; i++) { - var validation = validations[i]; - var context = Sys.Mvc.$create_ValidationContext(); - context.eventName = eventName; - context.fieldContext = this; - context.validation = validation; - var retVal = validation.validator(value, context); - var errorMessage = this._getErrorString(retVal, validation.fieldErrorMessage); - if (!Sys.Mvc._validationUtil.stringIsNullOrEmpty(errorMessage)) { - Array.add(errors, errorMessage); - } - } - this._markValidationFired(); - this.clearErrors(); - this.addErrors(errors); - return errors; - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.RangeValidator - -Sys.Mvc.RangeValidator = function Sys_Mvc_RangeValidator(minimum, maximum) { - /// - /// - /// - /// - /// - /// - /// - /// - this._minimum = minimum; - this._maximum = maximum; -} -Sys.Mvc.RangeValidator.create = function Sys_Mvc_RangeValidator$create(rule) { - /// - /// - /// - var min = rule.ValidationParameters['minimum']; - var max = rule.ValidationParameters['maximum']; - return Function.createDelegate(new Sys.Mvc.RangeValidator(min, max), new Sys.Mvc.RangeValidator(min, max).validate); -} -Sys.Mvc.RangeValidator.prototype = { - _minimum: null, - _maximum: null, - - validate: function Sys_Mvc_RangeValidator$validate(value, context) { - /// - /// - /// - /// - /// - if (Sys.Mvc._validationUtil.stringIsNullOrEmpty(value)) { - return true; - } - var n = Number.parseLocale(value); - return (!isNaN(n) && this._minimum <= n && n <= this._maximum); - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.RegularExpressionValidator - -Sys.Mvc.RegularExpressionValidator = function Sys_Mvc_RegularExpressionValidator(pattern) { - /// - /// - /// - /// - this._pattern = pattern; -} -Sys.Mvc.RegularExpressionValidator.create = function Sys_Mvc_RegularExpressionValidator$create(rule) { - /// - /// - /// - var pattern = rule.ValidationParameters['pattern']; - return Function.createDelegate(new Sys.Mvc.RegularExpressionValidator(pattern), new Sys.Mvc.RegularExpressionValidator(pattern).validate); -} -Sys.Mvc.RegularExpressionValidator.prototype = { - _pattern: null, - - validate: function Sys_Mvc_RegularExpressionValidator$validate(value, context) { - /// - /// - /// - /// - /// - if (Sys.Mvc._validationUtil.stringIsNullOrEmpty(value)) { - return true; - } - var regExp = new RegExp(this._pattern); - var matches = regExp.exec(value); - return (!Sys.Mvc._validationUtil.arrayIsNullOrEmpty(matches) && matches[0].length === value.length); - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.RequiredValidator - -Sys.Mvc.RequiredValidator = function Sys_Mvc_RequiredValidator() { -} -Sys.Mvc.RequiredValidator.create = function Sys_Mvc_RequiredValidator$create(rule) { - /// - /// - /// - return Function.createDelegate(new Sys.Mvc.RequiredValidator(), new Sys.Mvc.RequiredValidator().validate); -} -Sys.Mvc.RequiredValidator._isRadioInputElement = function Sys_Mvc_RequiredValidator$_isRadioInputElement(element) { - /// - /// - /// - if (element.tagName.toUpperCase() === 'INPUT') { - var inputType = (element.type).toUpperCase(); - if (inputType === 'RADIO') { - return true; - } - } - return false; -} -Sys.Mvc.RequiredValidator._isSelectInputElement = function Sys_Mvc_RequiredValidator$_isSelectInputElement(element) { - /// - /// - /// - if (element.tagName.toUpperCase() === 'SELECT') { - return true; - } - return false; -} -Sys.Mvc.RequiredValidator._isTextualInputElement = function Sys_Mvc_RequiredValidator$_isTextualInputElement(element) { - /// - /// - /// - if (element.tagName.toUpperCase() === 'INPUT') { - var inputType = (element.type).toUpperCase(); - switch (inputType) { - case 'TEXT': - case 'PASSWORD': - case 'FILE': - return true; - } - } - if (element.tagName.toUpperCase() === 'TEXTAREA') { - return true; - } - return false; -} -Sys.Mvc.RequiredValidator._validateRadioInput = function Sys_Mvc_RequiredValidator$_validateRadioInput(elements) { - /// - /// - /// - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - if (element.checked) { - return true; - } - } - return false; -} -Sys.Mvc.RequiredValidator._validateSelectInput = function Sys_Mvc_RequiredValidator$_validateSelectInput(optionElements) { - /// - /// - /// - for (var i = 0; i < optionElements.length; i++) { - var element = optionElements[i]; - if (element.selected) { - if (!Sys.Mvc._validationUtil.stringIsNullOrEmpty(element.value)) { - return true; - } - } - } - return false; -} -Sys.Mvc.RequiredValidator._validateTextualInput = function Sys_Mvc_RequiredValidator$_validateTextualInput(element) { - /// - /// - /// - return (!Sys.Mvc._validationUtil.stringIsNullOrEmpty(element.value)); -} -Sys.Mvc.RequiredValidator.prototype = { - - validate: function Sys_Mvc_RequiredValidator$validate(value, context) { - /// - /// - /// - /// - /// - var elements = context.fieldContext.elements; - if (!elements.length) { - return true; - } - var sampleElement = elements[0]; - if (Sys.Mvc.RequiredValidator._isTextualInputElement(sampleElement)) { - return Sys.Mvc.RequiredValidator._validateTextualInput(sampleElement); - } - if (Sys.Mvc.RequiredValidator._isRadioInputElement(sampleElement)) { - return Sys.Mvc.RequiredValidator._validateRadioInput(elements); - } - if (Sys.Mvc.RequiredValidator._isSelectInputElement(sampleElement)) { - return Sys.Mvc.RequiredValidator._validateSelectInput((sampleElement).options); - } - return true; - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.StringLengthValidator - -Sys.Mvc.StringLengthValidator = function Sys_Mvc_StringLengthValidator(minLength, maxLength) { - /// - /// - /// - /// - /// - /// - /// - /// - this._minLength = minLength; - this._maxLength = maxLength; -} -Sys.Mvc.StringLengthValidator.create = function Sys_Mvc_StringLengthValidator$create(rule) { - /// - /// - /// - var minLength = rule.ValidationParameters['minimumLength']; - var maxLength = rule.ValidationParameters['maximumLength']; - return Function.createDelegate(new Sys.Mvc.StringLengthValidator(minLength, maxLength), new Sys.Mvc.StringLengthValidator(minLength, maxLength).validate); -} -Sys.Mvc.StringLengthValidator.prototype = { - _maxLength: 0, - _minLength: 0, - - validate: function Sys_Mvc_StringLengthValidator$validate(value, context) { - /// - /// - /// - /// - /// - if (Sys.Mvc._validationUtil.stringIsNullOrEmpty(value)) { - return true; - } - return (this._minLength <= value.length && value.length <= this._maxLength); - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc._validationUtil - -Sys.Mvc._validationUtil = function Sys_Mvc__validationUtil() { -} -Sys.Mvc._validationUtil.arrayIsNullOrEmpty = function Sys_Mvc__validationUtil$arrayIsNullOrEmpty(array) { - /// - /// - /// - return (!array || !array.length); -} -Sys.Mvc._validationUtil.stringIsNullOrEmpty = function Sys_Mvc__validationUtil$stringIsNullOrEmpty(value) { - /// - /// - /// - return (!value || !value.length); -} -Sys.Mvc._validationUtil.elementSupportsEvent = function Sys_Mvc__validationUtil$elementSupportsEvent(element, eventAttributeName) { - /// - /// - /// - /// - /// - return (eventAttributeName in element); -} -Sys.Mvc._validationUtil.removeAllChildren = function Sys_Mvc__validationUtil$removeAllChildren(element) { - /// - /// - while (element.firstChild) { - element.removeChild(element.firstChild); - } -} -Sys.Mvc._validationUtil.setInnerText = function Sys_Mvc__validationUtil$setInnerText(element, innerText) { - /// - /// - /// - /// - var textNode = document.createTextNode(innerText); - Sys.Mvc._validationUtil.removeAllChildren(element); - element.appendChild(textNode); -} - - -//////////////////////////////////////////////////////////////////////////////// -// Sys.Mvc.ValidatorRegistry - -Sys.Mvc.ValidatorRegistry = function Sys_Mvc_ValidatorRegistry() { - /// - /// -} -Sys.Mvc.ValidatorRegistry.getValidator = function Sys_Mvc_ValidatorRegistry$getValidator(rule) { - /// - /// - /// - var creator = Sys.Mvc.ValidatorRegistry.validators[rule.ValidationType]; - return (creator) ? creator(rule) : null; -} -Sys.Mvc.ValidatorRegistry._getDefaultValidators = function Sys_Mvc_ValidatorRegistry$_getDefaultValidators() { - /// - return { required: Function.createDelegate(null, Sys.Mvc.RequiredValidator.create), stringLength: Function.createDelegate(null, Sys.Mvc.StringLengthValidator.create), regularExpression: Function.createDelegate(null, Sys.Mvc.RegularExpressionValidator.create), range: Function.createDelegate(null, Sys.Mvc.RangeValidator.create), number: Function.createDelegate(null, Sys.Mvc.NumberValidator.create) }; -} - - -Sys.Mvc.NumberValidator.registerClass('Sys.Mvc.NumberValidator'); -Sys.Mvc.FormContext.registerClass('Sys.Mvc.FormContext'); -Sys.Mvc.FieldContext.registerClass('Sys.Mvc.FieldContext'); -Sys.Mvc.RangeValidator.registerClass('Sys.Mvc.RangeValidator'); -Sys.Mvc.RegularExpressionValidator.registerClass('Sys.Mvc.RegularExpressionValidator'); -Sys.Mvc.RequiredValidator.registerClass('Sys.Mvc.RequiredValidator'); -Sys.Mvc.StringLengthValidator.registerClass('Sys.Mvc.StringLengthValidator'); -Sys.Mvc._validationUtil.registerClass('Sys.Mvc._validationUtil'); -Sys.Mvc.ValidatorRegistry.registerClass('Sys.Mvc.ValidatorRegistry'); -Sys.Mvc.FormContext._validationSummaryErrorCss = 'validation-summary-errors'; -Sys.Mvc.FormContext._validationSummaryValidCss = 'validation-summary-valid'; -Sys.Mvc.FormContext._formValidationTag = '__MVC_FormValidation'; -Sys.Mvc.FieldContext._hasTextChangedTag = '__MVC_HasTextChanged'; -Sys.Mvc.FieldContext._hasValidationFiredTag = '__MVC_HasValidationFired'; -Sys.Mvc.FieldContext._inputElementErrorCss = 'input-validation-error'; -Sys.Mvc.FieldContext._inputElementValidCss = 'input-validation-valid'; -Sys.Mvc.FieldContext._validationMessageErrorCss = 'field-validation-error'; -Sys.Mvc.FieldContext._validationMessageValidCss = 'field-validation-valid'; -Sys.Mvc.ValidatorRegistry.validators = Sys.Mvc.ValidatorRegistry._getDefaultValidators(); - -// ---- Do not remove this footer ---- -// Generated using Script# v0.5.0.0 (http://projects.nikhilk.net) -// ----------------------------------- - -// register validation -Sys.Application.add_load(function() { - Sys.Application.remove_load(arguments.callee); - Sys.Mvc.FormContext._Application_Load(); -}); diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftMvcValidation.js b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftMvcValidation.js deleted file mode 100644 index 9040973..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/MicrosoftMvcValidation.js +++ /dev/null @@ -1,55 +0,0 @@ -//---------------------------------------------------------- -// Copyright (C) Microsoft Corporation. All rights reserved. -//---------------------------------------------------------- -// MicrosoftMvcValidation.js - -Type.registerNamespace('Sys.Mvc');Sys.Mvc.$create_Validation=function(){return {};} -Sys.Mvc.$create_JsonValidationField=function(){return {};} -Sys.Mvc.$create_JsonValidationOptions=function(){return {};} -Sys.Mvc.$create_JsonValidationRule=function(){return {};} -Sys.Mvc.$create_ValidationContext=function(){return {};} -Sys.Mvc.NumberValidator=function(){} -Sys.Mvc.NumberValidator.create=function(rule){return Function.createDelegate(new Sys.Mvc.NumberValidator(),new Sys.Mvc.NumberValidator().validate);} -Sys.Mvc.NumberValidator.prototype={validate:function(value,context){if(Sys.Mvc._ValidationUtil.$1(value)){return true;}var $0=Number.parseLocale(value);return (!isNaN($0));}} -Sys.Mvc.FormContext=function(formElement,validationSummaryElement){this.$5=[];this.fields=new Array(0);this.$9=formElement;this.$7=validationSummaryElement;formElement['__MVC_FormValidation'] = this;if(validationSummaryElement){var $0=validationSummaryElement.getElementsByTagName('ul');if($0.length>0){this.$8=$0[0];}}this.$3=Function.createDelegate(this,this.$D);this.$4=Function.createDelegate(this,this.$E);} -Sys.Mvc.FormContext._Application_Load=function(){var $0=window.mvcClientValidationMetadata;if($0){while($0.length>0){var $1=$0.pop();Sys.Mvc.FormContext.$12($1);}}} -Sys.Mvc.FormContext.$F=function($p0,$p1){var $0=[];var $1=document.getElementsByName($p1);for(var $2=0;$2<$1.length;$2++){var $3=$1[$2];if(Sys.Mvc.FormContext.$10($p0,$3)){Array.add($0,$3);}}return $0;} -Sys.Mvc.FormContext.getValidationForForm=function(formElement){return formElement['__MVC_FormValidation'];} -Sys.Mvc.FormContext.$10=function($p0,$p1){while($p1){if($p0===$p1){return true;}$p1=$p1.parentNode;}return false;} -Sys.Mvc.FormContext.$12=function($p0){var $0=$get($p0.FormId);var $1=(!Sys.Mvc._ValidationUtil.$1($p0.ValidationSummaryId))?$get($p0.ValidationSummaryId):null;var $2=new Sys.Mvc.FormContext($0,$1);$2.enableDynamicValidation();$2.replaceValidationSummary=$p0.ReplaceValidationSummary;for(var $4=0;$4<$p0.Fields.length;$4++){var $5=$p0.Fields[$4];var $6=Sys.Mvc.FormContext.$F($0,$5.FieldName);var $7=(!Sys.Mvc._ValidationUtil.$1($5.ValidationMessageId))?$get($5.ValidationMessageId):null;var $8=new Sys.Mvc.FieldContext($2);Array.addRange($8.elements,$6);$8.validationMessageElement=$7;$8.replaceValidationMessageContents=$5.ReplaceValidationMessageContents;for(var $9=0;$9<$5.ValidationRules.length;$9++){var $A=$5.ValidationRules[$9];var $B=Sys.Mvc.ValidatorRegistry.getValidator($A);if($B){var $C=Sys.Mvc.$create_Validation();$C.fieldErrorMessage=$A.ErrorMessage;$C.validator=$B;Array.add($8.validations,$C);}}$8.enableDynamicValidation();Array.add($2.fields,$8);}var $3=$0.validationCallbacks;if(!$3){$3=[];$0.validationCallbacks = $3;}$3.push(Function.createDelegate(null,function(){ -return Sys.Mvc._ValidationUtil.$0($2.validate('submit'));}));return $2;} -Sys.Mvc.FormContext.prototype={$3:null,$4:null,$6:null,$7:null,$8:null,$9:null,replaceValidationSummary:false,addError:function(message){this.addErrors([message]);},addErrors:function(messages){if(!Sys.Mvc._ValidationUtil.$0(messages)){Array.addRange(this.$5,messages);this.$11();}},clearErrors:function(){Array.clear(this.$5);this.$11();},$A:function(){if(this.$7){if(this.$8){Sys.Mvc._ValidationUtil.$3(this.$8);for(var $0=0;$0=8){Sys.UI.DomEvent.addHandler($2,'propertychange',this.$9);}}else{Sys.UI.DomEvent.addHandler($2,'input',this.$8);}Sys.UI.DomEvent.addHandler($2,'change',this.$7);Sys.UI.DomEvent.addHandler($2,'blur',this.$6);}},$11:function($p0,$p1){var $0=$p1||this.defaultErrorMessage;if(Boolean.isInstanceOfType($p0)){return ($p0)?null:$0;}if(String.isInstanceOfType($p0)){return (($p0).length)?$p0:$0;}return null;},$12:function(){var $0=this.elements;return ($0.length>0)?$0[0].value:null;},$13:function(){var $0=this.elements;for(var $1=0;$1<$0.length;$1++){var $2=$0[$1];$2['__MVC_HasValidationFired'] = true;}},$14:function(){if(!this.$A.length){this.$C();}else{this.$B();}},validate:function(eventName){var $0=this.validations;var $1=[];var $2=this.$12();for(var $3=0;$3<$0.length;$3++){var $4=$0[$3];var $5=Sys.Mvc.$create_ValidationContext();$5.eventName=eventName;$5.fieldContext=this;$5.validation=$4;var $6=$4.validator($2,$5);var $7=this.$11($6,$4.fieldErrorMessage);if(!Sys.Mvc._ValidationUtil.$1($7)){Array.add($1,$7);}}this.$13();this.clearErrors();this.addErrors($1);return $1;}} -Sys.Mvc.RangeValidator=function(minimum,maximum){this.$0=minimum;this.$1=maximum;} -Sys.Mvc.RangeValidator.create=function(rule){var $0=rule.ValidationParameters['minimum'];var $1=rule.ValidationParameters['maximum'];return Function.createDelegate(new Sys.Mvc.RangeValidator($0,$1),new Sys.Mvc.RangeValidator($0,$1).validate);} -Sys.Mvc.RangeValidator.prototype={$0:null,$1:null,validate:function(value,context){if(Sys.Mvc._ValidationUtil.$1(value)){return true;}var $0=Number.parseLocale(value);return (!isNaN($0)&&this.$0<=$0&&$0<=this.$1);}} -Sys.Mvc.RegularExpressionValidator=function(pattern){this.$0=pattern;} -Sys.Mvc.RegularExpressionValidator.create=function(rule){var $0=rule.ValidationParameters['pattern'];return Function.createDelegate(new Sys.Mvc.RegularExpressionValidator($0),new Sys.Mvc.RegularExpressionValidator($0).validate);} -Sys.Mvc.RegularExpressionValidator.prototype={$0:null,validate:function(value,context){if(Sys.Mvc._ValidationUtil.$1(value)){return true;}var $0=new RegExp(this.$0);var $1=$0.exec(value);return (!Sys.Mvc._ValidationUtil.$0($1)&&$1[0].length===value.length);}} -Sys.Mvc.RequiredValidator=function(){} -Sys.Mvc.RequiredValidator.create=function(rule){return Function.createDelegate(new Sys.Mvc.RequiredValidator(),new Sys.Mvc.RequiredValidator().validate);} -Sys.Mvc.RequiredValidator.$0=function($p0){if($p0.tagName.toUpperCase()==='INPUT'){var $0=($p0.type).toUpperCase();if($0==='RADIO'){return true;}}return false;} -Sys.Mvc.RequiredValidator.$1=function($p0){if($p0.tagName.toUpperCase()==='SELECT'){return true;}return false;} -Sys.Mvc.RequiredValidator.$2=function($p0){if($p0.tagName.toUpperCase()==='INPUT'){var $0=($p0.type).toUpperCase();switch($0){case 'TEXT':case 'PASSWORD':case 'FILE':return true;}}if($p0.tagName.toUpperCase()==='TEXTAREA'){return true;}return false;} -Sys.Mvc.RequiredValidator.$3=function($p0){for(var $0=0;$0<$p0.length;$0++){var $1=$p0[$0];if($1.checked){return true;}}return false;} -Sys.Mvc.RequiredValidator.$4=function($p0){for(var $0=0;$0<$p0.length;$0++){var $1=$p0[$0];if($1.selected){if(!Sys.Mvc._ValidationUtil.$1($1.value)){return true;}}}return false;} -Sys.Mvc.RequiredValidator.$5=function($p0){return (!Sys.Mvc._ValidationUtil.$1($p0.value));} -Sys.Mvc.RequiredValidator.prototype={validate:function(value,context){var $0=context.fieldContext.elements;if(!$0.length){return true;}var $1=$0[0];if(Sys.Mvc.RequiredValidator.$2($1)){return Sys.Mvc.RequiredValidator.$5($1);}if(Sys.Mvc.RequiredValidator.$0($1)){return Sys.Mvc.RequiredValidator.$3($0);}if(Sys.Mvc.RequiredValidator.$1($1)){return Sys.Mvc.RequiredValidator.$4(($1).options);}return true;}} -Sys.Mvc.StringLengthValidator=function(minLength,maxLength){this.$1=minLength;this.$0=maxLength;} -Sys.Mvc.StringLengthValidator.create=function(rule){var $0=rule.ValidationParameters['minimumLength'];var $1=rule.ValidationParameters['maximumLength'];return Function.createDelegate(new Sys.Mvc.StringLengthValidator($0,$1),new Sys.Mvc.StringLengthValidator($0,$1).validate);} -Sys.Mvc.StringLengthValidator.prototype={$0:0,$1:0,validate:function(value,context){if(Sys.Mvc._ValidationUtil.$1(value)){return true;}return (this.$1<=value.length&&value.length<=this.$0);}} -Sys.Mvc._ValidationUtil=function(){} -Sys.Mvc._ValidationUtil.$0=function($p0){return (!$p0||!$p0.length);} -Sys.Mvc._ValidationUtil.$1=function($p0){return (!$p0||!$p0.length);} -Sys.Mvc._ValidationUtil.$2=function($p0,$p1){return ($p1 in $p0);} -Sys.Mvc._ValidationUtil.$3=function($p0){while($p0.firstChild){$p0.removeChild($p0.firstChild);}} -Sys.Mvc._ValidationUtil.$4=function($p0,$p1){var $0=document.createTextNode($p1);Sys.Mvc._ValidationUtil.$3($p0);$p0.appendChild($0);} -Sys.Mvc.ValidatorRegistry=function(){} -Sys.Mvc.ValidatorRegistry.getValidator=function(rule){var $0=Sys.Mvc.ValidatorRegistry.validators[rule.ValidationType];return ($0)?$0(rule):null;} -Sys.Mvc.ValidatorRegistry.$0=function(){return {required:Function.createDelegate(null,Sys.Mvc.RequiredValidator.create),stringLength:Function.createDelegate(null,Sys.Mvc.StringLengthValidator.create),regularExpression:Function.createDelegate(null,Sys.Mvc.RegularExpressionValidator.create),range:Function.createDelegate(null,Sys.Mvc.RangeValidator.create),number:Function.createDelegate(null,Sys.Mvc.NumberValidator.create)};} -Sys.Mvc.NumberValidator.registerClass('Sys.Mvc.NumberValidator');Sys.Mvc.FormContext.registerClass('Sys.Mvc.FormContext');Sys.Mvc.FieldContext.registerClass('Sys.Mvc.FieldContext');Sys.Mvc.RangeValidator.registerClass('Sys.Mvc.RangeValidator');Sys.Mvc.RegularExpressionValidator.registerClass('Sys.Mvc.RegularExpressionValidator');Sys.Mvc.RequiredValidator.registerClass('Sys.Mvc.RequiredValidator');Sys.Mvc.StringLengthValidator.registerClass('Sys.Mvc.StringLengthValidator');Sys.Mvc._ValidationUtil.registerClass('Sys.Mvc._ValidationUtil');Sys.Mvc.ValidatorRegistry.registerClass('Sys.Mvc.ValidatorRegistry');Sys.Mvc.ValidatorRegistry.validators=Sys.Mvc.ValidatorRegistry.$0(); -// ---- Do not remove this footer ---- -// Generated using Script# v0.5.0.0 (http://projects.nikhilk.net) -// ----------------------------------- -Sys.Application.add_load(function(){Sys.Application.remove_load(arguments.callee);Sys.Mvc.FormContext._Application_Load();}); \ No newline at end of file diff --git a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/jquery-1.4.1-vsdoc.js b/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/jquery-1.4.1-vsdoc.js deleted file mode 100644 index a6d00ce..0000000 --- a/sample/NServiceBus/Sample.JesseHouse/Sample.JesseHouse/Scripts/jquery-1.4.1-vsdoc.js +++ /dev/null @@ -1,8061 +0,0 @@ -/* - * This file has been commented to support Visual Studio Intellisense. - * You should not use this file at runtime inside the browser--it is only - * intended to be used only for design-time IntelliSense. Please use the - * standard jQuery library for all production use. - * - * Comment version: 1.4.1a - */ - -/*! - * jQuery JavaScript Library v1.4.1 - * http://jquery.com/ - * - * Distributed in whole under the terms of the MIT - * - * Copyright 2010, John Resig - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * Copyright 2010, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * - * Date: Mon Jan 25 19:43:33 2010 -0500 - */ - -(function( window, undefined ) { - -// Define a local copy of jQuery -var jQuery = function( selector, context ) { - /// - /// 1: $(expression, context) - This function accepts a string containing a CSS selector which is then used to match a set of elements. - /// 2: $(html) - Create DOM elements on-the-fly from the provided String of raw HTML. - /// 3: $(elements) - Wrap jQuery functionality around a single or multiple DOM Element(s). - /// 4: $(callback) - A shorthand for $(document).ready(). - /// 5: $() - As of jQuery 1.4, if you pass no arguments in to the jQuery() method, an empty jQuery set will be returned. - /// - /// - /// 1: expression - An expression to search with. - /// 2: html - A string of HTML to create on the fly. - /// 3: elements - DOM element(s) to be encapsulated by a jQuery object. - /// 4: callback - The function to execute when the DOM is ready. - /// - /// - /// 1: context - A DOM Element, Document or jQuery to use as context. - /// - /// - - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context ); - }, - - // Map over jQuery in case of overwrite - _jQuery = window.jQuery, - - // Map over the $ in case of overwrite - _$ = window.$, - - // Use the correct document accordingly with window argument (sandbox) - document = window.document, - - // A central reference to the root jQuery(document) - rootjQuery, - - // A simple way to check for HTML strings or ID strings - // (both of which we optimize for) - quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/, - - // Is it a simple selector - isSimple = /^.[^:#\[\.,]*$/, - - // Check if a string has a non-whitespace character in it - rnotwhite = /\S/, - - // Used for trimming whitespace - rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, - - // Keep a UserAgent string for use with jQuery.browser - userAgent = navigator.userAgent, - - // For matching the engine and version of the browser - browserMatch, - - // Has the ready events already been bound? - readyBound = false, - - // The functions to execute on DOM ready - readyList = [], - - // The ready event handler - DOMContentLoaded, - - // Save a reference to some core methods - toString = Object.prototype.toString, - hasOwnProperty = Object.prototype.hasOwnProperty, - push = Array.prototype.push, - slice = Array.prototype.slice, - indexOf = Array.prototype.indexOf; - -jQuery.fn = jQuery.prototype = { - init: function( selector, context ) { - - var match, elem, ret, doc; - - // Handle $(""), $(null), or $(undefined) - if ( !selector ) { - return this; - } - - // Handle $(DOMElement) - if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - // Are we dealing with HTML string or an ID? - match = quickExpr.exec( selector ); - - // Verify a match, and that no context was specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - doc = (context ? context.ownerDocument || context : document); - - // If a single string is passed in and it's a single tag - // just do a createElement and skip the rest - ret = rsingleTag.exec( selector ); - - if ( ret ) { - if ( jQuery.isPlainObject( context ) ) { - selector = [ document.createElement( ret[1] ) ]; - jQuery.fn.attr.call( selector, context, true ); - - } else { - selector = [ doc.createElement( ret[1] ) ]; - } - - } else { - ret = buildFragment( [ match[1] ], [ doc ] ); - selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes; - } - - // HANDLE: $("#id") - } else { - elem = document.getElementById( match[2] ); - - if ( elem ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $("TAG") - } else if ( !context && /^\w+$/.test( selector ) ) { - this.selector = selector; - this.context = document; - selector = document.getElementsByTagName( selector ); - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return (context || rootjQuery).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return jQuery( context ).find( selector ); - } - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } - - if (selector.selector !== undefined) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.isArray( selector ) ? - this.setArray( selector ) : - jQuery.makeArray( selector, this ); - }, - - // Start with an empty selector - selector: "", - - // The current version of jQuery being used - jquery: "1.4.1", - - // The default length of a jQuery object is 0 - length: 0, - - // The number of elements contained in the matched element set - size: function() { - /// - /// The number of elements currently matched. - /// Part of Core - /// - /// - - return this.length; - }, - - toArray: function() { - /// - /// Retrieve all the DOM elements contained in the jQuery set, as an array. - /// - /// - return slice.call( this, 0 ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - /// - /// Access a single matched element. num is used to access the - /// Nth element matched. - /// Part of Core - /// - /// - /// - /// Access the element in the Nth position. - /// - - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems, name, selector ) { - /// - /// Set the jQuery object to an array of elements, while maintaining - /// the stack. - /// Part of Core - /// - /// - /// - /// An array of elements - /// - - // Build a new jQuery matched element set - var ret = jQuery( elems || null ); - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - ret.context = this.context; - - if ( name === "find" ) { - ret.selector = this.selector + (this.selector ? " " : "") + selector; - } else if ( name ) { - ret.selector = this.selector + "." + name + "(" + selector + ")"; - } - - // Return the newly-formed element set - return ret; - }, - - // Force the current matched set of elements to become - // the specified array of elements (destroying the stack in the process) - // You should use pushStack() in order to do this, but maintain the stack - setArray: function( elems ) { - /// - /// Set the jQuery object to an array of elements. This operation is - /// completely destructive - be sure to use .pushStack() if you wish to maintain - /// the jQuery stack. - /// Part of Core - /// - /// - /// - /// An array of elements - /// - - // Resetting the length to 0, then using the native Array push - // is a super-fast way to populate an object with array-like properties - this.length = 0; - push.apply( this, elems ); - - return this; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - /// - /// Execute a function within the context of every matched element. - /// This means that every time the passed-in function is executed - /// (which is once for every element matched) the 'this' keyword - /// points to the specific element. - /// Additionally, the function, when executed, is passed a single - /// argument representing the position of the element in the matched - /// set. - /// Part of Core - /// - /// - /// - /// A function to execute - /// - - return jQuery.each( this, callback, args ); - }, - - ready: function( fn ) { - /// - /// Binds a function to be executed whenever the DOM is ready to be traversed and manipulated. - /// - /// The function to be executed when the DOM is ready. - - // Attach the listeners - jQuery.bindReady(); - - // If the DOM is already ready - if ( jQuery.isReady ) { - // Execute the function immediately - fn.call( document, jQuery ); - - // Otherwise, remember the function for later - } else if ( readyList ) { - // Add the function to the wait list - readyList.push( fn ); - } - - return this; - }, - - eq: function( i ) { - /// - /// Reduce the set of matched elements to a single element. - /// The position of the element in the set of matched elements - /// starts at 0 and goes to length - 1. - /// Part of Core - /// - /// - /// - /// pos The index of the element that you wish to limit to. - /// - - return i === -1 ? - this.slice( i ) : - this.slice( i, +i + 1 ); - }, - - first: function() { - /// - /// Reduce the set of matched elements to the first in the set. - /// - /// - - return this.eq( 0 ); - }, - - last: function() { - /// - /// Reduce the set of matched elements to the final one in the set. - /// - /// - - return this.eq( -1 ); - }, - - slice: function() { - /// - /// Selects a subset of the matched elements. Behaves exactly like the built-in Array slice method. - /// - /// Where to start the subset (0-based). - /// Where to end the subset (not including the end element itself). - /// If omitted, ends at the end of the selection - /// The sliced elements - - return this.pushStack( slice.apply( this, arguments ), - "slice", slice.call(arguments).join(",") ); - }, - - map: function( callback ) { - /// - /// This member is internal. - /// - /// - /// - - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - end: function() { - /// - /// End the most recent 'destructive' operation, reverting the list of matched elements - /// back to its previous state. After an end operation, the list of matched elements will - /// revert to the last state of matched elements. - /// If there was no destructive operation before, an empty set is returned. - /// Part of DOM/Traversing - /// - /// - - return this.prevObject || jQuery(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: [].sort, - splice: [].splice -}; - -// Give the init function the jQuery prototype for later instantiation -jQuery.fn.init.prototype = jQuery.fn; - -jQuery.extend = jQuery.fn.extend = function() { - /// - /// Extend one object with one or more others, returning the original, - /// modified, object. This is a great utility for simple inheritance. - /// jQuery.extend(settings, options); - /// var settings = jQuery.extend({}, defaults, options); - /// Part of JavaScript - /// - /// - /// The object to extend - /// - /// - /// The object that will be merged into the first. - /// - /// - /// (optional) More objects to merge into the first - /// - /// - - // copy reference to target object - var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( length === i ) { - target = this; - --i; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging object literal values or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) { - var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src - : jQuery.isArray(copy) ? [] : {}; - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend({ - noConflict: function( deep ) { - /// - /// Run this function to give control of the $ variable back - /// to whichever library first implemented it. This helps to make - /// sure that jQuery doesn't conflict with the $ object - /// of other libraries. - /// By using this function, you will only be able to access jQuery - /// using the 'jQuery' variable. For example, where you used to do - /// $("div p"), you now must do jQuery("div p"). - /// Part of Core - /// - /// - - window.$ = _$; - - if ( deep ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // Handle when the DOM is ready - ready: function() { - /// - /// This method is internal. - /// - /// - - // Make sure that the DOM is not already loaded - if ( !jQuery.isReady ) { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready, 13 ); - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If there are functions bound, to execute - if ( readyList ) { - // Execute all of them - var fn, i = 0; - while ( (fn = readyList[ i++ ]) ) { - fn.call( document, jQuery ); - } - - // Reset the list of functions - readyList = null; - } - - // Trigger any bound ready events - if ( jQuery.fn.triggerHandler ) { - jQuery( document ).triggerHandler( "ready" ); - } - } - }, - - bindReady: function() { - if ( readyBound ) { - return; - } - - readyBound = true; - - // Catch cases where $(document).ready() is called after the - // browser event has already occurred. - if ( document.readyState === "complete" ) { - return jQuery.ready(); - } - - // Mozilla, Opera and webkit nightlies currently support this event - if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", jQuery.ready, false ); - - // If IE event model is used - } else if ( document.attachEvent ) { - // ensure firing before onload, - // maybe late but safe also for iframes - document.attachEvent("onreadystatechange", DOMContentLoaded); - - // A fallback to window.onload, that will always work - window.attachEvent( "onload", jQuery.ready ); - - // If IE and not a frame - // continually check to see if the document is ready - var toplevel = false; - - try { - toplevel = window.frameElement == null; - } catch(e) {} - - if ( document.documentElement.doScroll && toplevel ) { - doScrollCheck(); - } - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - /// - /// Determines if the parameter passed is a function. - /// - /// The object to check - /// True if the parameter is a function; otherwise false. - - return toString.call(obj) === "[object Function]"; - }, - - isArray: function( obj ) { - /// - /// Determine if the parameter passed is an array. - /// - /// Object to test whether or not it is an array. - /// True if the parameter is a function; otherwise false. - - return toString.call(obj) === "[object Array]"; - }, - - isPlainObject: function( obj ) { - /// - /// Check to see if an object is a plain object (created using "{}" or "new Object"). - /// - /// - /// The object that will be checked to see if it's a plain object. - /// - /// - - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) { - return false; - } - - // Not own constructor property must be Object - if ( obj.constructor - && !hasOwnProperty.call(obj, "constructor") - && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - - var key; - for ( key in obj ) {} - - return key === undefined || hasOwnProperty.call( obj, key ); - }, - - isEmptyObject: function( obj ) { - /// - /// Check to see if an object is empty (contains no properties). - /// - /// - /// The object that will be checked to see if it's empty. - /// - /// - - for ( var name in obj ) { - return false; - } - return true; - }, - - error: function( msg ) { - throw msg; - }, - - parseJSON: function( data ) { - if ( typeof data !== "string" || !data ) { - return null; - } - - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") - .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) { - - // Try to use the native JSON parser first - return window.JSON && window.JSON.parse ? - window.JSON.parse( data ) : - (new Function("return " + data))(); - - } else { - jQuery.error( "Invalid JSON: " + data ); - } - }, - - noop: function() { - /// - /// An empty function. - /// - /// - }, - - // Evalulates a script in a global context - globalEval: function( data ) { - /// - /// Internally evaluates a script in a global context. - /// - /// - - if ( data && rnotwhite.test(data) ) { - // Inspired by code by Andrea Giammarchi - // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html - var head = document.getElementsByTagName("head")[0] || document.documentElement, - script = document.createElement("script"); - - script.type = "text/javascript"; - - if ( jQuery.support.scriptEval ) { - script.appendChild( document.createTextNode( data ) ); - } else { - script.text = data; - } - - // Use insertBefore instead of appendChild to circumvent an IE6 bug. - // This arises when a base node is used (#2709). - head.insertBefore( script, head.firstChild ); - head.removeChild( script ); - } - }, - - nodeName: function( elem, name ) { - /// - /// Checks whether the specified element has the specified DOM node name. - /// - /// The element to examine - /// The node name to check - /// True if the specified node name matches the node's DOM node name; otherwise false - - return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); - }, - - // args is for internal usage only - each: function( object, callback, args ) { - /// - /// A generic iterator function, which can be used to seemlessly - /// iterate over both objects and arrays. This function is not the same - /// as $().each() - which is used to iterate, exclusively, over a jQuery - /// object. This function can be used to iterate over anything. - /// The callback has two arguments:the key (objects) or index (arrays) as first - /// the first, and the value as the second. - /// Part of JavaScript - /// - /// - /// The object, or array, to iterate over. - /// - /// - /// The function that will be executed on every object. - /// - /// - - var name, i = 0, - length = object.length, - isObj = length === undefined || jQuery.isFunction(object); - - if ( args ) { - if ( isObj ) { - for ( name in object ) { - if ( callback.apply( object[ name ], args ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.apply( object[ i++ ], args ) === false ) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if ( isObj ) { - for ( name in object ) { - if ( callback.call( object[ name ], name, object[ name ] ) === false ) { - break; - } - } - } else { - for ( var value = object[0]; - i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} - } - } - - return object; - }, - - trim: function( text ) { - /// - /// Remove the whitespace from the beginning and end of a string. - /// Part of JavaScript - /// - /// - /// - /// The string to trim. - /// - - return (text || "").replace( rtrim, "" ); - }, - - // results is for internal usage only - makeArray: function( array, results ) { - /// - /// Turns anything into a true array. This is an internal method. - /// - /// Anything to turn into an actual Array - /// - /// - - var ret = results || []; - - if ( array != null ) { - // The window, strings (and functions) also have 'length' - // The extra typeof function check is to prevent crashes - // in Safari 2 (See: #3039) - if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) { - push.call( ret, array ); - } else { - jQuery.merge( ret, array ); - } - } - - return ret; - }, - - inArray: function( elem, array ) { - if ( array.indexOf ) { - return array.indexOf( elem ); - } - - for ( var i = 0, length = array.length; i < length; i++ ) { - if ( array[ i ] === elem ) { - return i; - } - } - - return -1; - }, - - merge: function( first, second ) { - /// - /// Merge two arrays together, removing all duplicates. - /// The new array is: All the results from the first array, followed - /// by the unique results from the second array. - /// Part of JavaScript - /// - /// - /// - /// The first array to merge. - /// - /// - /// The second array to merge. - /// - - var i = first.length, j = 0; - - if ( typeof second.length === "number" ) { - for ( var l = second.length; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, inv ) { - /// - /// Filter items out of an array, by using a filter function. - /// The specified function will be passed two arguments: The - /// current array item and the index of the item in the array. The - /// function must return 'true' to keep the item in the array, - /// false to remove it. - /// }); - /// Part of JavaScript - /// - /// - /// - /// array The Array to find items in. - /// - /// - /// The function to process each item against. - /// - /// - /// Invert the selection - select the opposite of the function. - /// - - var ret = []; - - // Go through the array, only saving the items - // that pass the validator function - for ( var i = 0, length = elems.length; i < length; i++ ) { - if ( !inv !== !callback( elems[ i ], i ) ) { - ret.push( elems[ i ] ); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - /// - /// Translate all items in an array to another array of items. - /// The translation function that is provided to this method is - /// called for each item in the array and is passed one argument: - /// The item to be translated. - /// The function can then return the translated value, 'null' - /// (to remove the item), or an array of values - which will - /// be flattened into the full array. - /// Part of JavaScript - /// - /// - /// - /// array The Array to translate. - /// - /// - /// The function to process each item against. - /// - - var ret = [], value; - - // Go through the array, translating each of the items to their - // new value (or values). - for ( var i = 0, length = elems.length; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - - return ret.concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - proxy: function( fn, proxy, thisObject ) { - /// - /// Takes a function and returns a new one that will always have a particular scope. - /// - /// - /// The function whose scope will be changed. - /// - /// - /// The object to which the scope of the function should be set. - /// - /// - - if ( arguments.length === 2 ) { - if ( typeof proxy === "string" ) { - thisObject = fn; - fn = thisObject[ proxy ]; - proxy = undefined; - - } else if ( proxy && !jQuery.isFunction( proxy ) ) { - thisObject = proxy; - proxy = undefined; - } - } - - if ( !proxy && fn ) { - proxy = function() { - return fn.apply( thisObject || this, arguments ); - }; - } - - // Set the guid of unique handler to the same of original handler, so it can be removed - if ( fn ) { - proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; - } - - // So proxy can be declared as an argument - return proxy; - }, - - // Use of jQuery.browser is frowned upon. - // More details: http://docs.jquery.com/Utilities/jQuery.browser - uaMatch: function( ua ) { - ua = ua.toLowerCase(); - - var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) || - /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) || - /(msie) ([\w.]+)/.exec( ua ) || - !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) || - []; - - return { browser: match[1] || "", version: match[2] || "0" }; - }, - - browser: {} -}); - -browserMatch = jQuery.uaMatch( userAgent ); -if ( browserMatch.browser ) { - jQuery.browser[ browserMatch.browser ] = true; - jQuery.browser.version = browserMatch.version; -} - -// Deprecated, use jQuery.browser.webkit instead -if ( jQuery.browser.webkit ) { - jQuery.browser.safari = true; -} - -if ( indexOf ) { - jQuery.inArray = function( elem, array ) { - /// - /// Determines the index of the first parameter in the array. - /// - /// The value to see if it exists in the array. - /// The array to look through for the value - /// The 0-based index of the item if it was found, otherwise -1. - - return indexOf.call( array, elem ); - }; -} - -// All jQuery objects should point back to these -rootjQuery = jQuery(document); - -// Cleanup functions for the document ready method -if ( document.addEventListener ) { - DOMContentLoaded = function() { - document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - jQuery.ready(); - }; - -} else if ( document.attachEvent ) { - DOMContentLoaded = function() { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( document.readyState === "complete" ) { - document.detachEvent( "onreadystatechange", DOMContentLoaded ); - jQuery.ready(); - } - }; -} - -// The DOM ready check for Internet Explorer -function doScrollCheck() { - if ( jQuery.isReady ) { - return; - } - - try { - // If IE is used, use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - document.documentElement.doScroll("left"); - } catch( error ) { - setTimeout( doScrollCheck, 1 ); - return; - } - - // and execute any waiting functions - jQuery.ready(); -} - -function evalScript( i, elem ) { - /// - /// This method is internal. - /// - /// - - if ( elem.src ) { - jQuery.ajax({ - url: elem.src, - async: false, - dataType: "script" - }); - } else { - jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); - } - - if ( elem.parentNode ) { - elem.parentNode.removeChild( elem ); - } -} - -// Mutifunctional method to get and set values to a collection -// The value/s can be optionally by executed if its a function -function access( elems, key, value, exec, fn, pass ) { - var length = elems.length; - - // Setting many attributes - if ( typeof key === "object" ) { - for ( var k in key ) { - access( elems, k, key[k], exec, fn, value ); - } - return elems; - } - - // Setting one attribute - if ( value !== undefined ) { - // Optionally, function values get executed if exec is true - exec = !pass && exec && jQuery.isFunction(value); - - for ( var i = 0; i < length; i++ ) { - fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); - } - - return elems; - } - - // Getting an attribute - return length ? fn( elems[0], key ) : null; -} - -function now() { - /// - /// Gets the current date. - /// - /// The current date. - - return (new Date).getTime(); -} - -// [vsdoc] The following function has been modified for IntelliSense. -// [vsdoc] Stubbing support properties to "false" for IntelliSense compat. -(function() { - - jQuery.support = {}; - - // var root = document.documentElement, - // script = document.createElement("script"), - // div = document.createElement("div"), - // id = "script" + now(); - - // div.style.display = "none"; - // div.innerHTML = "
a"; - - // var all = div.getElementsByTagName("*"), - // a = div.getElementsByTagName("a")[0]; - - // // Can't get basic test support - // if ( !all || !all.length || !a ) { - // return; - // } - - jQuery.support = { - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: false, - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: false, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: false, - - // Get the style information from getAttribute - // (IE uses .cssText insted) - style: false, - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: false, - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: false, - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: false, - - // Make sure that if no value is specified for a checkbox - // that it defaults to "on". - // (WebKit defaults to "" instead) - checkOn: false, - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: false, - - // Will be defined later - checkClone: false, - scriptEval: false, - noCloneEvent: false, - boxModel: false - }; - - // script.type = "text/javascript"; - // try { - // script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); - // } catch(e) {} - - // root.insertBefore( script, root.firstChild ); - - // // Make sure that the execution of code works by injecting a script - // // tag with appendChild/createTextNode - // // (IE doesn't support this, fails, and uses .text instead) - // if ( window[ id ] ) { - // jQuery.support.scriptEval = true; - // delete window[ id ]; - // } - - // root.removeChild( script ); - - // if ( div.attachEvent && div.fireEvent ) { - // div.attachEvent("onclick", function click() { - // // Cloning a node shouldn't copy over any - // // bound event handlers (IE does this) - // jQuery.support.noCloneEvent = false; - // div.detachEvent("onclick", click); - // }); - // div.cloneNode(true).fireEvent("onclick"); - // } - - // div = document.createElement("div"); - // div.innerHTML = ""; - - // var fragment = document.createDocumentFragment(); - // fragment.appendChild( div.firstChild ); - - // // WebKit doesn't clone checked state correctly in fragments - // jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; - - // // Figure out if the W3C box model works as expected - // // document.body must exist before we can do this - // jQuery(function() { - // var div = document.createElement("div"); - // div.style.width = div.style.paddingLeft = "1px"; - - // document.body.appendChild( div ); - // jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; - // document.body.removeChild( div ).style.display = 'none'; - // div = null; - // }); - - // // Technique from Juriy Zaytsev - // // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ - // var eventSupported = function( eventName ) { - // var el = document.createElement("div"); - // eventName = "on" + eventName; - - // var isSupported = (eventName in el); - // if ( !isSupported ) { - // el.setAttribute(eventName, "return;"); - // isSupported = typeof el[eventName] === "function"; - // } - // el = null; - - // return isSupported; - // }; - - jQuery.support.submitBubbles = false; - jQuery.support.changeBubbles = false; - - // // release memory in IE - // root = script = div = all = a = null; -})(); - -jQuery.props = { - "for": "htmlFor", - "class": "className", - readonly: "readOnly", - maxlength: "maxLength", - cellspacing: "cellSpacing", - rowspan: "rowSpan", - colspan: "colSpan", - tabindex: "tabIndex", - usemap: "useMap", - frameborder: "frameBorder" -}; -var expando = "jQuery" + now(), uuid = 0, windowData = {}; -var emptyObject = {}; - -jQuery.extend({ - cache: {}, - - expando:expando, - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - "object": true, - "applet": true - }, - - data: function( elem, name, data ) { - /// - /// Store arbitrary data associated with the specified element. - /// - /// - /// The DOM element to associate with the data. - /// - /// - /// A string naming the piece of data to set. - /// - /// - /// The new data value. - /// - /// - - if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { - return; - } - - elem = elem == window ? - windowData : - elem; - - var id = elem[ expando ], cache = jQuery.cache, thisCache; - - // Handle the case where there's no name immediately - if ( !name && !id ) { - return null; - } - - // Compute a unique ID for the element - if ( !id ) { - id = ++uuid; - } - - // Avoid generating a new cache unless none exists and we - // want to manipulate it. - if ( typeof name === "object" ) { - elem[ expando ] = id; - thisCache = cache[ id ] = jQuery.extend(true, {}, name); - } else if ( cache[ id ] ) { - thisCache = cache[ id ]; - } else if ( typeof data === "undefined" ) { - thisCache = emptyObject; - } else { - thisCache = cache[ id ] = {}; - } - - // Prevent overriding the named cache with undefined values - if ( data !== undefined ) { - elem[ expando ] = id; - thisCache[ name ] = data; - } - - return typeof name === "string" ? thisCache[ name ] : thisCache; - }, - - removeData: function( elem, name ) { - if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { - return; - } - - elem = elem == window ? - windowData : - elem; - - var id = elem[ expando ], cache = jQuery.cache, thisCache = cache[ id ]; - - // If we want to remove a specific section of the element's data - if ( name ) { - if ( thisCache ) { - // Remove the section of cache data - delete thisCache[ name ]; - - // If we've removed all the data, remove the element's cache - if ( jQuery.isEmptyObject(thisCache) ) { - jQuery.removeData( elem ); - } - } - - // Otherwise, we want to remove all of the element's data - } else { - // Clean up the element expando - try { - delete elem[ expando ]; - } catch( e ) { - // IE has trouble directly removing the expando - // but it's ok with using removeAttribute - if ( elem.removeAttribute ) { - elem.removeAttribute( expando ); - } - } - - // Completely remove the data cache - delete cache[ id ]; - } - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - /// - /// Store arbitrary data associated with the matched elements. - /// - /// - /// A string naming the piece of data to set. - /// - /// - /// The new data value. - /// - /// - - if ( typeof key === "undefined" && this.length ) { - return jQuery.data( this[0] ); - - } else if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } - - var parts = key.split("."); - parts[1] = parts[1] ? "." + parts[1] : ""; - - if ( value === undefined ) { - var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); - - if ( data === undefined && this.length ) { - data = jQuery.data( this[0], key ); - } - return data === undefined && parts[1] ? - this.data( parts[0] ) : - data; - } else { - return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function() { - jQuery.data( this, key, value ); - }); - } - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); -jQuery.extend({ - queue: function( elem, type, data ) { - if ( !elem ) { - return; - } - - type = (type || "fx") + "queue"; - var q = jQuery.data( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( !data ) { - return q || []; - } - - if ( !q || jQuery.isArray(data) ) { - q = jQuery.data( elem, type, jQuery.makeArray(data) ); - - } else { - q.push( data ); - } - - return q; - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), fn = queue.shift(); - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - } - - if ( fn ) { - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift("inprogress"); - } - - fn.call(elem, function() { - jQuery.dequeue(elem, type); - }); - } - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - /// - /// 1: queue() - Returns a reference to the first element's queue (which is an array of functions). - /// 2: queue(callback) - Adds a new function, to be executed, onto the end of the queue of all matched elements. - /// 3: queue(queue) - Replaces the queue of all matched element with this new queue (the array of functions). - /// - /// The function to add to the queue. - /// - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - } - - if ( data === undefined ) { - return jQuery.queue( this[0], type ); - } - return this.each(function( i, elem ) { - var queue = jQuery.queue( this, type, data ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - /// - /// Removes a queued function from the front of the queue and executes it. - /// - /// The type of queue to access. - /// - - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - /// - /// Set a timer to delay execution of subsequent items in the queue. - /// - /// - /// An integer indicating the number of milliseconds to delay execution of the next item in the queue. - /// - /// - /// A string containing the name of the queue. Defaults to fx, the standard effects queue. - /// - /// - - time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; - type = type || "fx"; - - return this.queue( type, function() { - var elem = this; - setTimeout(function() { - jQuery.dequeue( elem, type ); - }, time ); - }); - }, - - clearQueue: function( type ) { - /// - /// Remove from the queue all items that have not yet been run. - /// - /// - /// A string containing the name of the queue. Defaults to fx, the standard effects queue. - /// - /// - - return this.queue( type || "fx", [] ); - } -}); -var rclass = /[\n\t]/g, - rspace = /\s+/, - rreturn = /\r/g, - rspecialurl = /href|src|style/, - rtype = /(button|input)/i, - rfocusable = /(button|input|object|select|textarea)/i, - rclickable = /^(a|area)$/i, - rradiocheck = /radio|checkbox/; - -jQuery.fn.extend({ - attr: function( name, value ) { - /// - /// Set a single property to a computed value, on all matched elements. - /// Instead of a value, a function is provided, that computes the value. - /// Part of DOM/Attributes - /// - /// - /// - /// The name of the property to set. - /// - /// - /// A function returning the value to set. - /// - - return access( this, name, value, true, jQuery.attr ); - }, - - removeAttr: function( name, fn ) { - /// - /// Remove an attribute from each of the matched elements. - /// Part of DOM/Attributes - /// - /// - /// An attribute to remove. - /// - /// - - return this.each(function(){ - jQuery.attr( this, name, "" ); - if ( this.nodeType === 1 ) { - this.removeAttribute( name ); - } - }); - }, - - addClass: function( value ) { - /// - /// Adds the specified class(es) to each of the set of matched elements. - /// Part of DOM/Attributes - /// - /// - /// One or more class names to be added to the class attribute of each matched element. - /// - /// - - if ( jQuery.isFunction(value) ) { - return this.each(function(i) { - var self = jQuery(this); - self.addClass( value.call(this, i, self.attr("class")) ); - }); - } - - if ( value && typeof value === "string" ) { - var classNames = (value || "").split( rspace ); - - for ( var i = 0, l = this.length; i < l; i++ ) { - var elem = this[i]; - - if ( elem.nodeType === 1 ) { - if ( !elem.className ) { - elem.className = value; - - } else { - var className = " " + elem.className + " "; - for ( var c = 0, cl = classNames.length; c < cl; c++ ) { - if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { - elem.className += " " + classNames[c]; - } - } - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - /// - /// Removes all or the specified class(es) from the set of matched elements. - /// Part of DOM/Attributes - /// - /// - /// (Optional) A class name to be removed from the class attribute of each matched element. - /// - /// - - if ( jQuery.isFunction(value) ) { - return this.each(function(i) { - var self = jQuery(this); - self.removeClass( value.call(this, i, self.attr("class")) ); - }); - } - - if ( (value && typeof value === "string") || value === undefined ) { - var classNames = (value || "").split(rspace); - - for ( var i = 0, l = this.length; i < l; i++ ) { - var elem = this[i]; - - if ( elem.nodeType === 1 && elem.className ) { - if ( value ) { - var className = (" " + elem.className + " ").replace(rclass, " "); - for ( var c = 0, cl = classNames.length; c < cl; c++ ) { - className = className.replace(" " + classNames[c] + " ", " "); - } - elem.className = className.substring(1, className.length - 1); - - } else { - elem.className = ""; - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - /// - /// Add or remove a class from each element in the set of matched elements, depending - /// on either the class's presence or the value of the switch argument. - /// - /// - /// A class name to be toggled for each element in the matched set. - /// - /// - /// A boolean value to determine whether the class should be added or removed. - /// - /// - - var type = typeof value, isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function(i) { - var self = jQuery(this); - self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, i = 0, self = jQuery(this), - state = stateVal, - classNames = value.split( rspace ); - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space seperated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); - } - - } else if ( type === "undefined" || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery.data( this, "__className__", this.className ); - } - - // toggle whole className - this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - /// - /// Checks the current selection against a class and returns whether at least one selection has a given class. - /// - /// The class to check against - /// True if at least one element in the selection has the class, otherwise false. - - var className = " " + selector + " "; - for ( var i = 0, l = this.length; i < l; i++ ) { - if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { - return true; - } - } - - return false; - }, - - val: function( value ) { - /// - /// Set the value of every matched element. - /// Part of DOM/Attributes - /// - /// - /// - /// A string of text or an array of strings to set as the value property of each - /// matched element. - /// - - if ( value === undefined ) { - var elem = this[0]; - - if ( elem ) { - if ( jQuery.nodeName( elem, "option" ) ) { - return (elem.attributes.value || {}).specified ? elem.value : elem.text; - } - - // We need to handle select boxes special - if ( jQuery.nodeName( elem, "select" ) ) { - var index = elem.selectedIndex, - values = [], - options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if ( index < 0 ) { - return null; - } - - // Loop through all the selected options - for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { - var option = options[ i ]; - - if ( option.selected ) { - // Get the specifc value for the option - value = jQuery(option).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - return values; - } - - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { - return elem.getAttribute("value") === null ? "on" : elem.value; - } - - - // Everything else, we just grab the value - return (elem.value || "").replace(rreturn, ""); - - } - - return undefined; - } - - var isFunction = jQuery.isFunction(value); - - return this.each(function(i) { - var self = jQuery(this), val = value; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call(this, i, self.val()); - } - - // Typecast each time if the value is a Function and the appended - // value is therefore different each time. - if ( typeof val === "number" ) { - val += ""; - } - - if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { - this.checked = jQuery.inArray( self.val(), val ) >= 0; - - } else if ( jQuery.nodeName( this, "select" ) ) { - var values = jQuery.makeArray(val); - - jQuery( "option", this ).each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { - this.selectedIndex = -1; - } - - } else { - this.value = val; - } - }); - } -}); - -jQuery.extend({ - attrFn: { - val: true, - css: true, - html: true, - text: true, - data: true, - width: true, - height: true, - offset: true - }, - - attr: function( elem, name, value, pass ) { - /// - /// This method is internal. - /// - /// - - // don't set attributes on text and comment nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { - return undefined; - } - - if ( pass && name in jQuery.attrFn ) { - return jQuery(elem)[name](value); - } - - var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), - // Whether we are setting (or getting) - set = value !== undefined; - - // Try to normalize/fix the name - name = notxml && jQuery.props[ name ] || name; - - // Only do all the following if this is a node (faster for style) - if ( elem.nodeType === 1 ) { - // These attributes require special treatment - var special = rspecialurl.test( name ); - - // Safari mis-reports the default selected property of an option - // Accessing the parent's selectedIndex property fixes it - if ( name === "selected" && !jQuery.support.optSelected ) { - var parent = elem.parentNode; - if ( parent ) { - parent.selectedIndex; - - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - } - - // If applicable, access the attribute via the DOM 0 way - if ( name in elem && notxml && !special ) { - if ( set ) { - // We can't allow the type property to be changed (since it causes problems in IE) - if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { - jQuery.error( "type property can't be changed" ); - } - - elem[ name ] = value; - } - - // browsers index elements by id/name on forms, give priority to attributes. - if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { - return elem.getAttributeNode( name ).nodeValue; - } - - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - if ( name === "tabIndex" ) { - var attributeNode = elem.getAttributeNode( "tabIndex" ); - - return attributeNode && attributeNode.specified ? - attributeNode.value : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; - } - - return elem[ name ]; - } - - if ( !jQuery.support.style && notxml && name === "style" ) { - if ( set ) { - elem.style.cssText = "" + value; - } - - return elem.style.cssText; - } - - if ( set ) { - // convert the value to a string (all browsers do this but IE) see #1070 - elem.setAttribute( name, "" + value ); - } - - var attr = !jQuery.support.hrefNormalized && notxml && special ? - // Some attributes require a special call on IE - elem.getAttribute( name, 2 ) : - elem.getAttribute( name ); - - // Non-existent attributes return null, we normalize to undefined - return attr === null ? undefined : attr; - } - - // elem is actually elem.style ... set the style - // Using attr for specific style information is now deprecated. Use style insead. - return jQuery.style( elem, name, value ); - } -}); -var fcleanup = function( nm ) { - return nm.replace(/[^\w\s\.\|`]/g, function( ch ) { - return "\\" + ch; - }); -}; - -/* - * A number of helper functions used for managing events. - * Many of the ideas behind this code originated from - * Dean Edwards' addEvent library. - */ -jQuery.event = { - - // Bind an event to an element - // Original by Dean Edwards - add: function( elem, types, handler, data ) { - /// - /// This method is internal. - /// - /// - - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // For whatever reason, IE has trouble passing the window object - // around, causing it to be cloned in the process - if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) { - elem = window; - } - - // Make sure that the function being executed has a unique ID - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // if data is passed, bind to handler - if ( data !== undefined ) { - // Create temporary function pointer to original handler - var fn = handler; - - // Create unique handler function, wrapped around original handler - handler = jQuery.proxy( fn ); - - // Store data in unique handler - handler.data = data; - } - - // Init the element's event structure - var events = jQuery.data( elem, "events" ) || jQuery.data( elem, "events", {} ), - handle = jQuery.data( elem, "handle" ), eventHandle; - - if ( !handle ) { - eventHandle = function() { - // Handle the second event of a trigger and when - // an event is called after a page has unloaded - return typeof jQuery !== "undefined" && !jQuery.event.triggered ? - jQuery.event.handle.apply( eventHandle.elem, arguments ) : - undefined; - }; - - handle = jQuery.data( elem, "handle", eventHandle ); - } - - // If no handle is found then we must be trying to bind to one of the - // banned noData elements - if ( !handle ) { - return; - } - - // Add elem as a property of the handle function - // This is to prevent a memory leak with non-native - // event in IE. - handle.elem = elem; - - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = types.split( /\s+/ ); - - var type, i = 0; - - while ( (type = types[ i++ ]) ) { - // Namespaced event handlers - var namespaces = type.split("."); - type = namespaces.shift(); - - if ( i > 1 ) { - handler = jQuery.proxy( handler ); - - if ( data !== undefined ) { - handler.data = data; - } - } - - handler.type = namespaces.slice(0).sort().join("."); - - // Get the current list of functions bound to this event - var handlers = events[ type ], - special = this.special[ type ] || {}; - - // Init the event handler queue - if ( !handlers ) { - handlers = events[ type ] = {}; - - // Check for a special event handler - // Only use addEventListener/attachEvent if the special - // events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, handler) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, handle, false ); - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, handle ); - } - } - } - - if ( special.add ) { - var modifiedHandler = special.add.call( elem, handler, data, namespaces, handlers ); - if ( modifiedHandler && jQuery.isFunction( modifiedHandler ) ) { - modifiedHandler.guid = modifiedHandler.guid || handler.guid; - modifiedHandler.data = modifiedHandler.data || handler.data; - modifiedHandler.type = modifiedHandler.type || handler.type; - handler = modifiedHandler; - } - } - - // Add the function to the element's handler list - handlers[ handler.guid ] = handler; - - // Keep track of which events have been used, for global triggering - this.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - global: {}, - - // Detach an event or set of events from an element - remove: function( elem, types, handler ) { - /// - /// This method is internal. - /// - /// - - // don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - var events = jQuery.data( elem, "events" ), ret, type, fn; - - if ( events ) { - // Unbind all events for the element - if ( types === undefined || (typeof types === "string" && types.charAt(0) === ".") ) { - for ( type in events ) { - this.remove( elem, type + (types || "") ); - } - } else { - // types is actually an event object here - if ( types.type ) { - handler = types.handler; - types = types.type; - } - - // Handle multiple events separated by a space - // jQuery(...).unbind("mouseover mouseout", fn); - types = types.split(/\s+/); - var i = 0; - while ( (type = types[ i++ ]) ) { - // Namespaced event handlers - var namespaces = type.split("."); - type = namespaces.shift(); - var all = !namespaces.length, - cleaned = jQuery.map( namespaces.slice(0).sort(), fcleanup ), - namespace = new RegExp("(^|\\.)" + cleaned.join("\\.(?:.*\\.)?") + "(\\.|$)"), - special = this.special[ type ] || {}; - - if ( events[ type ] ) { - // remove the given handler for the given type - if ( handler ) { - fn = events[ type ][ handler.guid ]; - delete events[ type ][ handler.guid ]; - - // remove all handlers for the given type - } else { - for ( var handle in events[ type ] ) { - // Handle the removal of namespaced events - if ( all || namespace.test( events[ type ][ handle ].type ) ) { - delete events[ type ][ handle ]; - } - } - } - - if ( special.remove ) { - special.remove.call( elem, namespaces, fn); - } - - // remove generic event handler if no more handlers exist - for ( ret in events[ type ] ) { - break; - } - if ( !ret ) { - if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, jQuery.data( elem, "handle" ), false ); - } else if ( elem.detachEvent ) { - elem.detachEvent( "on" + type, jQuery.data( elem, "handle" ) ); - } - } - ret = null; - delete events[ type ]; - } - } - } - } - - // Remove the expando if it's no longer used - for ( ret in events ) { - break; - } - if ( !ret ) { - var handle = jQuery.data( elem, "handle" ); - if ( handle ) { - handle.elem = null; - } - jQuery.removeData( elem, "events" ); - jQuery.removeData( elem, "handle" ); - } - } - }, - - // bubbling is internal - trigger: function( event, data, elem /*, bubbling */ ) { - /// - /// This method is internal. - /// - /// - - // Event object or event type - var type = event.type || event, - bubbling = arguments[3]; - - if ( !bubbling ) { - event = typeof event === "object" ? - // jQuery.Event object - event[expando] ? event : - // Object literal - jQuery.extend( jQuery.Event(type), event ) : - // Just the event type (string) - jQuery.Event(type); - - if ( type.indexOf("!") >= 0 ) { - event.type = type = type.slice(0, -1); - event.exclusive = true; - } - - // Handle a global trigger - if ( !elem ) { - // Don't bubble custom events when global (to avoid too much overhead) - event.stopPropagation(); - - // Only trigger if we've ever bound an event for it - if ( this.global[ type ] ) { - jQuery.each( jQuery.cache, function() { - if ( this.events && this.events[type] ) { - jQuery.event.trigger( event, data, this.handle.elem ); - } - }); - } - } - - // Handle triggering a single element - - // don't do events on text and comment nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { - return undefined; - } - - // Clean up in case it is reused - event.result = undefined; - event.target = elem; - - // Clone the incoming data, if any - data = jQuery.makeArray( data ); - data.unshift( event ); - } - - event.currentTarget = elem; - - // Trigger the event, it is assumed that "handle" is a function - var handle = jQuery.data( elem, "handle" ); - if ( handle ) { - handle.apply( elem, data ); - } - - var parent = elem.parentNode || elem.ownerDocument; - - // Trigger an inline bound script - try { - if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { - if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { - event.result = false; - } - } - - // prevent IE from throwing an error for some elements with some event types, see #3533 - } catch (e) {} - - if ( !event.isPropagationStopped() && parent ) { - jQuery.event.trigger( event, data, parent, true ); - - } else if ( !event.isDefaultPrevented() ) { - var target = event.target, old, - isClick = jQuery.nodeName(target, "a") && type === "click"; - - if ( !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { - try { - if ( target[ type ] ) { - // Make sure that we don't accidentally re-trigger the onFOO events - old = target[ "on" + type ]; - - if ( old ) { - target[ "on" + type ] = null; - } - - this.triggered = true; - target[ type ](); - } - - // prevent IE from throwing an error for some elements with some event types, see #3533 - } catch (e) {} - - if ( old ) { - target[ "on" + type ] = old; - } - - this.triggered = false; - } - } - }, - - handle: function( event ) { - /// - /// This method is internal. - /// - /// - - // returned undefined or false - var all, handlers; - - event = arguments[0] = jQuery.event.fix( event || window.event ); - event.currentTarget = this; - - // Namespaced event handlers - var namespaces = event.type.split("."); - event.type = namespaces.shift(); - - // Cache this now, all = true means, any handler - all = !namespaces.length && !event.exclusive; - - var namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)"); - - handlers = ( jQuery.data(this, "events") || {} )[ event.type ]; - - for ( var j in handlers ) { - var handler = handlers[ j ]; - - // Filter the functions by class - if ( all || namespace.test(handler.type) ) { - // Pass in a reference to the handler function itself - // So that we can later remove it - event.handler = handler; - event.data = handler.data; - - var ret = handler.apply( this, arguments ); - - if ( ret !== undefined ) { - event.result = ret; - if ( ret === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - - if ( event.isImmediatePropagationStopped() ) { - break; - } - - } - } - - return event.result; - }, - - props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), - - fix: function( event ) { - /// - /// This method is internal. - /// - /// - - if ( event[ expando ] ) { - return event; - } - - // store a copy of the original event object - // and "clone" to set read-only properties - var originalEvent = event; - event = jQuery.Event( originalEvent ); - - for ( var i = this.props.length, prop; i; ) { - prop = this.props[ --i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Fix target property, if necessary - if ( !event.target ) { - event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either - } - - // check if target is a textnode (safari) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - // Add relatedTarget, if necessary - if ( !event.relatedTarget && event.fromElement ) { - event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; - } - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && event.clientX != null ) { - var doc = document.documentElement, body = document.body; - event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); - event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); - } - - // Add which for key events - if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) { - event.which = event.charCode || event.keyCode; - } - - // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) - if ( !event.metaKey && event.ctrlKey ) { - event.metaKey = event.ctrlKey; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && event.button !== undefined ) { - event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); - } - - return event; - }, - - // Deprecated, use jQuery.guid instead - guid: 1E8, - - // Deprecated, use jQuery.proxy instead - proxy: jQuery.proxy, - - special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady, - teardown: jQuery.noop - }, - - live: { - add: function( proxy, data, namespaces, live ) { - jQuery.extend( proxy, data || {} ); - - proxy.guid += data.selector + data.live; - data.liveProxy = proxy; - - jQuery.event.add( this, data.live, liveHandler, data ); - - }, - - remove: function( namespaces ) { - if ( namespaces.length ) { - var remove = 0, name = new RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)"); - - jQuery.each( (jQuery.data(this, "events").live || {}), function() { - if ( name.test(this.type) ) { - remove++; - } - }); - - if ( remove < 1 ) { - jQuery.event.remove( this, namespaces[0], liveHandler ); - } - } - }, - special: {} - }, - beforeunload: { - setup: function( data, namespaces, fn ) { - // We only want to do this special case on windows - if ( this.setInterval ) { - this.onbeforeunload = fn; - } - - return false; - }, - teardown: function( namespaces, fn ) { - if ( this.onbeforeunload === fn ) { - this.onbeforeunload = null; - } - } - } - } -}; - -jQuery.Event = function( src ) { - // Allow instantiation without the 'new' keyword - if ( !this.preventDefault ) { - return new jQuery.Event( src ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - // Event type - } else { - this.type = src; - } - - // timeStamp is buggy for some events on Firefox(#3843) - // So we won't rely on the native value - this.timeStamp = now(); - - // Mark it as fixed - this[ expando ] = true; -}; - -function returnFalse() { - return false; -} -function returnTrue() { - return true; -} - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - preventDefault: function() { - this.isDefaultPrevented = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - - // if preventDefault exists run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); - } - // otherwise set the returnValue property of the original event to false (IE) - e.returnValue = false; - }, - stopPropagation: function() { - this.isPropagationStopped = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - // if stopPropagation exists run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } - // otherwise set the cancelBubble property of the original event to true (IE) - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - }, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse -}; - -// Checks if an event happened on an element within another element -// Used in jQuery.event.special.mouseenter and mouseleave handlers -var withinElement = function( event ) { - // Check if mouse(over|out) are still within the same parent element - var parent = event.relatedTarget; - - // Traverse up the tree - while ( parent && parent !== this ) { - // Firefox sometimes assigns relatedTarget a XUL element - // which we cannot access the parentNode property of - try { - parent = parent.parentNode; - - // assuming we've left the element since we most likely mousedover a xul element - } catch(e) { - break; - } - } - - if ( parent !== this ) { - // set the correct event type - event.type = event.data; - - // handle event if we actually just moused on to a non sub-element - jQuery.event.handle.apply( this, arguments ); - } - -}, - -// In case of event delegation, we only need to rename the event.type, -// liveHandler will take care of the rest. -delegate = function( event ) { - event.type = event.data; - jQuery.event.handle.apply( this, arguments ); -}; - -// Create mouseenter and mouseleave events -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - setup: function( data ) { - jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); - }, - teardown: function( data ) { - jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); - } - }; -}); - -// submit delegation -if ( !jQuery.support.submitBubbles ) { - -jQuery.event.special.submit = { - setup: function( data, namespaces, fn ) { - if ( this.nodeName.toLowerCase() !== "form" ) { - jQuery.event.add(this, "click.specialSubmit." + fn.guid, function( e ) { - var elem = e.target, type = elem.type; - - if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { - return trigger( "submit", this, arguments ); - } - }); - - jQuery.event.add(this, "keypress.specialSubmit." + fn.guid, function( e ) { - var elem = e.target, type = elem.type; - - if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { - return trigger( "submit", this, arguments ); - } - }); - - } else { - return false; - } - }, - - remove: function( namespaces, fn ) { - jQuery.event.remove( this, "click.specialSubmit" + (fn ? "."+fn.guid : "") ); - jQuery.event.remove( this, "keypress.specialSubmit" + (fn ? "."+fn.guid : "") ); - } -}; - -} - -// change delegation, happens here so we have bind. -if ( !jQuery.support.changeBubbles ) { - -var formElems = /textarea|input|select/i; - -function getVal( elem ) { - var type = elem.type, val = elem.value; - - if ( type === "radio" || type === "checkbox" ) { - val = elem.checked; - - } else if ( type === "select-multiple" ) { - val = elem.selectedIndex > -1 ? - jQuery.map( elem.options, function( elem ) { - return elem.selected; - }).join("-") : - ""; - - } else if ( elem.nodeName.toLowerCase() === "select" ) { - val = elem.selectedIndex; - } - - return val; -} - -function testChange( e ) { - var elem = e.target, data, val; - - if ( !formElems.test( elem.nodeName ) || elem.readOnly ) { - return; - } - - data = jQuery.data( elem, "_change_data" ); - val = getVal(elem); - - // the current data will be also retrieved by beforeactivate - if ( e.type !== "focusout" || elem.type !== "radio" ) { - jQuery.data( elem, "_change_data", val ); - } - - if ( data === undefined || val === data ) { - return; - } - - if ( data != null || val ) { - e.type = "change"; - return jQuery.event.trigger( e, arguments[1], elem ); - } -} - -jQuery.event.special.change = { - filters: { - focusout: testChange, - - click: function( e ) { - var elem = e.target, type = elem.type; - - if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { - return testChange.call( this, e ); - } - }, - - // Change has to be called before submit - // Keydown will be called before keypress, which is used in submit-event delegation - keydown: function( e ) { - var elem = e.target, type = elem.type; - - if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || - (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || - type === "select-multiple" ) { - return testChange.call( this, e ); - } - }, - - // Beforeactivate happens also before the previous element is blurred - // with this event you can't trigger a change event, but you can store - // information/focus[in] is not needed anymore - beforeactivate: function( e ) { - var elem = e.target; - - if ( elem.nodeName.toLowerCase() === "input" && elem.type === "radio" ) { - jQuery.data( elem, "_change_data", getVal(elem) ); - } - } - }, - setup: function( data, namespaces, fn ) { - for ( var type in changeFilters ) { - jQuery.event.add( this, type + ".specialChange." + fn.guid, changeFilters[type] ); - } - - return formElems.test( this.nodeName ); - }, - remove: function( namespaces, fn ) { - for ( var type in changeFilters ) { - jQuery.event.remove( this, type + ".specialChange" + (fn ? "."+fn.guid : ""), changeFilters[type] ); - } - - return formElems.test( this.nodeName ); - } -}; - -var changeFilters = jQuery.event.special.change.filters; - -} - -function trigger( type, elem, args ) { - args[0].type = type; - return jQuery.event.handle.apply( elem, args ); -} - -// Create "bubbling" focus and blur events -if ( document.addEventListener ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - jQuery.event.special[ fix ] = { - setup: function() { - /// - /// This method is internal. - /// - /// - - this.addEventListener( orig, handler, true ); - }, - teardown: function() { - /// - /// This method is internal. - /// - /// - - this.removeEventListener( orig, handler, true ); - } - }; - - function handler( e ) { - e = jQuery.event.fix( e ); - e.type = fix; - return jQuery.event.handle.call( this, e ); - } - }); -} - -// jQuery.each(["bind", "one"], function( i, name ) { -// jQuery.fn[ name ] = function( type, data, fn ) { -// // Handle object literals -// if ( typeof type === "object" ) { -// for ( var key in type ) { -// this[ name ](key, data, type[key], fn); -// } -// return this; -// } -// -// if ( jQuery.isFunction( data ) ) { -// fn = data; -// data = undefined; -// } -// -// var handler = name === "one" ? jQuery.proxy( fn, function( event ) { -// jQuery( this ).unbind( event, handler ); -// return fn.apply( this, arguments ); -// }) : fn; -// -// return type === "unload" && name !== "one" ? -// this.one( type, data, fn ) : -// this.each(function() { -// jQuery.event.add( this, type, handler, data ); -// }); -// }; -// }); - -jQuery.fn[ "bind" ] = function( type, data, fn ) { - /// - /// Binds a handler to one or more events for each matched element. Can also bind custom events. - /// - /// One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error . - /// Additional data passed to the event handler as event.data - /// A function to bind to the event on each of the set of matched elements. function callback(eventObject) such that this corresponds to the dom element. - - // Handle object literals - if ( typeof type === "object" ) { - for ( var key in type ) { - this[ "bind" ](key, data, type[key], fn); - } - return this; - } - - if ( jQuery.isFunction( data ) ) { - fn = data; - data = undefined; - } - - var handler = "bind" === "one" ? jQuery.proxy( fn, function( event ) { - jQuery( this ).unbind( event, handler ); - return fn.apply( this, arguments ); - }) : fn; - - return type === "unload" && "bind" !== "one" ? - this.one( type, data, fn ) : - this.each(function() { - jQuery.event.add( this, type, handler, data ); - }); -}; - -jQuery.fn[ "one" ] = function( type, data, fn ) { - /// - /// Binds a handler to one or more events to be executed exactly once for each matched element. - /// - /// One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error . - /// Additional data passed to the event handler as event.data - /// A function to bind to the event on each of the set of matched elements. function callback(eventObject) such that this corresponds to the dom element. - - // Handle object literals - if ( typeof type === "object" ) { - for ( var key in type ) { - this[ "one" ](key, data, type[key], fn); - } - return this; - } - - if ( jQuery.isFunction( data ) ) { - fn = data; - data = undefined; - } - - var handler = "one" === "one" ? jQuery.proxy( fn, function( event ) { - jQuery( this ).unbind( event, handler ); - return fn.apply( this, arguments ); - }) : fn; - - return type === "unload" && "one" !== "one" ? - this.one( type, data, fn ) : - this.each(function() { - jQuery.event.add( this, type, handler, data ); - }); -}; - -jQuery.fn.extend({ - unbind: function( type, fn ) { - /// - /// Unbinds a handler from one or more events for each matched element. - /// - /// One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error . - /// A function to bind to the event on each of the set of matched elements. function callback(eventObject) such that this corresponds to the dom element. - - // Handle object literals - if ( typeof type === "object" && !type.preventDefault ) { - for ( var key in type ) { - this.unbind(key, type[key]); - } - return this; - } - - return this.each(function() { - jQuery.event.remove( this, type, fn ); - }); - }, - trigger: function( type, data ) { - /// - /// Triggers a type of event on every matched element. - /// - /// One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error . - /// Additional data passed to the event handler as additional arguments. - /// This parameter is undocumented. - - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - - triggerHandler: function( type, data ) { - /// - /// Triggers all bound event handlers on an element for a specific event type without executing the browser's default actions. - /// - /// One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error . - /// Additional data passed to the event handler as additional arguments. - /// This parameter is undocumented. - - if ( this[0] ) { - var event = jQuery.Event( type ); - event.preventDefault(); - event.stopPropagation(); - jQuery.event.trigger( event, data, this[0] ); - return event.result; - } - }, - - toggle: function( fn ) { - /// - /// Toggles among two or more function calls every other click. - /// - /// The functions among which to toggle execution - - // Save reference to arguments for access in closure - var args = arguments, i = 1; - - // link all the functions, so any of them can unbind this click handler - while ( i < args.length ) { - jQuery.proxy( fn, args[ i++ ] ); - } - - return this.click( jQuery.proxy( fn, function( event ) { - // Figure out which function to execute - var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; - jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); - - // Make sure that clicks stop - event.preventDefault(); - - // and execute the function - return args[ lastToggle ].apply( this, arguments ) || false; - })); - }, - - hover: function( fnOver, fnOut ) { - /// - /// Simulates hovering (moving the mouse on or off of an object). - /// - /// The function to fire when the mouse is moved over a matched element. - /// The function to fire when the mouse is moved off of a matched element. - - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); - } -}); - -// jQuery.each(["live", "die"], function( i, name ) { -// jQuery.fn[ name ] = function( types, data, fn ) { -// var type, i = 0; -// -// if ( jQuery.isFunction( data ) ) { -// fn = data; -// data = undefined; -// } -// -// types = (types || "").split( /\s+/ ); -// -// while ( (type = types[ i++ ]) != null ) { -// type = type === "focus" ? "focusin" : // focus --> focusin -// type === "blur" ? "focusout" : // blur --> focusout -// type === "hover" ? types.push("mouseleave") && "mouseenter" : // hover support -// type; -// -// if ( name === "live" ) { -// // bind live handler -// jQuery( this.context ).bind( liveConvert( type, this.selector ), { -// data: data, selector: this.selector, live: type -// }, fn ); -// -// } else { -// // unbind live handler -// jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null ); -// } -// } -// -// return this; -// } -// }); - -jQuery.fn[ "live" ] = function( types, data, fn ) { - /// - /// Attach a handler to the event for all elements which match the current selector, now or - /// in the future. - /// - /// - /// A string containing a JavaScript event type, such as "click" or "keydown". - /// - /// - /// A map of data that will be passed to the event handler. - /// - /// - /// A function to execute at the time the event is triggered. - /// - /// - - var type, i = 0; - - if ( jQuery.isFunction( data ) ) { - fn = data; - data = undefined; - } - - types = (types || "").split( /\s+/ ); - - while ( (type = types[ i++ ]) != null ) { - type = type === "focus" ? "focusin" : // focus --> focusin - type === "blur" ? "focusout" : // blur --> focusout - type === "hover" ? types.push("mouseleave") && "mouseenter" : // hover support - type; - - if ( "live" === "live" ) { - // bind live handler - jQuery( this.context ).bind( liveConvert( type, this.selector ), { - data: data, selector: this.selector, live: type - }, fn ); - - } else { - // unbind live handler - jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null ); - } - } - - return this; -} - -jQuery.fn[ "die" ] = function( types, data, fn ) { - /// - /// Remove all event handlers previously attached using .live() from the elements. - /// - /// - /// A string containing a JavaScript event type, such as click or keydown. - /// - /// - /// The function that is to be no longer executed. - /// - /// - - var type, i = 0; - - if ( jQuery.isFunction( data ) ) { - fn = data; - data = undefined; - } - - types = (types || "").split( /\s+/ ); - - while ( (type = types[ i++ ]) != null ) { - type = type === "focus" ? "focusin" : // focus --> focusin - type === "blur" ? "focusout" : // blur --> focusout - type === "hover" ? types.push("mouseleave") && "mouseenter" : // hover support - type; - - if ( "die" === "live" ) { - // bind live handler - jQuery( this.context ).bind( liveConvert( type, this.selector ), { - data: data, selector: this.selector, live: type - }, fn ); - - } else { - // unbind live handler - jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null ); - } - } - - return this; -} - -function liveHandler( event ) { - var stop, elems = [], selectors = [], args = arguments, - related, match, fn, elem, j, i, l, data, - live = jQuery.extend({}, jQuery.data( this, "events" ).live); - - // Make sure we avoid non-left-click bubbling in Firefox (#3861) - if ( event.button && event.type === "click" ) { - return; - } - - for ( j in live ) { - fn = live[j]; - if ( fn.live === event.type || - fn.altLive && jQuery.inArray(event.type, fn.altLive) > -1 ) { - - data = fn.data; - if ( !(data.beforeFilter && data.beforeFilter[event.type] && - !data.beforeFilter[event.type](event)) ) { - selectors.push( fn.selector ); - } - } else { - delete live[j]; - } - } - - match = jQuery( event.target ).closest( selectors, event.currentTarget ); - - for ( i = 0, l = match.length; i < l; i++ ) { - for ( j in live ) { - fn = live[j]; - elem = match[i].elem; - related = null; - - if ( match[i].selector === fn.selector ) { - // Those two events require additional checking - if ( fn.live === "mouseenter" || fn.live === "mouseleave" ) { - related = jQuery( event.relatedTarget ).closest( fn.selector )[0]; - } - - if ( !related || related !== elem ) { - elems.push({ elem: elem, fn: fn }); - } - } - } - } - - for ( i = 0, l = elems.length; i < l; i++ ) { - match = elems[i]; - event.currentTarget = match.elem; - event.data = match.fn.data; - if ( match.fn.apply( match.elem, args ) === false ) { - stop = false; - break; - } - } - - return stop; -} - -function liveConvert( type, selector ) { - return "live." + (type ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&"); -} - -// jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + -// "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + -// "change select submit keydown keypress keyup error").split(" "), function( i, name ) { -// -// // Handle event binding -// jQuery.fn[ name ] = function( fn ) { -// return fn ? this.bind( name, fn ) : this.trigger( name ); -// }; -// -// if ( jQuery.attrFn ) { -// jQuery.attrFn[ name ] = true; -// } -// }); - -jQuery.fn[ "blur" ] = function( fn ) { - /// - /// 1: blur() - Triggers the blur event of each matched element. - /// 2: blur(fn) - Binds a function to the blur event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "blur", fn ) : this.trigger( "blur" ); -}; - -jQuery.fn[ "focus" ] = function( fn ) { - /// - /// 1: focus() - Triggers the focus event of each matched element. - /// 2: focus(fn) - Binds a function to the focus event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "focus", fn ) : this.trigger( "focus" ); -}; - -jQuery.fn[ "focusin" ] = function( fn ) { - /// - /// Bind an event handler to the "focusin" JavaScript event. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return fn ? this.bind( "focusin", fn ) : this.trigger( "focusin" ); -}; - -jQuery.fn[ "focusout" ] = function( fn ) { - /// - /// Bind an event handler to the "focusout" JavaScript event. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return fn ? this.bind( "focusout", fn ) : this.trigger( "focusout" ); -}; - -jQuery.fn[ "load" ] = function( fn ) { - /// - /// 1: load() - Triggers the load event of each matched element. - /// 2: load(fn) - Binds a function to the load event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "load", fn ) : this.trigger( "load" ); -}; - -jQuery.fn[ "resize" ] = function( fn ) { - /// - /// 1: resize() - Triggers the resize event of each matched element. - /// 2: resize(fn) - Binds a function to the resize event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "resize", fn ) : this.trigger( "resize" ); -}; - -jQuery.fn[ "scroll" ] = function( fn ) { - /// - /// 1: scroll() - Triggers the scroll event of each matched element. - /// 2: scroll(fn) - Binds a function to the scroll event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "scroll", fn ) : this.trigger( "scroll" ); -}; - -jQuery.fn[ "unload" ] = function( fn ) { - /// - /// 1: unload() - Triggers the unload event of each matched element. - /// 2: unload(fn) - Binds a function to the unload event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "unload", fn ) : this.trigger( "unload" ); -}; - -jQuery.fn[ "click" ] = function( fn ) { - /// - /// 1: click() - Triggers the click event of each matched element. - /// 2: click(fn) - Binds a function to the click event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "click", fn ) : this.trigger( "click" ); -}; - -jQuery.fn[ "dblclick" ] = function( fn ) { - /// - /// 1: dblclick() - Triggers the dblclick event of each matched element. - /// 2: dblclick(fn) - Binds a function to the dblclick event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "dblclick", fn ) : this.trigger( "dblclick" ); -}; - -jQuery.fn[ "mousedown" ] = function( fn ) { - /// - /// Binds a function to the mousedown event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "mousedown", fn ) : this.trigger( "mousedown" ); -}; - -jQuery.fn[ "mouseup" ] = function( fn ) { - /// - /// Bind a function to the mouseup event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "mouseup", fn ) : this.trigger( "mouseup" ); -}; - -jQuery.fn[ "mousemove" ] = function( fn ) { - /// - /// Bind a function to the mousemove event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "mousemove", fn ) : this.trigger( "mousemove" ); -}; - -jQuery.fn[ "mouseover" ] = function( fn ) { - /// - /// Bind a function to the mouseover event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "mouseover", fn ) : this.trigger( "mouseover" ); -}; - -jQuery.fn[ "mouseout" ] = function( fn ) { - /// - /// Bind a function to the mouseout event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "mouseout", fn ) : this.trigger( "mouseout" ); -}; - -jQuery.fn[ "mouseenter" ] = function( fn ) { - /// - /// Bind a function to the mouseenter event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "mouseenter", fn ) : this.trigger( "mouseenter" ); -}; - -jQuery.fn[ "mouseleave" ] = function( fn ) { - /// - /// Bind a function to the mouseleave event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "mouseleave", fn ) : this.trigger( "mouseleave" ); -}; - -jQuery.fn[ "change" ] = function( fn ) { - /// - /// 1: change() - Triggers the change event of each matched element. - /// 2: change(fn) - Binds a function to the change event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "change", fn ) : this.trigger( "change" ); -}; - -jQuery.fn[ "select" ] = function( fn ) { - /// - /// 1: select() - Triggers the select event of each matched element. - /// 2: select(fn) - Binds a function to the select event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "select", fn ) : this.trigger( "select" ); -}; - -jQuery.fn[ "submit" ] = function( fn ) { - /// - /// 1: submit() - Triggers the submit event of each matched element. - /// 2: submit(fn) - Binds a function to the submit event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "submit", fn ) : this.trigger( "submit" ); -}; - -jQuery.fn[ "keydown" ] = function( fn ) { - /// - /// 1: keydown() - Triggers the keydown event of each matched element. - /// 2: keydown(fn) - Binds a function to the keydown event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "keydown", fn ) : this.trigger( "keydown" ); -}; - -jQuery.fn[ "keypress" ] = function( fn ) { - /// - /// 1: keypress() - Triggers the keypress event of each matched element. - /// 2: keypress(fn) - Binds a function to the keypress event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "keypress", fn ) : this.trigger( "keypress" ); -}; - -jQuery.fn[ "keyup" ] = function( fn ) { - /// - /// 1: keyup() - Triggers the keyup event of each matched element. - /// 2: keyup(fn) - Binds a function to the keyup event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "keyup", fn ) : this.trigger( "keyup" ); -}; - -jQuery.fn[ "error" ] = function( fn ) { - /// - /// 1: error() - Triggers the error event of each matched element. - /// 2: error(fn) - Binds a function to the error event of each matched element. - /// - /// The function to execute. - /// - - return fn ? this.bind( "error", fn ) : this.trigger( "error" ); -}; - -// Prevent memory leaks in IE -// Window isn't included so as not to unbind existing unload events -// More info: -// - http://isaacschlueter.com/2006/10/msie-memory-leaks/ -if ( window.attachEvent && !window.addEventListener ) { - window.attachEvent("onunload", function() { - for ( var id in jQuery.cache ) { - if ( jQuery.cache[ id ].handle ) { - // Try/Catch is to handle iframes being unloaded, see #4280 - try { - jQuery.event.remove( jQuery.cache[ id ].handle.elem ); - } catch(e) {} - } - } - }); -} -/*! - * Sizzle CSS Selector Engine - v1.0 - * Copyright 2009, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ - -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true; - -// Here we check if the JavaScript engine is using some sort of -// optimization where it does not always call our comparision -// function. If that is the case, discard the hasDuplicate value. -// Thus far that includes Google Chrome. -[0, 0].sort(function(){ - baseHasDuplicate = false; - return 0; -}); - -var Sizzle = function(selector, context, results, seed) { - results = results || []; - var origContext = context = context || document; - - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - var parts = [], m, set, checkSet, extra, prune = true, contextXML = isXML(context), - soFar = selector; - - // Reset the position of the chunker regexp (start from head) - while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { - soFar = m[3]; - - parts.push( m[1] ); - - if ( m[2] ) { - extra = m[3]; - break; - } - } - - if ( parts.length > 1 && origPOS.exec( selector ) ) { - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context ); - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); - - while ( parts.length ) { - selector = parts.shift(); - - if ( Expr.relative[ selector ] ) { - selector += parts.shift(); - } - - set = posProcess( selector, set ); - } - } - } else { - // Take a shortcut and set the context if the root selector is an ID - // (but not if it'll be faster if the inner selector is an ID) - if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { - var ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; - } - - if ( context ) { - var ret = seed ? - { expr: parts.pop(), set: makeArray(seed) } : - Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; - - if ( parts.length > 0 ) { - checkSet = makeArray(set); - } else { - prune = false; - } - - while ( parts.length ) { - var cur = parts.pop(), pop = cur; - - if ( !Expr.relative[ cur ] ) { - cur = ""; - } else { - pop = parts.pop(); - } - - if ( pop == null ) { - pop = context; - } - - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } - } else { - checkSet = parts = []; - } - } - - if ( !checkSet ) { - checkSet = set; - } - - if ( !checkSet ) { - Sizzle.error( cur || selector ); - } - - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); - } else if ( context && context.nodeType === 1 ) { - for ( var i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { - results.push( set[i] ); - } - } - } else { - for ( var i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } - } - } - } else { - makeArray( checkSet, results ); - } - - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } - - return results; -}; - -Sizzle.uniqueSort = function(results){ - /// - /// Removes all duplicate elements from an array of elements. - /// - /// The array to translate - /// The array after translation. - - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort(sortOrder); - - if ( hasDuplicate ) { - for ( var i = 1; i < results.length; i++ ) { - if ( results[i] === results[i-1] ) { - results.splice(i--, 1); - } - } - } - } - - return results; -}; - -Sizzle.matches = function(expr, set){ - return Sizzle(expr, null, null, set); -}; - -Sizzle.find = function(expr, context, isXML){ - var set, match; - - if ( !expr ) { - return []; - } - - for ( var i = 0, l = Expr.order.length; i < l; i++ ) { - var type = Expr.order[i], match; - - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - var left = match[1]; - match.splice(1,1); - - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace(/\\/g, ""); - set = Expr.find[ type ]( match, context, isXML ); - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; - } - } - } - } - - if ( !set ) { - set = context.getElementsByTagName("*"); - } - - return {set: set, expr: expr}; -}; - -Sizzle.filter = function(expr, set, inplace, not){ - var old = expr, result = [], curLoop = set, match, anyFound, - isXMLFilter = set && set[0] && isXML(set[0]); - - while ( expr && set.length ) { - for ( var type in Expr.filter ) { - if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { - var filter = Expr.filter[ type ], found, item, left = match[1]; - anyFound = false; - - match.splice(1,1); - - if ( left.substr( left.length - 1 ) === "\\" ) { - continue; - } - - if ( curLoop === result ) { - result = []; - } - - if ( Expr.preFilter[ type ] ) { - match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); - - if ( !match ) { - anyFound = found = true; - } else if ( match === true ) { - continue; - } - } - - if ( match ) { - for ( var i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - var pass = not ^ !!found; - - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; - } else { - curLoop[i] = false; - } - } else if ( pass ) { - result.push( item ); - anyFound = true; - } - } - } - } - - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } - - expr = expr.replace( Expr.match[ type ], "" ); - - if ( !anyFound ) { - return []; - } - - break; - } - } - } - - // Improper expression - if ( expr === old ) { - if ( anyFound == null ) { - Sizzle.error( expr ); - } else { - break; - } - } - - old = expr; - } - - return curLoop; -}; - -Sizzle.error = function( msg ) { - throw "Syntax error, unrecognized expression: " + msg; -}; - -var Expr = Sizzle.selectors = { - order: [ "ID", "NAME", "TAG" ], - match: { - ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ - }, - leftMatch: {}, - attrMap: { - "class": "className", - "for": "htmlFor" - }, - attrHandle: { - href: function(elem){ - return elem.getAttribute("href"); - } - }, - relative: { - "+": function(checkSet, part){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !/\W/.test(part), - isPartStrNotTag = isPartStr && !isTag; - - if ( isTag ) { - part = part.toLowerCase(); - } - - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; - } - } - - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, - ">": function(checkSet, part){ - var isPartStr = typeof part === "string"; - - if ( isPartStr && !/\W/.test(part) ) { - part = part.toLowerCase(); - - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } - } else { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, - "": function(checkSet, part, isXML){ - var doneName = done++, checkFn = dirCheck; - - if ( typeof part === "string" && !/\W/.test(part) ) { - var nodeCheck = part = part.toLowerCase(); - checkFn = dirNodeCheck; - } - - checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); - }, - "~": function(checkSet, part, isXML){ - var doneName = done++, checkFn = dirCheck; - - if ( typeof part === "string" && !/\W/.test(part) ) { - var nodeCheck = part = part.toLowerCase(); - checkFn = dirNodeCheck; - } - - checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); - } - }, - find: { - ID: function(match, context, isXML){ - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - return m ? [m] : []; - } - }, - NAME: function(match, context){ - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], results = context.getElementsByName(match[1]); - - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } - - return ret.length === 0 ? null : ret; - } - }, - TAG: function(match, context){ - return context.getElementsByTagName(match[1]); - } - }, - preFilter: { - CLASS: function(match, curLoop, inplace, result, not, isXML){ - match = " " + match[1].replace(/\\/g, "") + " "; - - if ( isXML ) { - return match; - } - - for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { - if ( elem ) { - if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { - if ( !inplace ) { - result.push( elem ); - } - } else if ( inplace ) { - curLoop[i] = false; - } - } - } - - return false; - }, - ID: function(match){ - return match[1].replace(/\\/g, ""); - }, - TAG: function(match, curLoop){ - return match[1].toLowerCase(); - }, - CHILD: function(match){ - if ( match[1] === "nth" ) { - // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' - var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( - match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || - !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); - - // calculate the numbers (first)n+(last) including if they are negative - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - - // TODO: Move to normal caching system - match[0] = done++; - - return match; - }, - ATTR: function(match, curLoop, inplace, result, not, isXML){ - var name = match[1].replace(/\\/g, ""); - - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } - - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } - - return match; - }, - PSEUDO: function(match, curLoop, inplace, result, not){ - if ( match[1] === "not" ) { - // If we're dealing with a complex expression, or a simple one - if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { - match[3] = Sizzle(match[3], null, null, curLoop); - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); - if ( !inplace ) { - result.push.apply( result, ret ); - } - return false; - } - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; - } - - return match; - }, - POS: function(match){ - match.unshift( true ); - return match; - } - }, - filters: { - enabled: function(elem){ - return elem.disabled === false && elem.type !== "hidden"; - }, - disabled: function(elem){ - return elem.disabled === true; - }, - checked: function(elem){ - return elem.checked === true; - }, - selected: function(elem){ - // Accessing this property makes selected-by-default - // options in Safari work properly - elem.parentNode.selectedIndex; - return elem.selected === true; - }, - parent: function(elem){ - return !!elem.firstChild; - }, - empty: function(elem){ - return !elem.firstChild; - }, - has: function(elem, i, match){ - /// - /// Internal use only; use hasClass('class') - /// - /// - - return !!Sizzle( match[3], elem ).length; - }, - header: function(elem){ - return /h\d/i.test( elem.nodeName ); - }, - text: function(elem){ - return "text" === elem.type; - }, - radio: function(elem){ - return "radio" === elem.type; - }, - checkbox: function(elem){ - return "checkbox" === elem.type; - }, - file: function(elem){ - return "file" === elem.type; - }, - password: function(elem){ - return "password" === elem.type; - }, - submit: function(elem){ - return "submit" === elem.type; - }, - image: function(elem){ - return "image" === elem.type; - }, - reset: function(elem){ - return "reset" === elem.type; - }, - button: function(elem){ - return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; - }, - input: function(elem){ - return /input|select|textarea|button/i.test(elem.nodeName); - } - }, - setFilters: { - first: function(elem, i){ - return i === 0; - }, - last: function(elem, i, match, array){ - return i === array.length - 1; - }, - even: function(elem, i){ - return i % 2 === 0; - }, - odd: function(elem, i){ - return i % 2 === 1; - }, - lt: function(elem, i, match){ - return i < match[3] - 0; - }, - gt: function(elem, i, match){ - return i > match[3] - 0; - }, - nth: function(elem, i, match){ - return match[3] - 0 === i; - }, - eq: function(elem, i, match){ - return match[3] - 0 === i; - } - }, - filter: { - PSEUDO: function(elem, match, i, array){ - var name = match[1], filter = Expr.filters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; - } else if ( name === "not" ) { - var not = match[3]; - - for ( var i = 0, l = not.length; i < l; i++ ) { - if ( not[i] === elem ) { - return false; - } - } - - return true; - } else { - Sizzle.error( "Syntax error, unrecognized expression: " + name ); - } - }, - CHILD: function(elem, match){ - var type = match[1], node = elem; - switch (type) { - case 'only': - case 'first': - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - if ( type === "first" ) { - return true; - } - node = elem; - case 'last': - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - return true; - case 'nth': - var first = match[2], last = match[3]; - - if ( first === 1 && last === 0 ) { - return true; - } - - var doneName = match[0], - parent = elem.parentNode; - - if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { - var count = 0; - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; - } - } - parent.sizcache = doneName; - } - - var diff = elem.nodeIndex - last; - if ( first === 0 ) { - return diff === 0; - } else { - return ( diff % first === 0 && diff / first >= 0 ); - } - } - }, - ID: function(elem, match){ - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, - TAG: function(elem, match){ - return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; - }, - CLASS: function(elem, match){ - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; - }, - ATTR: function(elem, match){ - var name = match[1], - result = Expr.attrHandle[ name ] ? - Expr.attrHandle[ name ]( elem ) : - elem[ name ] != null ? - elem[ name ] : - elem.getAttribute( name ), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value !== check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - POS: function(elem, match, i, array){ - var name = match[2], filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } - } - } -}; - -var origPOS = Expr.match.POS; - -for ( var type in Expr.match ) { - Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); - Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, function(all, num){ - return "\\" + (num - 0 + 1); - })); -} - -var makeArray = function(array, results) { - array = Array.prototype.slice.call( array, 0 ); - - if ( results ) { - results.push.apply( results, array ); - return results; - } - - return array; -}; - -// Perform a simple check to determine if the browser is capable of -// converting a NodeList to an array using builtin methods. -try { - Array.prototype.slice.call( document.documentElement.childNodes, 0 ); - -// Provide a fallback method if it does not work -} catch(e){ - makeArray = function(array, results) { - var ret = results || []; - - if ( toString.call(array) === "[object Array]" ) { - Array.prototype.push.apply( ret, array ); - } else { - if ( typeof array.length === "number" ) { - for ( var i = 0, l = array.length; i < l; i++ ) { - ret.push( array[i] ); - } - } else { - for ( var i = 0; array[i]; i++ ) { - ret.push( array[i] ); - } - } - } - - return ret; - }; -} - -var sortOrder; - -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - if ( a == b ) { - hasDuplicate = true; - } - return a.compareDocumentPosition ? -1 : 1; - } - - var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; - if ( ret === 0 ) { - hasDuplicate = true; - } - return ret; - }; -} else if ( "sourceIndex" in document.documentElement ) { - sortOrder = function( a, b ) { - if ( !a.sourceIndex || !b.sourceIndex ) { - if ( a == b ) { - hasDuplicate = true; - } - return a.sourceIndex ? -1 : 1; - } - - var ret = a.sourceIndex - b.sourceIndex; - if ( ret === 0 ) { - hasDuplicate = true; - } - return ret; - }; -} else if ( document.createRange ) { - sortOrder = function( a, b ) { - if ( !a.ownerDocument || !b.ownerDocument ) { - if ( a == b ) { - hasDuplicate = true; - } - return a.ownerDocument ? -1 : 1; - } - - var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); - aRange.setStart(a, 0); - aRange.setEnd(a, 0); - bRange.setStart(b, 0); - bRange.setEnd(b, 0); - var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); - if ( ret === 0 ) { - hasDuplicate = true; - } - return ret; - }; -} - -// Utility function for retreiving the text value of an array of DOM nodes -function getText( elems ) { - var ret = "", elem; - - for ( var i = 0; elems[i]; i++ ) { - elem = elems[i]; - - // Get the text from text nodes and CDATA nodes - if ( elem.nodeType === 3 || elem.nodeType === 4 ) { - ret += elem.nodeValue; - - // Traverse everything else, except comment nodes - } else if ( elem.nodeType !== 8 ) { - ret += getText( elem.childNodes ); - } - } - - return ret; -} - -// [vsdoc] The following function has been modified for IntelliSense. -// Check to see if the browser returns elements by name when -// querying by getElementById (and provide a workaround) -(function(){ - // We're going to inject a fake input element with a specified name - // var form = document.createElement("div"), - // id = "script" + (new Date).getTime(); - // form.innerHTML = ""; - - // // Inject it into the root element, check its status, and remove it quickly - // var root = document.documentElement; - // root.insertBefore( form, root.firstChild ); - - // The workaround has to do additional checks after a getElementById - // Which slows things down for other browsers (hence the branching) - // if ( document.getElementById( id ) ) { - Expr.find.ID = function(match, context, isXML){ - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; - } - }; - - Expr.filter.ID = function(elem, match){ - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - // } - - // root.removeChild( form ); - root = form = null; // release memory in IE -})(); - -// [vsdoc] The following function has been modified for IntelliSense. -(function(){ - // Check to see if the browser returns only elements - // when doing getElementsByTagName("*") - - // Create a fake element - // var div = document.createElement("div"); - // div.appendChild( document.createComment("") ); - - // Make sure no comments are found - // if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function(match, context){ - var results = context.getElementsByTagName(match[1]); - - // Filter out possible comments - if ( match[1] === "*" ) { - var tmp = []; - - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); - } - } - - results = tmp; - } - - return results; - }; - // } - - // Check to see if an attribute returns normalized href attributes - // div.innerHTML = ""; - // if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - // div.firstChild.getAttribute("href") !== "#" ) { - Expr.attrHandle.href = function(elem){ - return elem.getAttribute("href", 2); - }; - // } - - div = null; // release memory in IE -})(); - -if ( document.querySelectorAll ) { - (function(){ - var oldSizzle = Sizzle, div = document.createElement("div"); - div.innerHTML = "

"; - - // Safari can't handle uppercase or unicode characters when - // in quirks mode. - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; - } - - Sizzle = function(query, context, extra, seed){ - context = context || document; - - // Only use querySelectorAll on non-XML documents - // (ID selectors don't work in non-HTML documents) - if ( !seed && context.nodeType === 9 && !isXML(context) ) { - try { - return makeArray( context.querySelectorAll(query), extra ); - } catch(e){} - } - - return oldSizzle(query, context, extra, seed); - }; - - for ( var prop in oldSizzle ) { - Sizzle[ prop ] = oldSizzle[ prop ]; - } - - div = null; // release memory in IE - })(); -} - -(function(){ - var div = document.createElement("div"); - - div.innerHTML = "
"; - - // Opera can't find a second classname (in 9.6) - // Also, make sure that getElementsByClassName actually exists - if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { - return; - } - - // Safari caches class attributes, doesn't catch changes (in 3.2) - div.lastChild.className = "e"; - - if ( div.getElementsByClassName("e").length === 1 ) { - return; - } - - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function(match, context, isXML) { - if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { - return context.getElementsByClassName(match[1]); - } - }; - - div = null; // release memory in IE -})(); - -function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - if ( elem ) { - elem = elem[dir]; - var match = false; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem.sizcache = doneName; - elem.sizset = i; - } - - if ( elem.nodeName.toLowerCase() === cur ) { - match = elem; - break; - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - if ( elem ) { - elem = elem[dir]; - var match = false; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem.sizcache = doneName; - elem.sizset = i; - } - if ( typeof cur !== "string" ) { - if ( elem === cur ) { - match = true; - break; - } - - } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { - match = elem; - break; - } - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -var contains = document.compareDocumentPosition ? function(a, b){ - /// - /// Check to see if a DOM node is within another DOM node. - /// - /// - /// The DOM element that may contain the other element. - /// - /// - /// The DOM node that may be contained by the other element. - /// - /// - - return a.compareDocumentPosition(b) & 16; -} : function(a, b){ - /// - /// Check to see if a DOM node is within another DOM node. - /// - /// - /// The DOM element that may contain the other element. - /// - /// - /// The DOM node that may be contained by the other element. - /// - /// - - return a !== b && (a.contains ? a.contains(b) : true); -}; - -var isXML = function(elem){ - /// - /// Determines if the parameter passed is an XML document. - /// - /// The object to test - /// True if the parameter is an XML document; otherwise false. - - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -var posProcess = function(selector, context){ - var tmpSet = [], later = "", match, - root = context.nodeType ? [context] : context; - - // Position selectors must be done after the filter - // And so must :not(positional) so we move all PSEUDOs to the end - while ( (match = Expr.match.PSEUDO.exec( selector )) ) { - later += match[0]; - selector = selector.replace( Expr.match.PSEUDO, "" ); - } - - selector = Expr.relative[selector] ? selector + "*" : selector; - - for ( var i = 0, l = root.length; i < l; i++ ) { - Sizzle( selector, root[i], tmpSet ); - } - - return Sizzle.filter( later, tmpSet ); -}; - -// EXPOSE -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.filters; -jQuery.unique = Sizzle.uniqueSort; -jQuery.getText = getText; -jQuery.isXMLDoc = isXML; -jQuery.contains = contains; - -return; - -window.Sizzle = Sizzle; - -})(); -var runtil = /Until$/, - rparentsprev = /^(?:parents|prevUntil|prevAll)/, - // Note: This RegExp should be improved, or likely pulled from Sizzle - rmultiselector = /,/, - slice = Array.prototype.slice; - -// Implement the identical functionality for filter and not -var winnow = function( elements, qualifier, keep ) { - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - return !!qualifier.call( elem, i, elem ) === keep; - }); - - } else if ( qualifier.nodeType ) { - return jQuery.grep(elements, function( elem, i ) { - return (elem === qualifier) === keep; - }); - - } else if ( typeof qualifier === "string" ) { - var filtered = jQuery.grep(elements, function( elem ) { - return elem.nodeType === 1; - }); - - if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); - } - } - - return jQuery.grep(elements, function( elem, i ) { - return (jQuery.inArray( elem, qualifier ) >= 0) === keep; - }); -}; - -jQuery.fn.extend({ - find: function( selector ) { - /// - /// Searches for all elements that match the specified expression. - /// This method is a good way to find additional descendant - /// elements with which to process. - /// All searching is done using a jQuery expression. The expression can be - /// written using CSS 1-3 Selector syntax, or basic XPath. - /// Part of DOM/Traversing - /// - /// - /// - /// An expression to search with. - /// - /// - - var ret = this.pushStack( "", "find", selector ), length = 0; - - for ( var i = 0, l = this.length; i < l; i++ ) { - length = ret.length; - jQuery.find( selector, this[i], ret ); - - if ( i > 0 ) { - // Make sure that the results are unique - for ( var n = length; n < ret.length; n++ ) { - for ( var r = 0; r < length; r++ ) { - if ( ret[r] === ret[n] ) { - ret.splice(n--, 1); - break; - } - } - } - } - } - - return ret; - }, - - has: function( target ) { - /// - /// Reduce the set of matched elements to those that have a descendant that matches the - /// selector or DOM element. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var targets = jQuery( target ); - return this.filter(function() { - for ( var i = 0, l = targets.length; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - not: function( selector ) { - /// - /// Removes any elements inside the array of elements from the set - /// of matched elements. This method is used to remove one or more - /// elements from a jQuery object. - /// Part of DOM/Traversing - /// - /// - /// A set of elements to remove from the jQuery set of matched elements. - /// - /// - - return this.pushStack( winnow(this, selector, false), "not", selector); - }, - - filter: function( selector ) { - /// - /// Removes all elements from the set of matched elements that do not - /// pass the specified filter. This method is used to narrow down - /// the results of a search. - /// }) - /// Part of DOM/Traversing - /// - /// - /// - /// A function to use for filtering - /// - /// - - return this.pushStack( winnow(this, selector, true), "filter", selector ); - }, - - is: function( selector ) { - /// - /// Checks the current selection against an expression and returns true, - /// if at least one element of the selection fits the given expression. - /// Does return false, if no element fits or the expression is not valid. - /// filter(String) is used internally, therefore all rules that apply there - /// apply here, too. - /// Part of DOM/Traversing - /// - /// - /// - /// The expression with which to filter - /// - - return !!selector && jQuery.filter( selector, this ).length > 0; - }, - - closest: function( selectors, context ) { - /// - /// Get a set of elements containing the closest parent element that matches the specified selector, the starting element included. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - /// A DOM element within which a matching element may be found. If no context is passed - /// in then the context of the jQuery set will be used instead. - /// - /// - - if ( jQuery.isArray( selectors ) ) { - var ret = [], cur = this[0], match, matches = {}, selector; - - if ( cur && selectors.length ) { - for ( var i = 0, l = selectors.length; i < l; i++ ) { - selector = selectors[i]; - - if ( !matches[selector] ) { - matches[selector] = jQuery.expr.match.POS.test( selector ) ? - jQuery( selector, context || this.context ) : - selector; - } - } - - while ( cur && cur.ownerDocument && cur !== context ) { - for ( selector in matches ) { - match = matches[selector]; - - if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { - ret.push({ selector: selector, elem: cur }); - delete matches[selector]; - } - } - cur = cur.parentNode; - } - } - - return ret; - } - - var pos = jQuery.expr.match.POS.test( selectors ) ? - jQuery( selectors, context || this.context ) : null; - - return this.map(function( i, cur ) { - while ( cur && cur.ownerDocument && cur !== context ) { - if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) { - return cur; - } - cur = cur.parentNode; - } - return null; - }); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - /// - /// Searches every matched element for the object and returns - /// the index of the element, if found, starting with zero. - /// Returns -1 if the object wasn't found. - /// Part of Core - /// - /// - /// - /// Object to search for - /// - - if ( !elem || typeof elem === "string" ) { - return jQuery.inArray( this[0], - // If it receives a string, the selector is used - // If it receives nothing, the siblings are used - elem ? jQuery( elem ) : this.parent().children() ); - } - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - /// - /// Adds one or more Elements to the set of matched elements. - /// Part of DOM/Traversing - /// - /// - /// A string containing a selector expression to match additional elements against. - /// - /// - /// Add some elements rooted against the specified context. - /// - /// - - var set = typeof selector === "string" ? - jQuery( selector, context || this.context ) : - jQuery.makeArray( selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? - all : - jQuery.unique( all ) ); - }, - - andSelf: function() { - /// - /// Adds the previous selection to the current selection. - /// - /// - - return this.add( this.prevObject ); - } -}); - -// A painfully simple check to see if an element is disconnected -// from a document (should be improved, where feasible). -function isDisconnected( node ) { - return !node || !node.parentNode || node.parentNode.nodeType === 11; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - next: function( elem ) { - return jQuery.nth( elem, 2, "nextSibling" ); - }, - prev: function( elem ) { - return jQuery.nth( elem, 2, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - siblings: function( elem ) { - return jQuery.sibling( elem.parentNode.firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.makeArray( elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ); - - if ( !runtil.test( name ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, name, slice.call(arguments).join(",") ); - }; -}); - -jQuery.fn[ "parentsUntil" ] = function( until, selector ) { - /// - /// Get the ancestors of each element in the current set of matched elements, up to but not - /// including the element matched by the selector. - /// - /// - /// A string containing a selector expression to indicate where to stop matching ancestor - /// elements. - /// - /// - - var fn = function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - } - - var ret = jQuery.map( this, fn, until ); - - if ( !runtil.test( "parentsUntil" ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( "parentsUntil" ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, "parentsUntil", slice.call(arguments).join(",") ); -}; - -jQuery.fn[ "nextUntil" ] = function( until, selector ) { - /// - /// Get all following siblings of each element up to but not including the element matched - /// by the selector. - /// - /// - /// A string containing a selector expression to indicate where to stop matching following - /// sibling elements. - /// - /// - - var fn = function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - } - - var ret = jQuery.map( this, fn, until ); - - if ( !runtil.test( "nextUntil" ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( "nextUntil" ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, "nextUntil", slice.call(arguments).join(",") ); -}; - -jQuery.fn[ "prevUntil" ] = function( until, selector ) { - /// - /// Get all preceding siblings of each element up to but not including the element matched - /// by the selector. - /// - /// - /// A string containing a selector expression to indicate where to stop matching preceding - /// sibling elements. - /// - /// - - var fn = function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - } - - var ret = jQuery.map( this, fn, until ); - - if ( !runtil.test( "prevUntil" ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( "prevUntil" ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, "prevUntil", slice.call(arguments).join(",") ); -}; - -jQuery.extend({ - filter: function( expr, elems, not ) { - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return jQuery.find.matches(expr, elems); - }, - - dir: function( elem, dir, until ) { - /// - /// This member is internal only. - /// - /// - - var matched = [], cur = elem[dir]; - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; - } - return matched; - }, - - nth: function( cur, result, dir, elem ) { - /// - /// This member is internal only. - /// - /// - - result = result || 1; - var num = 0; - - for ( ; cur; cur = cur[dir] ) { - if ( cur.nodeType === 1 && ++num === result ) { - break; - } - } - - return cur; - }, - - sibling: function( n, elem ) { - /// - /// This member is internal only. - /// - /// - - var r = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } - } - - return r; - } -}); -var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, - rleadingWhitespace = /^\s+/, - rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g, - rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i, - rtagName = /<([\w:]+)/, - rtbody = /"; - }, - wrapMap = { - option: [ 1, "" ], - legend: [ 1, "
", "
" ], - thead: [ 1, "", "
" ], - tr: [ 2, "", "
" ], - td: [ 3, "", "
" ], - col: [ 2, "", "
" ], - area: [ 1, "", "" ], - _default: [ 0, "", "" ] - }; - -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// IE can't serialize and - - - -

Log On

- <%: Html.ValidationSummary("Login was unsuccessful. Please correct the errors and try again.") %> - - -
-

via 3rd Party (recommended)

- - <% Html.RenderPartial("LogOnContent"); %> - -
-
OR
-
-

using a NerdDinner account

- - <% using (Html.BeginForm()) { %> -
-

- - <%: Html.TextBox("username") %> - <%: Html.ValidationMessage("username", "*") %> -

-

- - <%: Html.Password("password") %> - <%: Html.ValidationMessage("password", "*")%> -

-

- <%: Html.CheckBox("rememberMe") %> -

-

- -

-

- Please enter your username and password. <%: Html.ActionLink("Register", "Register") %> if you don't have an account. -

-
-
- <% } %> - - <% var options = new OpenIdSelector(); - options.TextBox.LogOnText = "Log On"; %> - - <%= Html.OpenIdSelectorScripts(this.Page, options, null)%> - -
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Account/Register.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Account/Register.aspx deleted file mode 100644 index e8fbcfd..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Account/Register.aspx +++ /dev/null @@ -1,52 +0,0 @@ -<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - - - Register - - - - - - - -

Create a New Account

-

- Use the form below to create a new account. -

-

- Passwords are required to be a minimum of <%:ViewData["PasswordLength"]%> characters in length. -

- <%: Html.ValidationSummary() %> - <% Html.EnableClientValidation(); %> - - <% using (Html.BeginForm()) { %> -
-
- Account Information -

- - <%: Html.TextBox("username") %> - <%: Html.ValidationMessage("username") %> -

-

- - <%: Html.TextBox("email") %> - <%: Html.ValidationMessage("email") %> -

-

- - <%: Html.Password("password") %> - <%: Html.ValidationMessage("password") %> -

-

- - <%: Html.Password("confirmPassword") %> - <%: Html.ValidationMessage("confirmPassword") %> -

-

- -

-
-
- <% } %> -
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Create.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Create.aspx deleted file mode 100644 index 6464459..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Create.aspx +++ /dev/null @@ -1,14 +0,0 @@ -<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" MasterPageFile="~/Views/Shared/Site.Master" %> - - - Host a Nerd Dinner - - - - -

Host a Dinner

- - <% Html.RenderPartial("DinnerForm"); %> - -
- diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Delete.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Delete.aspx deleted file mode 100644 index b0d39dd..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Delete.aspx +++ /dev/null @@ -1,24 +0,0 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - - - Delete Confirmation: <%:Model.Title %> - - - - -

- Delete Confirmation -

- -
-

Please confirm you want to cancel the dinner titled: - <%:Model.Title %>?

-
- - <% using (Html.BeginForm()) { %> - - - - <% } %> - -
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Deleted.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Deleted.aspx deleted file mode 100644 index dbdcad7..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Deleted.aspx +++ /dev/null @@ -1,19 +0,0 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - - - Deleted - - - - -

Dinner Deleted

- -
-

Your dinner was successfully deleted.

-
- - - -
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Details.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Details.aspx deleted file mode 100644 index 7653e7f..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Details.aspx +++ /dev/null @@ -1,122 +0,0 @@ -<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" MasterPageFile="~/Views/Shared/Site.Master" %> -<%@ Import Namespace="NerdDinner.Helpers" %> - - <%: Model.Title %> - - - - -
- -

<%: Model.Title %>

- - - - -

- <%: Html.ActionLink("Add event to your calendar:", "iCal", "Services", new { id = Model.DinnerId }, null) %> - "> -

- -

- When: - "> - <%: Model.EventDate.ToString("MMM dd, yyyy") %> - @ - <%: Model.EventDate.ToShortTimeString() %> - -

- -

- Where: - - <%: Model.Address %>, - <%: Model.Country %> - - -

- -

- Description: - <%: Model.Description %> - - <%: Html.ActionLink("URL for hCalendar", "iCal", "Services", new { id = Model.DinnerId }, new { @class = "url" })%> - -

- -

- Organizer: - - - <%: Model.HostedBy %> - <%: Model.ContactPhone %> - - -

- - <% Html.RenderPartial("RSVPStatus"); %> - -

- Who's Coming: - <%if (Model.GetRsvpCount() == 0){%> - No one has registered. - <% } %> -

- - <%if(Model.GetRsvpCount() > 0) {%> -
-
    - <% - var rsvps = Model.GetRsvps().Reverse(); - foreach (var rsvp in rsvps) - {%> -
  • - - <%:rsvp.AttendeeName.StartsWith("@") ? rsvp.AttendeeName : rsvp.AttendeeName.Replace("@", " at ").Truncate(30)%> - -
  • - <% } %> -
-
- <%} %> - - <% Html.RenderPartial("EditAndDeleteLinks"); %> - -
- -
- <% Html.RenderPartial("map"); %> -

- hCalendar -

-
- -
- - - -blog comments powered by Disqus - - -
- diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/DinnerForm.ascx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/DinnerForm.ascx deleted file mode 100644 index a96ea32..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/DinnerForm.ascx +++ /dev/null @@ -1,78 +0,0 @@ -<%@ Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> -<%@ Import Namespace="NerdDinner.Helpers" %> - - - - - -<% Html.EnableClientValidation(); %> -<%: Html.ValidationSummary("Please correct the errors and try again.") %> - -<% using (Html.BeginForm()) { %> -
- -
- -

- - <%: Html.EditorFor(m => Model.Title) %> -

-

- - <%: Html.EditorFor(m => m.EventDate) %> -

-

- - <%: Html.TextAreaFor(m => Model.Description, 6, 35, null) %> -

-

- - <%: Html.EditorFor(m => Model.Address)%> -

-

- - <%: Html.DropDownListFor(m => Model.Country, new SelectList(PhoneValidator.Countries, Model.Country))%> -

-

- - <%: Html.EditorFor(m => Model.ContactPhone)%> -

-

- <%: Html.HiddenFor(m => Model.Latitude)%> - <%: Html.HiddenFor(m => Model.Longitude)%> -

-

- -

- -
- -
- <% Html.RenderPartial("Map", Model); %> - (drag the pin in the map if it doesn't look right) -
- -
- -<% } %> - - - - diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Edit.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Edit.aspx deleted file mode 100644 index 6a37e95..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Edit.aspx +++ /dev/null @@ -1,46 +0,0 @@ -<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" - MasterPageFile="~/Views/Shared/Site.Master" %> - - - Edit: - <%:Model.Title %> - - -

- Edit Dinner

- <% Html.EnableClientValidation(); %> - <%: Html.ValidationSummary("Please correct the errors and try again.") %> - <% using (Html.BeginForm()) - { %> -
-
- <%:Html.EditorForModel() %> -

- -

-
-
- <%: Html.Partial("LocationDetail")%> -
-
- <% } %> - -
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/EditAndDeleteLinks.ascx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/EditAndDeleteLinks.ascx deleted file mode 100644 index fab58bc..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/EditAndDeleteLinks.ascx +++ /dev/null @@ -1,9 +0,0 @@ -<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> - -<% if (Model.IsHostedBy(Context.User.Identity.Name)) { %> - - <%: Html.ActionLink("Edit Dinner", "Edit", new { id=Model.DinnerId })%> - | - <%: Html.ActionLink("Delete Dinner", "Delete", new { id = Model.DinnerId })%> - -<% } %> \ No newline at end of file diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Index.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Index.aspx deleted file mode 100644 index 227bc87..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Index.aspx +++ /dev/null @@ -1,56 +0,0 @@ -<%@ Page Inherits="System.Web.Mvc.ViewPage>" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" %> - - - Upcoming Nerd Dinners - - - - <% Html.RenderPartial("Masthead", false); %> - - - - -
-

Upcoming Dinners

- -
    - - <% foreach (var dinner in Model) { %> - -
  • - <%: Html.ActionLink(dinner.Title, "Details", new { id=dinner.DinnerId }) %> - on - <%: dinner.EventDate.ToString("yyyy-MMM-dd")%> - <%: dinner.EventDate.ToString("HH:mm tt")%> - at - <%: dinner.Address + " " + dinner.Country %> -
  • - - <% } %> - -
-
- - - -
- - diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/InvalidOwner.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/InvalidOwner.aspx deleted file mode 100644 index 2a068bb..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/InvalidOwner.aspx +++ /dev/null @@ -1,14 +0,0 @@ - -<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - - - You Don't Own This Dinner - - - - -

Error Accessing Dinner

- -

Sorry - but only the host of a Dinner can edit or delete it.

- -
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Map.ascx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Map.ascx deleted file mode 100644 index 4b8ddf1..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Map.ascx +++ /dev/null @@ -1,28 +0,0 @@ -<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> - - - - - -
- diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Mobile/Details.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Mobile/Details.aspx deleted file mode 100644 index 629d41a..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Mobile/Details.aspx +++ /dev/null @@ -1,29 +0,0 @@ -<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Mobile/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - -<%: Model.Title %> - - -

nerddinner

-

<%: Model.Title %>

-
    -
  • When: <%: Model.EventDate.ToShortDateString() %> @ <%: Model.EventDate.ToShortTimeString() %>
  • -
  • Where: "><%: Model.Address %>, <%: Model.Country %>
  • -
  • Description: <%: Model.Description %>
  • -
  • Organizer: <%: Model.HostedBy %> (<%: Model.ContactPhone %>)
  • -
- -
-

Who's Coming?

- <%if (Model.GetRsvpCount() == 0){%> -
  • No one has registered.
- <% } %> - - <%if(Model.GetRsvpCount() > 0) {%> -
    - <%foreach (var rsvp in Model.GetRsvps()){%> -
  • <%: rsvp.AttendeeName.Replace("@"," at ") %>
  • - <% } %> -
- <%} %> -
-
\ No newline at end of file diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Mobile/iPhone/Details.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Mobile/iPhone/Details.aspx deleted file mode 100644 index b33c6c1..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/Mobile/iPhone/Details.aspx +++ /dev/null @@ -1,25 +0,0 @@ -<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %> - - - -
-

Who's Coming?

- <%if (Model.GetRsvpCount() == 0){%> -
  • No one has registered.
- <% } %> - - <%if(Model.GetRsvpCount() > 0) {%> -
    - <%foreach (var rsvp in Model.GetRsvps()){%> -
  • <%: rsvp.AttendeeName.Replace("@", " at ")%>
  • - <% } %> -
- <%} %> -
\ No newline at end of file diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/My.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/My.aspx deleted file mode 100644 index 9cab86d..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/My.aspx +++ /dev/null @@ -1,40 +0,0 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage>" %> - - - My Dinners - - - - -

My Dinners

- -
    - - <% foreach (var dinner in Model) { %> - -
  • - <%: Html.ActionLink(dinner.Title, "Details", new { id=dinner.DinnerId }) %> - on - <%: dinner.EventDate.ToString("yyyy-MMM-dd")%> - <%: dinner.EventDate.ToString("HH:mm tt")%> - at - <%: dinner.Address + " " + dinner.Country %> -
  • - - <% } %> - - <% if (Model.Count() == 0) { %> -
  • You don't own or aren't registered for any dinners.
  • - <% } %> - - -
- -
- - - - - - - diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/NotFound.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/NotFound.aspx deleted file mode 100644 index bd62ea5..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/NotFound.aspx +++ /dev/null @@ -1,14 +0,0 @@ - -<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - - - Nerd Dinner Not Found - - - - -

Lost?

- -

Sorry - but the dinner you requested doesn't exist or was deleted.

- -
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/RSVPStatus.ascx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/RSVPStatus.ascx deleted file mode 100644 index 66a7219..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/RSVPStatus.ascx +++ /dev/null @@ -1,44 +0,0 @@ -<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> - - - - - - -
- -<% if (Request.IsAuthenticated) { %> - - <% if (Model.IsHostedBy(Context.User.Identity.Name)) { %> - -

You are the host for this event!

- - <% } else if (Model.IsUserRegistered(Context.User.Identity.Name)) { %> - -

You are registered for this event!

- - <% } - else - { %> - - <%: Ajax.ActionLink("RSVP for this event", - "Register", "RSVP", - new { id = Model.DinnerId }, - new AjaxOptions { UpdateTargetId = "rsvpmsg", OnSuccess = "AnimateRSVPMessage" })%> - <% } %> - -<% } else { %> - - RSVP for this event: - ">Twitter - ">Google - ">Yahoo! -<% } %> - -
\ No newline at end of file diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/WebSlice.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/WebSlice.aspx deleted file mode 100644 index 1b44f72..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Dinners/WebSlice.aspx +++ /dev/null @@ -1,30 +0,0 @@ -<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage>" ContentType="text/html" %> - - - - - - <%: ViewData["Title"] %>< - - -
-
-

<%: ViewData["Title"] %>

-
-
    - <% foreach (var dinner in Model) { %> -
  • - <%: Html.ActionLink(dinner.Title, "Details", new { id=dinner.DinnerId }) %> - on - <%: dinner.EventDate.ToString("yyyy-MMM-dd")%> - <%: dinner.EventDate.ToString("HH:mm tt")%> at - <%: dinner.Address + " " + dinner.Country %> -
  • - <% } %> -
-
-
- -
- - diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Home/About.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Home/About.aspx deleted file mode 100644 index 6c15ce7..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Home/About.aspx +++ /dev/null @@ -1,20 +0,0 @@ -<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - - - About - - - - -

What is NerdDinner.com?

-
-

Picture of a huge nerd.Are you a huge nerd? Perhaps a geek? No? Maybe a dork, dweeb or wonk. - Quite possibly you're just a normal person. Either way, you're a social being. You need to get out for a bite - to eat occasionally, preferably with folks that are like you.

-

Enter NerdDinner.com, for all your event planning needs. We're focused on one thing. Organizing the world's - nerds and helping them eat in packs.

-

We're free and fun. Find a dinner near you, or host a dinner. Be social.

-

We also have blog badges and widgets that you can install on your blog or website so your readers can get - involved in the Nerd Dinner movement. Well, it's not really a movement. Mostly just geeks in a food court, but still.

-
-
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Home/Index.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Home/Index.aspx deleted file mode 100644 index c5b9024..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Home/Index.aspx +++ /dev/null @@ -1,87 +0,0 @@ -<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - - - NerdDinner - - - - <% Html.RenderPartial("Masthead", true); %> - - - - - - - -

Find a Dinner

- -
- - -
- -
- -
-
-

Popular Dinners

-
- -
-
- - - -
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Home/Mobile/Index.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Home/Mobile/Index.aspx deleted file mode 100644 index 5695ee0..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Home/Mobile/Index.aspx +++ /dev/null @@ -1,16 +0,0 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Mobile/Site.Master" - Inherits="System.Web.Mvc.ViewPage" %> - - - NerdDinner.com - - -

nerddinner

-

Find a Nerd Dinner near you!

- <% using (Html.BeginForm("SearchByPlaceNameOrZip", "Search", FormMethod.Post)) { %> - - <% } %> -
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Home/Mobile/iPhone/Index.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Home/Mobile/iPhone/Index.aspx deleted file mode 100644 index 1a7415a..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Home/Mobile/iPhone/Index.aspx +++ /dev/null @@ -1,25 +0,0 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Mobile/iPhone/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - - - NerdDinner - - - - -
-

- -
-
- -

Find a Nerd Dinner near you!

-
-
- - -
-
- Go -
- -
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Home/PrivacyPolicy.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Home/PrivacyPolicy.aspx deleted file mode 100644 index 03ae88f..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Home/PrivacyPolicy.aspx +++ /dev/null @@ -1,18 +0,0 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - - - PrivacyPolicy - - - - -

PrivacyPolicy

- -
- - - - - - We will never sell or give away anything of yours that we have. Honest. - diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Services/Flair.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Services/Flair.aspx deleted file mode 100644 index 87bf772..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Services/Flair.aspx +++ /dev/null @@ -1,34 +0,0 @@ -<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %> -<%@ Import Namespace="NerdDinner.Helpers" %> -<%@ Import Namespace="NerdDinner.Models" %> - - - - Nerd Dinner - - - -
-

NerdDinner.com

-
- <% if (Model.Dinners.Count == 0) { %> -
- Looks like there's no Nerd Dinners near - <%:Model.LocationName %> - in the near future. Why not host one?
- <% } else { %> -

- Dinners Near You

-
    - <% foreach (var item in Model.Dinners) { %> -
  • - <%: Html.ActionLink(String.Format("{0} with {1} on {2}", item.Title.Truncate(20), item.HostedBy, item.EventDate.ToShortDateString()), "Details", "Dinners", new { id = item.DinnerId }, new { target = "_blank" })%>
  • - <% } %> -
- <% } %> - -
-
- - diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Services/JavascriptFlair.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Services/JavascriptFlair.aspx deleted file mode 100644 index 269b3f1..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Services/JavascriptFlair.aspx +++ /dev/null @@ -1,15 +0,0 @@ -<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" ContentType="application/x-javascript" %> -<%@ Import Namespace="NerdDinner.Helpers" %> -<%@ Import Namespace="NerdDinner.Models" %> -document.write(''); -document.write('

NerdDinner.com

'); -<% if (Model.Dinners.Count == 0) { %> - document.write('
Looks like there\'s no Nerd Dinners near <%:Model.LocationName %> in the near future. Why not host one?
'); -<% } else { %> -document.write('

Dinners Near You

'); -<% } %> -document.write('
More dinners and fun at http://nrddnr.com
'); \ No newline at end of file diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Confused.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Confused.aspx deleted file mode 100644 index 1867d1e..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Confused.aspx +++ /dev/null @@ -1,10 +0,0 @@ -<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - - - Error - - - -

Confused?

-

Are you lost? Try taking a look at the complete list of Upcoming Dinners.

-
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/EditorTemplates/CountryDropDown.ascx b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/EditorTemplates/CountryDropDown.ascx deleted file mode 100644 index d34486d..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/EditorTemplates/CountryDropDown.ascx +++ /dev/null @@ -1,2 +0,0 @@ -<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> -<%: Html.DropDownList("", new SelectList(NerdDinner.Helpers.PhoneValidator.Countries, Model)) %> \ No newline at end of file diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/EditorTemplates/DateTime.ascx b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/EditorTemplates/DateTime.ascx deleted file mode 100644 index be40414..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/EditorTemplates/DateTime.ascx +++ /dev/null @@ -1,10 +0,0 @@ -<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> - <%: Html.TextBox("", String.Format("{0:yyyy-MM-dd HH:mm}",Model)) %> - diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Error.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Error.aspx deleted file mode 100644 index 98a0db5..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Error.aspx +++ /dev/null @@ -1,10 +0,0 @@ -<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - - - Error - - - -

Oh Snap!

-

Sorry, an error occurred while processing your request. We've been notified and we will check it out. If you know what you were doing, or if you're evil, let us know on our feedback site.

-
diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/LocationDetail.ascx b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/LocationDetail.ascx deleted file mode 100644 index b224ad4..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/LocationDetail.ascx +++ /dev/null @@ -1,27 +0,0 @@ -<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> - - -
-
- - (drag the pin in the map if it doesn't look right) * diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/LogOn.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/LogOn.aspx deleted file mode 100644 index 4709507..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/LogOn.aspx +++ /dev/null @@ -1,12 +0,0 @@ -<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> - - - " /> - " /> - - - <% Html.RenderPartial("LogOnContent"); %> - - - <% Html.RenderPartial("LogOnScripts"); %> - \ No newline at end of file diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/LogOnContent.ascx b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/LogOnContent.ascx deleted file mode 100644 index fe5f1f5..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/LogOnContent.ascx +++ /dev/null @@ -1,23 +0,0 @@ -<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> -<%@ Import Namespace="DotNetOpenAuth.Mvc" %> -<%@ Import Namespace="DotNetOpenAuth.OpenId.RelyingParty" %> - -<% using (Html.BeginForm("LogOnPostAssertion", "Auth", FormMethod.Post, new { target = "_top" })) { %> -<%= Html.AntiForgeryToken() %> -<%= Html.Hidden("ReturnUrl", Request.QueryString["ReturnUrl"], new { id = "ReturnUrl" }) %> -<%= Html.Hidden("openid_openidAuthData") %> -
-<%= Html.OpenIdSelector(this.Page, new SelectorButton[] { - new SelectorProviderButton("https://me.yahoo.com/", Url.Content("~/Content/images/yahoo.gif")), - new SelectorProviderButton("https://www.google.com/accounts/o8/id", Url.Content("~/Content/images/google.gif")), - new SelectorOpenIdButton(Url.Content("~/Content/images/openid.gif")), -}) %> - -
-

- If you have logged in previously, click the same button you did last time. -

-
- -
-<% } %> diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/LoginStatus.ascx b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/LoginStatus.ascx deleted file mode 100644 index 31b4f17..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/LoginStatus.ascx +++ /dev/null @@ -1,15 +0,0 @@ -<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> -<%@ Import Namespace="NerdDinner" %> -<% - if (Request.IsAuthenticated) { -%> - Welcome <%: ((NerdIdentity)Page.User.Identity).FriendlyName %>! - [ <%: Html.ActionLink("Log Off", "LogOff", "Account") %> ] -<% - } - else { -%> - [ <%: Html.ActionLink("Log On", "LogOn", new { controller = "Account", returnUrl = HttpContext.Current.Request.RawUrl }) %> ] -<% - } -%> diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Masthead.ascx b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Masthead.ascx deleted file mode 100644 index eaf01e3..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Masthead.ascx +++ /dev/null @@ -1,11 +0,0 @@ -<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> -
- <%if ((bool)Model == true) { //Show Search Box %> - - <% } %> -
- diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Mobile/Results.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Mobile/Results.aspx deleted file mode 100644 index 30099c6..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Mobile/Results.aspx +++ /dev/null @@ -1,36 +0,0 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Mobile/Site.Master" Inherits="System.Web.Mvc.ViewPage>" %> - - - Results - - - - -

Nerd Dinners

-
    - <% foreach (var dinner in Model) { %> -
  • -
      -
    • - "><%:dinner.Title %> -
    • -
    • - <%:dinner.EventDate.ToString("yyyy-MMM-dd")%> - @ - <%: dinner.EventDate.ToString("h:mm tt")%> -
    • -
    - -
  • - <% } %> - <% if (Model.Count() == 0) { %> -
  • No Nerd Dinners found!
  • - <% } %> - -
-

- <%: Html.ActionLink("Back", "Index", "Home") %> -

- -
- diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Mobile/Site.Master b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Mobile/Site.Master deleted file mode 100644 index 6e3213a..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Mobile/Site.Master +++ /dev/null @@ -1,18 +0,0 @@ -<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %> - - - - <asp:ContentPlaceHolder ID="TitleContent" runat="server" ></asp:ContentPlaceHolder> - - <%-- TODO: Remove expires tag --%> - - - - , height=<%:Request.Browser["ScreenPixelsHeight"]%>"/> - - -
- -
- - \ No newline at end of file diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Mobile/iPhone/Results.aspx b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Mobile/iPhone/Results.aspx deleted file mode 100644 index 15ba7d4..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Mobile/iPhone/Results.aspx +++ /dev/null @@ -1,11 +0,0 @@ -<%@ Page Inherits="System.Web.Mvc.ViewPage>" Language="C#" %> - diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Mobile/iPhone/Site.Master b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Mobile/iPhone/Site.Master deleted file mode 100644 index 4e24fb1..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Mobile/iPhone/Site.Master +++ /dev/null @@ -1,17 +0,0 @@ -<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %> - - - - <asp:ContentPlaceHolder ID="TitleContent" runat="server" ></asp:ContentPlaceHolder> - - - - - - - - - - - - \ No newline at end of file diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Site.Master b/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Site.Master deleted file mode 100644 index 6a17066..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Shared/Site.Master +++ /dev/null @@ -1,98 +0,0 @@ -<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %> - - - - - <asp:ContentPlaceHolder ID="TitleContent" runat="server" /> - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - -
- -
- - - -
- - - - - - - - - - - diff --git a/sample/NerdDinner_2.0/NerdDinner/Views/Web.config b/sample/NerdDinner_2.0/NerdDinner/Views/Web.config deleted file mode 100644 index 04c0482..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Views/Web.config +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sample/NerdDinner_2.0/NerdDinner/Web.config b/sample/NerdDinner_2.0/NerdDinner/Web.config deleted file mode 100644 index f72792a..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/Web.config +++ /dev/null @@ -1,148 +0,0 @@ - - - - - -
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/sample/NerdDinner_2.0/NerdDinner/apple-touch-icon.png b/sample/NerdDinner_2.0/NerdDinner/apple-touch-icon.png deleted file mode 100644 index a478f5f..0000000 Binary files a/sample/NerdDinner_2.0/NerdDinner/apple-touch-icon.png and /dev/null differ diff --git a/sample/NerdDinner_2.0/NerdDinner/favicon.ico b/sample/NerdDinner_2.0/NerdDinner/favicon.ico deleted file mode 100644 index 4fb92bf..0000000 Binary files a/sample/NerdDinner_2.0/NerdDinner/favicon.ico and /dev/null differ diff --git a/sample/NerdDinner_2.0/NerdDinner/lib/DDay.iCal-License.txt b/sample/NerdDinner_2.0/NerdDinner/lib/DDay.iCal-License.txt deleted file mode 100644 index e789652..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/lib/DDay.iCal-License.txt +++ /dev/null @@ -1,35 +0,0 @@ -The DDay.iCal library, its documentation, and its source code -are Copyright © 2007 Douglas Day . -All rights reserved. - -Redistribution and use in source and binary forms, with or -without modification, are permitted provided that the following -conditions are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - - * Neither the name "DDay.iCal" nor the names of - its contributors may be used to endorse or promote - products derived from this software without specific - prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND -CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/sample/NerdDinner_2.0/NerdDinner/lib/DDay.iCal.dll b/sample/NerdDinner_2.0/NerdDinner/lib/DDay.iCal.dll deleted file mode 100644 index 21ecae7..0000000 Binary files a/sample/NerdDinner_2.0/NerdDinner/lib/DDay.iCal.dll and /dev/null differ diff --git a/sample/NerdDinner_2.0/NerdDinner/lib/DotNetOpenAuth.dll b/sample/NerdDinner_2.0/NerdDinner/lib/DotNetOpenAuth.dll deleted file mode 100644 index b66beb5..0000000 Binary files a/sample/NerdDinner_2.0/NerdDinner/lib/DotNetOpenAuth.dll and /dev/null differ diff --git a/sample/NerdDinner_2.0/NerdDinner/lib/DotNetOpenAuth.pdb b/sample/NerdDinner_2.0/NerdDinner/lib/DotNetOpenAuth.pdb deleted file mode 100644 index 5228e33..0000000 Binary files a/sample/NerdDinner_2.0/NerdDinner/lib/DotNetOpenAuth.pdb and /dev/null differ diff --git a/sample/NerdDinner_2.0/NerdDinner/lib/ELMAH-LICENSE.txt b/sample/NerdDinner_2.0/NerdDinner/lib/ELMAH-LICENSE.txt deleted file mode 100644 index a11f7fa..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/lib/ELMAH-LICENSE.txt +++ /dev/null @@ -1,12 +0,0 @@ -Copyright (c) 2004-7, Atif Aziz. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -- Neither the name of the original author (Atif Aziz) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/sample/NerdDinner_2.0/NerdDinner/lib/Elmah.dll b/sample/NerdDinner_2.0/NerdDinner/lib/Elmah.dll deleted file mode 100644 index 541146d..0000000 Binary files a/sample/NerdDinner_2.0/NerdDinner/lib/Elmah.dll and /dev/null differ diff --git a/sample/NerdDinner_2.0/NerdDinner/lib/Elmah.pdb b/sample/NerdDinner_2.0/NerdDinner/lib/Elmah.pdb deleted file mode 100644 index a52aa36..0000000 Binary files a/sample/NerdDinner_2.0/NerdDinner/lib/Elmah.pdb and /dev/null differ diff --git a/sample/NerdDinner_2.0/NerdDinner/lib/Elmah.xml b/sample/NerdDinner_2.0/NerdDinner/lib/Elmah.xml deleted file mode 100644 index e8ab87b..0000000 --- a/sample/NerdDinner_2.0/NerdDinner/lib/Elmah.xml +++ /dev/null @@ -1,1713 +0,0 @@ - - - - Elmah - - - - - Renders an HTML page that presents information about the version, - build configuration, source files as well as a method to check - for updates. - - - - - Provides the base implementation and layout for most pages that render - HTML for the error log. - - - - - The exception that is thrown when a non-fatal error occurs. - This exception also serves as the base for all exceptions thrown by - this library. - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class - with a specified error message. - - - - - Initializes a new instance of the - class with a specified error message and a reference to the - inner exception that is the cause of this exception. - - - - - Initializes a new instance of the class - with serialized data. - - - - - An implementation that uses Microsoft Access - as its backing store. - - - The MDB file is automatically created at the path specified in the - connection string if it does not already exist. - - - - - Represents an error log capable of storing and retrieving errors - generated in an ASP.NET Web application. - - - - - Logs an error in log for the application. - - - - - When overridden in a subclass, begins an asynchronous version - of . - - - - - When overridden in a subclass, ends an asynchronous version - of . - - - - - Retrieves a single application error from log given its - identifier, or null if it does not exist. - - - - - When overridden in a subclass, begins an asynchronous version - of . - - - - - When overridden in a subclass, ends an asynchronous version - of . - - - - - Retrieves a page of application errors from the log in - descending order of logged time. - - - - - When overridden in a subclass, begins an asynchronous version - of . - - - - - When overridden in a subclass, ends an asynchronous version - of . - - - - - Gets the default error log implementation specified in the - configuration file, or the in-memory log implemention if - none is configured. - - - - - Get the name of this log. - - - - - Gets the name of the application to which the log is scoped. - - - - - Gets the default error log implementation specified in the - configuration file, or the in-memory log implemention if - none is configured. - - - - - Initializes a new instance of the class - using a dictionary of configured settings. - - - - - Initializes a new instance of the class - to use a specific connection string for connecting to the database. - - - - - Logs an error to the database. - - - Use the stored procedure called by this implementation to set a - policy on how long errors are kept in the log. The default - implementation stores all errors for an indefinite time. - - - - - Returns a page of errors from the databse in descending order - of logged time. - - - - - Returns the specified error from the database, or null - if it does not exist. - - - - - Gets the name of this error log implementation. - - - - - Gets the connection string used by the log to connect to the database. - - - - - Represents the method that will be responsible for creating an - assertion object and initializing it from an XML configuration - element. - - - - - Holds factory methods for creating configured assertion objects. - - - - - Ideally, we would be able to use SoapServices.DecodeXmlNamespaceForClrTypeNamespace - but that requires a link demand permission that will fail in partially trusted - environments such as ASP.NET medium trust. - - - - - An assertion implementation whose test is based on whether - the result of an input expression evaluated against a context - matches a regular expression pattern or not. - - - - - Provides evaluation of a context to determine whether it matches - certain criteria or not. - - - - - The context is typed generically as System.Object when it could have - been restricted to System.Web.HttpContext and also avoid unnecessary - casting downstream. However, using object allows simple - assertions to be unit-tested without having to stub out a lot of - the classes from System.Web (most of which cannot be stubbed anyhow - due to lack of virtual and instance methods). - - - - - Read-only collection of instances. - - - - - Provides data expression evaluation facilites similar to - in ASP.NET. - - - - - An assertion implementation that uses a JScript expression to - determine the outcome. - - - Each instance of this type maintains a separate copy of the JScript - engine so use it sparingly. For example, instead of creating several - objects, each with different a expression, try and group all - expressions that apply to particular context into a single compound - JScript expression using the conditional-OR (||) operator. - - - - - Uses the JScript eval function to compile and evaluate the - expression against the context on each evaluation. - - - - - Compiles the given expression into a JScript function at time of - construction and then simply invokes it during evaluation, using - the context as a parameter. - - - - - An assertion implementation whose test is based on whether - the result of an input expression evaluated against a context - matches a regular expression pattern or not. - - - - - An static assertion implementation that always evaluates to - a preset value. - - - - - An assertion implementation whose test is based on whether - the result of an input expression evaluated against a context - matches a regular expression pattern or not. - - - - - This is the status or milestone of the build. Examples are - M1, M2, ..., Mn, BETA1, BETA2, RC1, RC2, RTM. - - - - - Gets a string representing the version of the CLR saved in - the file containing the manifest. Under 1.0, this returns - the hard-wired string "v1.0.3705". - - - - - Helper class for handling values in configuration sections. - - - - - Helper class for resolving connection strings. - - - - - Gets the connection string from the given configuration - dictionary. - - - - - Extracts the Data Source file path from a connection string - ~/ gets resolved as does |DataDirectory| - - - - - Gets the connection string from the given configuration, - resolving ~/ and DataDirectory if necessary. - - - - - Converts the supplied connection string so that the Data Source - specification contains the full path and not ~/ or DataDirectory. - - - - - Provides methods for assertions and debugging help that is mostly - applicable during development. - - - - - Represents a logical application error (as opposed to the actual - exception it may be representing). - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class - from a given instance. - - - - - Initializes a new instance of the class - from a given instance and - instance representing the HTTP - context during the exception. - - - - - Returns the value of the property. - - - - - Creates a new object that is a copy of the current instance. - - - - - Gets the instance used to initialize this - instance. - - - This is a run-time property only that is not written or read - during XML serialization via and - . - - - - - Gets or sets the name of application in which this error occurred. - - - - - Gets or sets name of host machine where this error occurred. - - - - - Gets or sets the type, class or category of the error. - - - - - Gets or sets the source that is the cause of the error. - - - - - Gets or sets a brief text describing the error. - - - - - Gets or sets a detailed text describing the error, such as a - stack trace. - - - - - Gets or sets the user logged into the application at the time - of the error. - - - - - Gets or sets the date and time (in local time) at which the - error occurred. - - - - - Gets or sets the HTTP status code of the output returned to the - client for the error. - - - For cases where this value cannot always be reliably determined, - the value may be reported as zero. - - - - - Gets or sets the HTML message generated by the web host (ASP.NET) - for the given error. - - - - - Gets a collection representing the Web server variables - captured as part of diagnostic data for the error. - - - - - Gets a collection representing the Web query string variables - captured as part of diagnostic data for the error. - - - - - Gets a collection representing the form variables captured as - part of diagnostic data for the error. - - - - - Gets a collection representing the client cookies - captured as part of diagnostic data for the error. - - - - - Renders an HTML page displaying details about an error from the - error log. - - - - - Renders an RSS feed that is a daily digest of the most recently - recorded errors in the error log. The feed spans at most 15 - days on which errors occurred. - - - - - Provides miscellaneous formatting methods for - - - - - Formats the type of an error, typically supplied as the - value, in a short and human- - readable form. - - - Typically, exception type names can be long to display and - complex to consume. The essential part can usually be found in - the start of an exception type name minus its namespace. For - example, a human reading the string, - "System.Runtime.InteropServices.COMException", will usually - considers "COM" as the most useful component of the entire - type name. This method does exactly that. It assumes that the - the input type is a .NET Framework exception type name where - the namespace and class will be separated by the last - period (.) and where the type name ends in "Exception". If - these conditions are method then a string like, - "System.Web.HttpException" will be transformed into simply - "Html". - - - - - Formats the error type of an object in a - short and human-readable form. - - - - - HTTP module implementation that logs unhandled exceptions in an - ASP.NET Web application to an error log. - - - - - Initializes the module and prepares it to handle requests. - - - - - Disposes of the resources (other than memory) used by the module. - - - - - Handler for the <errorFilter> section of the - configuration file. - - - - - Renders an HTML page displaying the detailed host-generated (ASP.NET) - HTML recorded for an error from the error log. - - - - - Responsible for primarily encoding the JSON representation of - objects. - - - - - Encodes the default JSON representation of an - object to a string. - - - Only properties and collection entires with non-null - and non-empty strings are emitted. - - - - - Encodes the default JSON representation of an - object to a . - - - Only properties and collection entires with non-null - and non-empty strings are emitted. - - - - - Renders an error as JSON Text (RFC 4627). - - - - - Methods of this type are designed to serve an - control - and are adapted according to expected call signatures and - behavior. - - - - - Initializes a new instance of the - class with the default - error log implementation. - - - - - Use as the value for . - - - - - Use as the value for . - - - The parameters of this method are named after the default values - for - and so - that the minimum markup is needed for the object data source - control. - - - - - Binds an instance with the - instance from where it was served. - - - - - Initializes a new instance of the class - for a given unique error entry in an error log. - - - - - Gets the instance where this entry - originated from. - - - - - Gets the unique identifier that identifies the error entry - in the log. - - - - - Gets the object held in the entry. - - - - - HTTP module implementation that logs unhandled exceptions in an - ASP.NET Web application to an error log. - - - - - Provides an abstract base class for that - supports discovery from within partial trust environments. - - - - - Initializes the module and prepares it to handle requests. - - - - - Disposes of the resources (other than memory) used by the module. - - - - - Determines whether the module will be registered for discovery - in partial trust environments or not. - - - - - Initializes the module and prepares it to handle requests. - - - - - Gets the instance to which the module - will log exceptions. - - - - - The handler called when an unhandled exception bubbles up to - the module. - - - - - The handler called when an exception is explicitly signaled. - - - - - Logs an exception and its context to the error log. - - - - - Raises the event. - - - - - Raises the event. - - - - - Determines whether the module will be registered for discovery - in partial trust environments or not. - - - - - Renders an HTML page displaying a page of errors from the error log. - - - - - HTTP handler factory that dispenses handlers for rendering views and - resources needed to display the error log. - - - - - Returns an object that implements the - interface and which is responsible for serving the request. - - - A new object that processes the request. - - - - - Enables the factory to reuse an existing handler instance. - - - - - Determines if the request is authorized by objects implementing - . - - - Returns zero if unauthorized, a value greater than zero if - authorized otherwise a value less than zero if no handlers - were available to answer. - - - - - Handler for the <errorLog> section of the - configuration file. - - - - - Formats the HTML to display the details of a given error that is - suitable for sending as the body of an e-mail message. - - - - - Provides the base contract for implementations that render - text-based formatting for an error. - - - - - Formats a text representation of the given - instance using a . - - - - - Gets the MIME type of the text format provided by the formatter - implementation. - - - - - Formats a complete HTML document describing the given - instance. - - - - - Renders the <head> section of the HTML document. - - - - - Renders the <body> section of the HTML document. - - - - - Renders the footer content that appears at the end of the - HTML document body. - - - - - Renders the <style> element along with in-line styles - used to format the body of the HTML document. - - - - - Renders the details about the object in - body of the HTML document. - - - - - Renders a summary about the object in - body of the HTML document. - - - - - Renders the diagnostic collections of the object in - body of the HTML document. - - - - - Renders a collection as a table in HTML document body. - - - This method is called by to - format a diagnostic collection from object. - - - - - Returns the text/html MIME type that is the format provided - by this implementation. - - - - - Gets the used for HTML formatting. - - - This property is only available to downstream methods in the - context of the method call. - - - - - Gets the object for which a HTML document - is being formatted. - - - This property is only available to downstream methods in the - context of the method call. - - - - - HTTP module that sends an e-mail whenever an unhandled exception - occurs in an ASP.NET web application. - - - - - Initializes the module and prepares it to handle requests. - - - - - The handler called when an unhandled exception bubbles up to - the module. - - - - - The handler called when an exception is explicitly signaled. - - - - - Reports the exception. - - - - - Raises the event. - - - - - Schedules the error to be e-mailed asynchronously. - - - The default implementation uses the - to queue the reporting. - - - - - Schedules the error to be e-mailed synchronously. - - - - - Creates the implementation to - be used to format the body of the e-mail. - - - - - Sends the e-mail using SmtpMail or SmtpClient. - - - - - Fires the event. - - - - - Fires the event. - - - - - Fires the event. - - - - - Gets the configuration object used by to read - the settings for module. - - - - - Builds an object from the last context - exception generated. - - - - - Determines whether the module will be registered for discovery - in partial trust environments or not. - - - - - Gets the e-mail address of the sender. - - - - - Gets the e-mail address of the recipient, or a - comma-/semicolon-delimited list of e-mail addresses in case of - multiple recipients. - - - When using System.Web.Mail components under .NET Framework 1.x, - multiple recipients must be semicolon-delimited. - When using System.Net.Mail components under .NET Framework 2.0 - or later, multiple recipients must be comma-delimited. - - - - - Gets the e-mail address of the recipient for mail carbon - copy (CC), or a comma-/semicolon-delimited list of e-mail - addresses in case of multiple recipients. - - - When using System.Web.Mail components under .NET Framework 1.x, - multiple recipients must be semicolon-delimited. - When using System.Net.Mail components under .NET Framework 2.0 - or later, multiple recipients must be comma-delimited. - - - - - Gets the text used to format the e-mail subject. - - - The subject text specification may include {0} where the - error message () should be inserted - and {1} where the error type should - be insert. - - - - - Gets the SMTP server host name used when sending the mail. - - - - - Gets the SMTP port used when sending the mail. - - - - - Gets the user name to use if the SMTP server requires authentication. - - - - - Gets the clear-text password to use if the SMTP server requires - authentication. - - - - - Handler for the <errorMail> section of the - configuration file. - - - - - Renders a XML using the RSS 0.91 vocabulary that displays, at most, - the 15 most recent errors recorded in the error log. - - - - - Responsible for encoding and decoding the XML representation of - an object. - - - - - Decodes an object from its default XML - representation. - - - - - Decodes an object from its XML representation. - - - - - Reads the error data in XML attributes. - - - - - Reads the error data in child nodes. - - - - - Encodes the default XML representation of an - object to a string. - - - - - Encodes the XML representation of an object. - - - - - Writes the error data that belongs in XML attributes. - - - - - Writes the error data that belongs in child nodes. - - - - - Encodes an XML representation for a - object. - - - - - Updates an existing object from - its XML representation. - - - - - Renders an error as an XML document. - - - - - HTTP module that resolves issues in ELMAH when wilcard mapping - is implemented in IIS 5.x. - - - See Elmah - with existing wildcard mapping for more information behind the - reason for this module. - - - - - User agents, search engines, etc. may interpret and use these link - types in a variety of ways. For example, user agents may provide - access to linked documents through a navigation bar. - - - See 6.12 Link types - for more information. - - - - - Security-related helper methods for web requests. - - - - - Determines whether the request is from the local computer or not. - - - This method is primarily for .NET Framework 1.x where the - was not available. - - - - - Represents an HTTP status (code plus reason) as per - Section 6.1 of RFC 2616. - - - - - Helper methods for array containing culturally-invariant strings. - The main reason for this helper is to help with po - - - - - Indicates that the marked method is assertion method, i.e. it halts control flow if one of the conditions is satisfied. - To set the condition, mark one of the parameters with attribute. - - - - - - Indicates the condition parameter of the assertion method. - The method itself should be marked by attribute. - The mandatory argument of the attribute is the assertion type. - - - - - - Initializes new instance of AssertionConditionAttribute. - - Specifies condition type. - - - - Gets condition type. - - - - - Specifies assertion type. If the assertion method argument satisifes the condition, then the execution continues. - Otherwise, execution is assumed to be halted. - - - - - Indicates that the marked parameter should be evaluated to true. - - - - - Indicates that the marked parameter should be evaluated to false. - - - - - Indicates that the marked parameter should be evaluated to null value. - - - - - Indicates that the marked parameter should be evaluated to not null value. - - - - - Represents a writer that provides a fast, non-cached, forward-only - way of generating streams or files containing JSON Text according - to the grammar rules laid out in - RFC 4627. - - - This class supports ELMAH and is not intended to be used directly - from your code. It may be modified or removed in the future without - notice. It has public accessibility for testing purposes. If you - need a general-purpose JSON Text encoder, consult - JSON.org for implementations - or use classes available from the Microsoft .NET Framework. - - - - - Reads a resource from the assembly manifest and returns its contents - as the response entity. - - - - - Collection of utility methods for masking values. - - - - - An implementation that uses memory as its - backing store. - - - All instances will share the same memory - store that is bound to the application (not an instance of this class). - - - - - The maximum number of errors that will ever be allowed to be stored - in memory. - - - - - The maximum number of errors that will be held in memory by default - if no size is specified. - - - - - Initializes a new instance of the class - with a default size for maximum recordable entries. - - - - - Initializes a new instance of the class - with a specific size for maximum recordable entries. - - - - - Initializes a new instance of the class - using a dictionary of configured settings. - - - - - Logs an error to the application memory. - - - If the log is full then the oldest error entry is removed. - - - - - Returns the specified error from application memory, or null - if it does not exist. - - - - - Returns a page of errors from the application memory in - descending order of logged time. - - - - - Gets the name of this error log implementation. - - - - - Module to log unhandled exceptions during a delta-update - request issued by the client when a page uses the UpdatePanel - introduced with ASP.NET 2.0 AJAX Extensions. - - - - This module is ONLY required when dealing with v1.0.x.x of System.Web.Extensions.dll - (i.e. the downloadable version to extend v2.0 of the .Net Framework) - - - Using it with v3.5 of System.Web.Extensions.dll (which shipped as part of v3.5 of the - .Net Framework) will result in a duplication of errors. - - - This is because MS have changed the implementation of - System.Web.UI.PageRequestManager.OnPageError - - - In v1.0.x.x, the code performs a brutal Response.End(); in an attempt to - "tidy up"! This means that the error will not bubble up to the Application.Error - handlers, so Elmah is unable to catch them. - - - In v3.5, this is handled much more gracefully, allowing Elmah to do its thing without - the need for this module! - - - - - - Logs an exception and its context to the error log. - - - - - An implementation that uses Oracle as its backing store. - - - - - Initializes a new instance of the class - using a dictionary of configured settings. - - - - - Initializes a new instance of the class - to use a specific connection string for connecting to the database. - - - - - Logs an error to the database. - - - Use the stored procedure called by this implementation to set a - policy on how long errors are kept in the log. The default - implementation stores all errors for an indefinite time. - - - - - Returns a page of errors from the databse in descending order - of logged time. - - - - - Returns the specified error from the database, or null - if it does not exist. - - - - - Gets the name of this error log implementation. - - - - - Gets the connection string used by the log to connect to the database. - - - - - Displays a "Powered-by ELMAH" message that also contains the assembly - file version informatin and copyright notice. - - - - - Renders the contents of the control into the specified writer. - - - - - Represents a source code control (SCC) stamp and its components. - - - - - Initializes an instance given a SCC stamp - ID. The ID is expected to be in the format popularized by CVS - and SVN. - - - - - Finds and builds an array of instances - from all the attributes applied to - the given assembly. - - - - - Finds the latest SCC stamp for an assembly. The latest stamp is - the one with the highest revision number. - - - - - Finds the latest stamp among an array of - objects. The latest stamp is the one with the highest revision - number. - - - - - Sorts an array of objects by their - revision numbers in ascending order. - - - - - Sorts an array of objects by their - revision numbers in ascending or descending order. - - - - - Gets the original SCC stamp ID. - - - - - Gets the author component of the SCC stamp ID. - - - - - Gets the file name component of the SCC stamp ID. - - - - - Gets the revision number component of the SCC stamp ID. - - - - - Gets the last modification time component of the SCC stamp ID. - - - - - Gets the last modification time, in coordinated universal time - (UTC), component of the SCC stamp ID in local time. - - - - - Handler for the <security> section of the - configuration file. - - - - - A simple factory for creating instances of types specified in a - section of the configuration file. - - - - - An implementation that uses Microsoft SQL - Server 2000 as its backing store. - - - - - Initializes a new instance of the class - using a dictionary of configured settings. - - - - - Initializes a new instance of the class - to use a specific connection string for connecting to the database. - - - - - Logs an error to the database. - - - Use the stored procedure called by this implementation to set a - policy on how long errors are kept in the log. The default - implementation stores all errors for an indefinite time. - - - - - Returns a page of errors from the databse in descending order - of logged time. - - - - - Begins an asynchronous version of . - - - - - Ends an asynchronous version of . - - - - - Returns the specified error from the database, or null - if it does not exist. - - - - - Gets the name of this error log implementation. - - - - - Gets the connection string used by the log to connect to the database. - - - - - An implementation that wraps another. - - - - - Provides translation from multiple representations of a string to a - single base representation. - - - - - An implementation that uses SQLite as its backing store. - - - - - Initializes a new instance of the class - using a dictionary of configured settings. - - - - - Initializes a new instance of the class - to use a specific connection string for connecting to the database. - - - - - Logs an error to the database. - - - Use the stored procedure called by this implementation to set a - policy on how long errors are kept in the log. The default - implementation stores all errors for an indefinite time. - - - - - Returns a page of errors from the databse in descending order - of logged time. - - - - - Returns the specified error from the database, or null - if it does not exist. - - - - - Gets the name of this error log implementation. - - - - - Gets the connection string used by the log to connect to the database. - - - - - The exception that is thrown when to test the error logging - subsystem. This exception is used for testing purposes only and - should not be used for any other purpose. - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class - with a specified error message. - - - - - ializes a new instance of the - class with a specified error message and a reference to the - inner exception that is the cause of this exception. - - - - - Initializes a new instance of the class - with serialized data. - - - - - An implementation that uses VistaDB as its backing store. - - - - - Initializes a new instance of the class - using a dictionary of configured settings. - - - - - Initializes a new instance of the class - to use a specific connection string for connecting to the database. - - - - - Logs an error to the database. - - - Use the stored procedure called by this implementation to set a - policy on how long errors are kept in the log. The default - implementation stores all errors for an indefinite time. - - - - - Returns a page of errors from the databse in descending order - of logged time. - - - - - Returns the specified error from the database, or null - if it does not exist. - - - - - Gets the name of this error log implementation. - - - - - Gets the connection string used by the log to connect to the database. - - - - - An implementation that uses XML files stored on - disk as its backing store. - - - - - Initializes a new instance of the class - using a dictionary of configured settings. - - - - - This method is excluded from inlining so that if - HostingEnvironment does not need JIT-ing if it is not implicated - by the caller. - - - - - Initializes a new instance of the class - to use a specific path to store/load XML files. - - - - - Logs an error to the database. - - - Logs an error as a single XML file stored in a folder. XML files are named with a - sortable date and a unique identifier. Currently the XML files are stored indefinately. - As they are stored as files, they may be managed using standard scheduled jobs. - - - - - Returns a page of errors from the folder in descending order - of logged time as defined by the sortable filenames. - - - - - Returns the specified error from the filesystem, or throws an exception if it does not exist. - - - - - Gets the path to where the log is stored. - - - - - Gets the name of this error log implementation. - - - - diff --git a/sample/NerdDinner_2.0/NerdDinner/lib/OpenSearchToolkit.dll b/sample/NerdDinner_2.0/NerdDinner/lib/OpenSearchToolkit.dll deleted file mode 100644 index 2b7bc47..0000000 Binary files a/sample/NerdDinner_2.0/NerdDinner/lib/OpenSearchToolkit.dll and /dev/null differ diff --git a/sample/NerdDinner_2.0/NerdDinner/lib/antlr.runtime.dll b/sample/NerdDinner_2.0/NerdDinner/lib/antlr.runtime.dll deleted file mode 100644 index 857fbf3..0000000 Binary files a/sample/NerdDinner_2.0/NerdDinner/lib/antlr.runtime.dll and /dev/null differ diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo.sln b/sample/SimpleCQRSDemo/SimpleCQRSDemo.sln deleted file mode 100644 index 6fe7cf7..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleCQRSDemo", "SimpleCQRSDemo\SimpleCQRSDemo.csproj", "{E9C9FB2C-9DF3-492F-BC94-47298AD92E14}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x86 = Debug|x86 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E9C9FB2C-9DF3-492F-BC94-47298AD92E14}.Debug|x86.ActiveCfg = Debug|x86 - {E9C9FB2C-9DF3-492F-BC94-47298AD92E14}.Debug|x86.Build.0 = Debug|x86 - {E9C9FB2C-9DF3-492F-BC94-47298AD92E14}.Release|x86.ActiveCfg = Release|x86 - {E9C9FB2C-9DF3-492F-BC94-47298AD92E14}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/CommandHandlers/CreateAccountCommandHandler.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/CommandHandlers/CreateAccountCommandHandler.cs deleted file mode 100644 index fa215a2..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/CommandHandlers/CreateAccountCommandHandler.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using SimpleCqrs.Commanding; -using SimpleCqrs.Domain; -using SimpleCQRSDemo.Commands; -using SimpleCQRSDemo.Domain; - -namespace SimpleCQRSDemo.CommandHandlers -{ - public class CreateAccountCommandHandler : CommandHandler - { - private readonly IDomainRepository repository; - - public CreateAccountCommandHandler(IDomainRepository repository) - { - this.repository = repository; - } - - public override void Handle(CreateAccountCommand command) - { - var account = new Account(Guid.NewGuid()); - account.SetName(command.FirstName, command.LastName); - - repository.Save(account); - } - } -} \ No newline at end of file diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Commands/CreateAccountCommand.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/Commands/CreateAccountCommand.cs deleted file mode 100644 index da4fdc1..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Commands/CreateAccountCommand.cs +++ /dev/null @@ -1,10 +0,0 @@ -using SimpleCqrs.Commanding; - -namespace SimpleCQRSDemo.Commands -{ - public class CreateAccountCommand : ICommand - { - public string FirstName { get; set; } - public string LastName { get; set; } - } -} \ No newline at end of file diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Denormalizers/AccountReportDenormalizer.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/Denormalizers/AccountReportDenormalizer.cs deleted file mode 100644 index aee4a1b..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Denormalizers/AccountReportDenormalizer.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Linq; -using SimpleCqrs.Eventing; -using SimpleCQRSDemo.Events; -using SimpleCQRSDemo.FakeDb; - -namespace SimpleCQRSDemo.Denormalizers -{ - public class AccountReportDenormalizer : IHandleDomainEvents, - IHandleDomainEvents - { - private readonly FakeAccountTable accountTable; - - public AccountReportDenormalizer(FakeAccountTable accountTable) - { - this.accountTable = accountTable; - } - - public void Handle(AccountCreatedEvent domainEvent) - { - accountTable.Add(new FakeAccountTableRow {Id = domainEvent.AggregateRootId }); - } - - public void Handle(AccountNameSetEvent domainEvent) - { - var account = accountTable.Single(x => x.Id == domainEvent.AggregateRootId); - account.Name = domainEvent.FirstName + " " + domainEvent.LastName; - } - } -} \ No newline at end of file diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Domain/Account.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/Domain/Account.cs deleted file mode 100644 index ecbdedd..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Domain/Account.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using SimpleCqrs.Domain; -using SimpleCQRSDemo.Events; - -namespace SimpleCQRSDemo.Domain -{ - public class Account : AggregateRoot - { - public Account(Guid id) - { - Apply(new AccountCreatedEvent { AggregateRootId = id }); - } - - public void SetName(string firstName, string lastName) - { - Apply(new AccountNameSetEvent{ FirstName = firstName, LastName = lastName}); - } - - public void OnAccountCreated(AccountCreatedEvent evt) - { - Id = evt.AggregateRootId; - } - } -} \ No newline at end of file diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Events/AccountCreatedEvent.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/Events/AccountCreatedEvent.cs deleted file mode 100644 index 10663ec..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Events/AccountCreatedEvent.cs +++ /dev/null @@ -1,7 +0,0 @@ -using System; -using SimpleCqrs.Eventing; - -namespace SimpleCQRSDemo.Events -{ - public class AccountCreatedEvent : DomainEvent { } -} \ No newline at end of file diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Events/AccountNameSetEvent.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/Events/AccountNameSetEvent.cs deleted file mode 100644 index 1bb4b8d..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Events/AccountNameSetEvent.cs +++ /dev/null @@ -1,10 +0,0 @@ -using SimpleCqrs.Eventing; - -namespace SimpleCQRSDemo.Events -{ - public class AccountNameSetEvent : DomainEvent - { - public string FirstName { get; set; } - public string LastName { get; set; } - } -} \ No newline at end of file diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/FakeDb/FakeAccountTable.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/FakeDb/FakeAccountTable.cs deleted file mode 100644 index ec9d377..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/FakeDb/FakeAccountTable.cs +++ /dev/null @@ -1,7 +0,0 @@ -using System.Collections.Generic; - -namespace SimpleCQRSDemo.FakeDb -{ - public class FakeAccountTable : List - { } -} \ No newline at end of file diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/FakeDb/FakeAccountTableRow.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/FakeDb/FakeAccountTableRow.cs deleted file mode 100644 index 4753bbf..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/FakeDb/FakeAccountTableRow.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace SimpleCQRSDemo.FakeDb -{ - public class FakeAccountTableRow - { - public Guid Id { get; set; } - public string Name { get; set; } - } -} \ No newline at end of file diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Program.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/Program.cs deleted file mode 100644 index e7d6a36..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Program.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Collections; -using SimpleCqrs.Commanding; -using SimpleCQRSDemo.Commands; -using SimpleCQRSDemo.FakeDb; -using SimpleCQRSDemo.ReadModel; - -namespace SimpleCQRSDemo -{ - class Program - { - static void Main(string[] args) - { - - var runtime = new SampleRunTime(); - - runtime.Start(); - - // Infrastructure and fakes - var fakeAccountTable = new FakeAccountTable(); - runtime.ServiceLocator.Register(fakeAccountTable); // Create Fake-db - runtime.ServiceLocator.Register(new AccountReportReadService(fakeAccountTable)); - var commandBus = runtime.ServiceLocator.Resolve(); - - - // Create and send a couple of command - var cmdMarcus = new CreateAccountCommand { FirstName = "Marcus", LastName = "Hammarberg" }; - var cmdDarren = new CreateAccountCommand { FirstName = "Darren", LastName = "Cauthon" }; - var cmdTyrone = new CreateAccountCommand { FirstName = "Tyrone", LastName = "Groves" }; - commandBus.Send(cmdMarcus); - commandBus.Send(cmdDarren); - commandBus.Send(cmdTyrone); - - // Get the denormalized version of the data back from the read model - var accountReportReadModel = runtime.ServiceLocator.Resolve(); - Console.WriteLine("Accounts in database"); - Console.WriteLine("####################"); - foreach (var account in accountReportReadModel.GetAccounts()) - { - Console.WriteLine(" Id: {0} Name: {1}", account.Id, account.Name); - } - - - - runtime.Shutdown(); - - Console.ReadLine(); - } - } -} diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/Properties/AssemblyInfo.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/Properties/AssemblyInfo.cs deleted file mode 100644 index 5c4126c..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/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("SimpleCQRSDemo")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SimpleCQRSDemo")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[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("fc8c43fb-fe55-4f62-b63d-9c9eadf37238")] - -// 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/sample/SimpleCQRSDemo/SimpleCQRSDemo/ReadModel/AccountReadModel.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/ReadModel/AccountReadModel.cs deleted file mode 100644 index 786dee8..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/ReadModel/AccountReadModel.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace SimpleCQRSDemo.ReadModel -{ - public class AccountReadModel - { - public string Name { get; set; } - public Guid Id { get; set; } - } -} \ No newline at end of file diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/ReadModel/AccountReportReadService.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/ReadModel/AccountReportReadService.cs deleted file mode 100644 index 56be086..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/ReadModel/AccountReportReadService.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using SimpleCQRSDemo.FakeDb; - -namespace SimpleCQRSDemo.ReadModel -{ - public class AccountReportReadService - { - private FakeAccountTable fakeAccountDb; - - public AccountReportReadService(FakeAccountTable fakeAccountDb) - { - this.fakeAccountDb = fakeAccountDb; - } - - public IEnumerable GetAccounts() - { - return from a in fakeAccountDb - select new AccountReadModel { Id = a.Id, Name = a.Name }; - } - } -} \ No newline at end of file diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/SampleRunTime.cs b/sample/SimpleCQRSDemo/SimpleCQRSDemo/SampleRunTime.cs deleted file mode 100644 index f34bf8f..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/SampleRunTime.cs +++ /dev/null @@ -1,7 +0,0 @@ -using SimpleCqrs; -using SimpleCqrs.Unity; - -namespace SimpleCQRSDemo -{ - public class SampleRunTime : SimpleCqrsRuntime { } -} \ No newline at end of file diff --git a/sample/SimpleCQRSDemo/SimpleCQRSDemo/SimpleCQRSDemo.csproj b/sample/SimpleCQRSDemo/SimpleCQRSDemo/SimpleCQRSDemo.csproj deleted file mode 100644 index 91f5fa8..0000000 --- a/sample/SimpleCQRSDemo/SimpleCQRSDemo/SimpleCQRSDemo.csproj +++ /dev/null @@ -1,82 +0,0 @@ - - - - Debug - x86 - 8.0.30703 - 2.0 - {E9C9FB2C-9DF3-492F-BC94-47298AD92E14} - Exe - Properties - SimpleCQRSDemo - SimpleCQRSDemo - v4.0 - Client - 512 - - - x86 - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - x86 - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\binaries\servicelocators\unity\Microsoft.Practices.ServiceLocation.dll - - - False - ..\..\..\binaries\servicelocators\unity\Microsoft.Practices.Unity.dll - - - ..\..\..\binaries\SimpleCqrs.dll - - - ..\..\..\binaries\servicelocators\unity\SimpleCqrs.Unity.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/sample/SqlServerEventStore/SqlServerEventStore.sln b/sample/SqlServerEventStore/SqlServerEventStore.sln deleted file mode 100644 index 58baeb8..0000000 --- a/sample/SqlServerEventStore/SqlServerEventStore.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SqlServerEventStore", "SqlServerEventStore\SqlServerEventStore.csproj", "{EAE99B0F-509C-4268-BA1E-2D225745AC0B}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x86 = Debug|x86 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {EAE99B0F-509C-4268-BA1E-2D225745AC0B}.Debug|x86.ActiveCfg = Debug|x86 - {EAE99B0F-509C-4268-BA1E-2D225745AC0B}.Debug|x86.Build.0 = Debug|x86 - {EAE99B0F-509C-4268-BA1E-2D225745AC0B}.Release|x86.ActiveCfg = Release|x86 - {EAE99B0F-509C-4268-BA1E-2D225745AC0B}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/sample/SqlServerEventStore/SqlServerEventStore/Program.cs b/sample/SqlServerEventStore/SqlServerEventStore/Program.cs deleted file mode 100644 index 5f4c2d0..0000000 --- a/sample/SqlServerEventStore/SqlServerEventStore/Program.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SimpleCqrs.Commanding; -using SimpleCqrs.Domain; -using SimpleCqrs.Eventing; -using SimpleCqrs.EventStore.SqlServer; -using SimpleCqrs.EventStore.SqlServer.Serializers; - -namespace SqlServerEventStoreSample -{ - class Program - { - static void Main(string[] args) - { - var p = new Program(); - - p.DoBinarySerializedEvents(); - - p.DoJsonSerializedEvents(); - } - - void DoBinarySerializedEvents() { - var json = new BinarySampleRuntime(); - json.Start(); - - var id = Guid.NewGuid(); - - var serializer = new BinaryDomainEventSerializer(); - - var obj = serializer.Serialize(new FooCreatedEvent()); - - - - var root = new FooRoot(); - root.CreateMe(id); - - var repo = json.ServiceLocator.Resolve(); - - repo.Save(root); - - var newRoot = repo.GetById(id); - - Console.WriteLine(String.Format("Id : {0}, Type : {1}", newRoot.Id, newRoot.GetType())); - - json.Shutdown(); - } - - void DoJsonSerializedEvents() - { - var json = new JsonSampleRuntime(); - json.Start(); - - var id = Guid.NewGuid(); - - var root = new FooRoot(); - root.CreateMe(id); - var repo = json.ServiceLocator.Resolve(); - - repo.Save(root); - - var newRoot = repo.GetById(id); - - Console.WriteLine(String.Format("Id : {0}, Type : {1}", newRoot.Id, newRoot.GetType())); - json.Shutdown(); - } - } - - public class BinarySampleRuntime : SimpleCqrs.SimpleCqrsRuntime - { - protected override IEventStore GetEventStore(SimpleCqrs.IServiceLocator serviceLocator) { - var configuration = new SqlServerConfiguration("Server=(local)\\sqlexpress;Database=test_event_store;Trusted_Connection=True;", - "dbo", "binary_event_store"); - return new SqlServerEventStore(configuration, new BinaryDomainEventSerializer()); - } - } - - public class JsonSampleRuntime : SimpleCqrs.SimpleCqrsRuntime - { - protected override IEventStore GetEventStore(SimpleCqrs.IServiceLocator serviceLocator) - { - var configuration = new SqlServerConfiguration("Server=(local)\\sqlexpress;Database=test_event_store;Trusted_Connection=True;", - "dbo", "json_event_store"); - return new SqlServerEventStore(configuration, new JsonDomainEventSerializer()); - } - } - - [Serializable] - public class FooCreatedEvent : DomainEvent - { - public string Bar { get; set; } - } - - public class FooRoot : AggregateRoot - { - public void CreateMe(Guid id) - { - Apply(new FooCreatedEvent{AggregateRootId = id, Bar = "foobar"}); - } - - public void OnFooCreated(FooCreatedEvent domainEvent) - { - Id = domainEvent.AggregateRootId; - } - } -} diff --git a/sample/SqlServerEventStore/SqlServerEventStore/Properties/AssemblyInfo.cs b/sample/SqlServerEventStore/SqlServerEventStore/Properties/AssemblyInfo.cs deleted file mode 100644 index 7ea4d42..0000000 --- a/sample/SqlServerEventStore/SqlServerEventStore/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("SqlServerEventStore")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SqlServerEventStore")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[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("baa8dbd1-35f2-4874-a878-5067914fcd02")] - -// 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/sample/SqlServerEventStore/SqlServerEventStore/SqlServerEventStore.csproj b/sample/SqlServerEventStore/SqlServerEventStore/SqlServerEventStore.csproj deleted file mode 100644 index 495b110..0000000 --- a/sample/SqlServerEventStore/SqlServerEventStore/SqlServerEventStore.csproj +++ /dev/null @@ -1,75 +0,0 @@ - - - - Debug - x86 - 8.0.30703 - 2.0 - {EAE99B0F-509C-4268-BA1E-2D225745AC0B} - Exe - Properties - SqlServerEventStore - SqlServerEventStore - v4.0 - Client - 512 - - - x86 - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - x86 - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\binaries\servicelocators\unity\Microsoft.Practices.ServiceLocation.dll - - - ..\..\..\binaries\servicelocators\unity\Microsoft.Practices.Unity.dll - - - ..\..\..\src\EventStores\SimpleCqrs.EventStore.SqlServer\bin\Debug\ServiceStack.Text.dll - - - ..\..\..\binaries\SimpleCqrs.dll - - - ..\..\..\src\EventStores\SimpleCqrs.EventStore.SqlServer\bin\Debug\SimpleCqrs.EventStore.SqlServer.dll - - - ..\..\..\binaries\servicelocators\unity\SimpleCqrs.Unity.dll - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/.vs/SimpleCQRS/DesignTimeBuild/.dtbcache.v2 b/src/.vs/SimpleCQRS/DesignTimeBuild/.dtbcache.v2 new file mode 100644 index 0000000..eeae566 Binary files /dev/null and b/src/.vs/SimpleCQRS/DesignTimeBuild/.dtbcache.v2 differ diff --git a/src/.vs/SimpleCQRS/FileContentIndex/read.lock b/src/.vs/SimpleCQRS/FileContentIndex/read.lock new file mode 100644 index 0000000..e69de29 diff --git a/src/EventSourcingCQRS.EventStore.AzureTableStorage/AzureTableEventStore.cs b/src/EventSourcingCQRS.EventStore.AzureTableStorage/AzureTableEventStore.cs new file mode 100644 index 0000000..3c85a7f --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.AzureTableStorage/AzureTableEventStore.cs @@ -0,0 +1,117 @@ +using Azure.Data.Tables; +using EventSourcingCQRS.Eventing; + +namespace EventSourcingCQRS.EventStore.AzureTableStorage +{ + public class AzureTableEventStore : IEventStore + { + private readonly TableClient _client; + private readonly IDomainEventSerializer _eventSerializer; + + //BlobContainerClient blobContainerClient = new BlobContainerClient("UseDevelopmentStorage=true", "sample-container"); + //blobContainerClient.CreateIfNotExists(); + + public AzureTableEventStore(TableClient tableClient, IDomainEventSerializer eventDeserializer) + { + _client = tableClient ?? throw new ArgumentNullException(nameof(tableClient)); + _eventSerializer = eventDeserializer ?? throw new ArgumentNullException(nameof(eventDeserializer)); + } + + private static EventData SerializeEvents(DomainEvent @event, IDomainEventSerializer eventSerializer) + { + if (@event is null) + throw new ArgumentNullException(nameof(@event)); + + if (eventSerializer is null) + throw new ArgumentNullException(nameof(eventSerializer)); + + var json = eventSerializer.Serialize(@event); + //var data = Encoding.UTF8.GetBytes(json); + var data = json; + var eventType = @event.GetType(); + + return new EventData() + { + PartitionKey = @event.AggregateRootId.ToString(), + RowKey = @event.Sequence.ToString("00000000000"), + AggregateVersion = @event.Sequence, + EventType = eventType.AssemblyQualifiedName, + Data = data + }; + } + + private static DomainEvent DeserializeEvents(EventData @event, IDomainEventSerializer eventSerializer) + { + if (@event is null) + throw new ArgumentNullException(nameof(@event)); + + if (eventSerializer is null) + throw new ArgumentNullException(nameof(eventSerializer)); + + var domainEvent = eventSerializer.Deserialize(typeof(DomainEvent), @event.Data); + //var data = Encoding.UTF8.GetBytes(json); + + return domainEvent; + } + + public async Task Insert(IEnumerable domainEvents) + { + var cancellationToken = new CancellationToken(); + var newEvents = domainEvents.Select(evt => + { + var eventData = SerializeEvents(evt, _eventSerializer); + return new TableTransactionAction(TableTransactionActionType.Add, eventData); + }).ToArray(); + await _client.SubmitTransactionAsync(newEvents, cancellationToken) + .ConfigureAwait(false); + } + + public Task> GetDistinctAggregateRootsId() + { + throw new NotImplementedException(); + } + + public async Task> GetEvents(Guid aggregateRootId, int startSequence) + { + var filter = $"PartitionKey eq '{aggregateRootId.ToString()}'"; + var entities = _client.Query(filter); + + return entities.Select(entity => DeserializeEvents(entity, _eventSerializer)).ToList(); + } + + public Task> GetEventsUpToSequence(Guid aggregateRootId, int sequence) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByEventTypes(IEnumerable domainEventTypes) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByEventTypes(IEnumerable domainEventTypes, Guid aggregateRootId) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByEventTypesUpToSequence(IEnumerable domainEventTypes, Guid aggregateRootId, int sequence) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByEventTypes(IEnumerable domainEventTypes, DateTime startDate, DateTime endDate) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByCriteria(Dictionary criteria) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByCriteria(List criteria) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.AzureTableStorage/AzureTableSnapshotStore.cs b/src/EventSourcingCQRS.EventStore.AzureTableStorage/AzureTableSnapshotStore.cs new file mode 100644 index 0000000..06dcda1 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.AzureTableStorage/AzureTableSnapshotStore.cs @@ -0,0 +1,20 @@ +using EventSourcingCQRS.Domain; +using EventSourcingCQRS.Eventing; + +namespace EventSourcingCQRS.EventStore.AzureTableStorage +{ + public class AzureTableSnapshotStore : ISnapshotStore + { + public Task GetSnapshot(Guid aggregateRootId, CancellationToken cancellationToken) + { + Snapshot documents = null; + return Task.FromResult(documents) ; + + } + + public Task SaveSnapshot(TSnapshot snapshot, CancellationToken cancellationToken) where TSnapshot : Snapshot + { + throw new NotImplementedException(); + } + } +} diff --git a/src/EventSourcingCQRS.EventStore.AzureTableStorage/EventData.cs b/src/EventSourcingCQRS.EventStore.AzureTableStorage/EventData.cs new file mode 100644 index 0000000..b839565 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.AzureTableStorage/EventData.cs @@ -0,0 +1,37 @@ +using Azure; +using Azure.Data.Tables; + +namespace EventSourcingCQRS.EventStore.AzureTableStorage +{ + public record EventData : ITableEntity + { + /// + /// this is the Aggregate id + /// + public string PartitionKey { get; set; } + + /// + /// aggregate version on the event + /// + public string RowKey { get; set; } + + /// + /// the event type + /// + public string EventType { get; init; } + + /// + /// serialized event data + /// + //public byte[] Data { get; init; } + public string Data { get; init; } + + /// + /// aggregate version on the event + /// + public long AggregateVersion { get; init; } + + public DateTimeOffset? Timestamp { get; set; } + public ETag ETag { get; set; } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.AzureTableStorage/EventSourcingCQRS.EventStore.AzureTableStorage.csproj b/src/EventSourcingCQRS.EventStore.AzureTableStorage/EventSourcingCQRS.EventStore.AzureTableStorage.csproj new file mode 100644 index 0000000..e152b44 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.AzureTableStorage/EventSourcingCQRS.EventStore.AzureTableStorage.csproj @@ -0,0 +1,25 @@ + + + + net7.0 + enable + enable + True + Event Sourcing CQRS Azure Table Storage Event Store + A Azure Table Storage based event store for EventSourcingCQRS + https://github.com/LyndseyPaxton/EventSourcingCQRS + EventSourcing CQRS EventSourced Azure Table Storage + EventSourcingCQRS.EventStore.AzureTableStorage.Beta + $([System.DateTime]::Now.ToString("yyyy.MM.dd.HHmm")) + Lyndsey Paxton + Mental Monkey Software + + + + + + + + + + diff --git a/src/EventSourcingCQRS.EventStore.AzureTableStorage/IDomainEventSerializer.cs b/src/EventSourcingCQRS.EventStore.AzureTableStorage/IDomainEventSerializer.cs new file mode 100644 index 0000000..186d9ec --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.AzureTableStorage/IDomainEventSerializer.cs @@ -0,0 +1,10 @@ +using EventSourcingCQRS.Eventing; + +namespace EventSourcingCQRS.EventStore.AzureTableStorage +{ + public interface IDomainEventSerializer + { + string Serialize(DomainEvent domainEvent); + DomainEvent Deserialize(Type targetType, string serializedDomainEvent); + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.AzureTableStorage/JsonDomainEventSerializer.cs b/src/EventSourcingCQRS.EventStore.AzureTableStorage/JsonDomainEventSerializer.cs new file mode 100644 index 0000000..d4837fb --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.AzureTableStorage/JsonDomainEventSerializer.cs @@ -0,0 +1,80 @@ + + +using EventSourcingCQRS.Eventing; +using Newtonsoft.Json; + +namespace EventSourcingCQRS.EventStore.AzureTableStorage +{ + public class JsonDomainEventSerializer : IDomainEventSerializer + { + public string Serialize(DomainEvent domainEvent) + { + //// return $"Cannot find type '{domainEvent.GetType()}', yet the type is in the event store. Are you sure you haven't changed a class name or something arising from mental dullness?"; + //var options = new JsonSerializerOptions { WriteIndented = true }; + ////using var stream = new MemoryStream(); + ////JsonSerializer.Serialize(stream, domainEvent, options); + ////var reader = new StreamReader(stream); + ////var text = reader.ReadToEnd(); + ////return text; + + //return JsonSerializer.Serialize(domainEvent,domainEvent.GetType(), options); + + var settings = new Newtonsoft.Json.JsonSerializerSettings + { + TypeNameAssemblyFormatHandling = Newtonsoft.Json.TypeNameAssemblyFormatHandling.Simple, + TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects, + }; + + var json = JsonConvert.SerializeObject(domainEvent, settings); + + return json; + } + + public DomainEvent Deserialize(Type targetType, string serializedDomainEvent) + { + //var options = new JsonSerializerOptions + //{ + // IncludeFields=true, + // PropertyNameCaseInsensitive = true, + + //}; + //var domainEvent = JsonSerializer.Deserialize(serializedDomainEvent, targetType, options); + //return domainEvent as DomainEvent; + JsonSerializerSettings settings = new JsonSerializerSettings + { + ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver + { + NamingStrategy = new Newtonsoft.Json.Serialization.CamelCaseNamingStrategy() + }, + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + TypeNameHandling = TypeNameHandling.Auto + }; + + DomainEvent domainEvent = JsonConvert.DeserializeObject(serializedDomainEvent, settings); + + return domainEvent; + } + } + + public class BinaryDomainEventSerializer : IDomainEventSerializer + { + public string Serialize(DomainEvent domainEvent) + { + throw new NotImplementedException(); + + //var options = new JsonSerializerOptions { WriteIndented = true }; + //using var stream = new MemoryStream(); + //JsonSerializer.Serialize(stream, domainEvent, options); + //return Convert.ToBase64String(stream.ToArray()); + } + + public DomainEvent Deserialize(Type targetType, string serializedDomainEvent) + { + throw new NotImplementedException(); + //var formatter = new BinaryFormatter(); + //using var stream = new MemoryStream(Convert.FromBase64String(serializedDomainEvent)); + //var domainEvent = JsonSerializer.Deserialize(stream); + //return domainEvent as DomainEvent; + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.AzureTableStorage/ServiceCollectionExtensions.cs b/src/EventSourcingCQRS.EventStore.AzureTableStorage/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..216e8c3 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.AzureTableStorage/ServiceCollectionExtensions.cs @@ -0,0 +1,31 @@ +using Azure.Data.Tables; +using EventSourcingCQRS.Eventing; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace EventSourcingCQRS.EventStore.AzureTableStorage +{ + public static class ServiceCollectionExtensions + { + public static void AddAzureTableEventStore(this IServiceCollection services, IConfiguration configuration) + { + services + .AddSingleton(); + + services + .AddTransient(tc => + { + var connectionString = + "UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://localhost:10002"; + var tableClient = new TableClient(connectionString, "Events"); + tableClient.CreateIfNotExists(); + return tableClient; + }); + services + .AddTransient(); + + services + .AddTransient(); + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.CosmosDb.UnitTests/CosmosDbConnectionStringBuilderTests.cs b/src/EventSourcingCQRS.EventStore.CosmosDb.UnitTests/CosmosDbConnectionStringBuilderTests.cs new file mode 100644 index 0000000..8336ff5 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.CosmosDb.UnitTests/CosmosDbConnectionStringBuilderTests.cs @@ -0,0 +1,32 @@ +namespace EventSourcingCQRS.EventStore.CosmosDb.UnitTests +{ + [TestClass] + public class CosmosDbConnectionStringBuilderTests + { + [TestMethod] + public void ParseConnectionString_When_DatabaseName_Is_Present_Then_Returns_Value() + { + //Arrange + var connectionString = "DatabaseName=test"; + + //Act + var uut = CosmosDbConnectionStringBuilder.ParseConnectionString(connectionString); + + //Assert + Assert.AreEqual("test", uut.DatabaseName); + } + + [TestMethod] + public void ParseConnectionString_When_AccountKey_Is_Present_Then_Returns_Value() + { + //Arrange + var connectionString = "AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="; + + //Act + var uut = CosmosDbConnectionStringBuilder.ParseConnectionString(connectionString); + + //Assert + Assert.AreEqual("C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==", uut.AccountKey); + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.CosmosDb.UnitTests/EventSourcingCQRS.EventStore.CosmosDb.UnitTests.csproj b/src/EventSourcingCQRS.EventStore.CosmosDb.UnitTests/EventSourcingCQRS.EventStore.CosmosDb.UnitTests.csproj new file mode 100644 index 0000000..66d57dd --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.CosmosDb.UnitTests/EventSourcingCQRS.EventStore.CosmosDb.UnitTests.csproj @@ -0,0 +1,22 @@ + + + + net7.0 + enable + enable + + false + + + + + + + + + + + + + + diff --git a/src/EventSourcingCQRS.EventStore.CosmosDb.UnitTests/Usings.cs b/src/EventSourcingCQRS.EventStore.CosmosDb.UnitTests/Usings.cs new file mode 100644 index 0000000..ab67c7e --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.CosmosDb.UnitTests/Usings.cs @@ -0,0 +1 @@ +global using Microsoft.VisualStudio.TestTools.UnitTesting; \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbConfiguration.cs b/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbConfiguration.cs new file mode 100644 index 0000000..a8ee8e7 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbConfiguration.cs @@ -0,0 +1,14 @@ +namespace EventSourcingCQRS.EventStore.CosmosDb +{ + public class CosmosDbConfiguration + { + private readonly string _connectionString; + + public CosmosDbConfiguration(string connectionString) + { + this._connectionString = connectionString; + } + + public string ConnectionString => _connectionString; + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbConnectionStringBuilder.cs b/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbConnectionStringBuilder.cs new file mode 100644 index 0000000..b46725c --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbConnectionStringBuilder.cs @@ -0,0 +1,257 @@ +using System.Text.Json; + +namespace EventSourcingCQRS.EventStore.CosmosDb +{ + public class CosmosDbConnectionStringBuilder + + { + private string _accountEndpoint; + private string _accountKey; + private string _connectionMode; + private string _consistencyLevel; + private string _databaseName; + private int _gatewayModeMaxConnectionLimit; + private int _gatewayModeMaxRetryAttempts; + private int _gatewayModeMaxRetryWaitTimeInSeconds; + private int _maxConnectionLimit; + private int _retryAttemptsOnThrottledRequests; + private int _retryWaitTimeInSeconds; + private JsonSerializerOptions _serializerOptions; + private bool _useMultipleWriteLocations; + + public CosmosDbConnectionStringBuilder() + { + // Set default values for properties + this._connectionMode = "Direct"; + this._consistencyLevel = "Session"; + this._gatewayModeMaxConnectionLimit = 50; + this._gatewayModeMaxRetryAttempts = 0; + this._gatewayModeMaxRetryWaitTimeInSeconds = 30; + this._maxConnectionLimit = 50; + this._retryAttemptsOnThrottledRequests = 9; + this._retryWaitTimeInSeconds = 1; + this._serializerOptions = new JsonSerializerOptions(); + this._useMultipleWriteLocations = false; + } + + + + public string AccountEndpoint + { + get => this._accountEndpoint; + set => this._accountEndpoint = value; + } + + public string AccountKey + { + get => this._accountKey; + set => this._accountKey = value; + } + + public string ConnectionMode + { + get => this._connectionMode; + set => this._connectionMode = value; + } + + public string ConsistencyLevel + { + get => this._consistencyLevel; + set => this._consistencyLevel = value; + } + + public string DatabaseName + { + get => this._databaseName; + set => this._databaseName = value; + } + + public int GatewayModeMaxConnectionLimit + { + get => this._gatewayModeMaxConnectionLimit; + set => this._gatewayModeMaxConnectionLimit = value; + } + + public int GatewayModeMaxRetryAttempts + { + get => this._gatewayModeMaxRetryAttempts; + set => this._gatewayModeMaxRetryAttempts = value; + } + + public int GatewayModeMaxRetryWaitTimeInSeconds + { + get => this._gatewayModeMaxRetryWaitTimeInSeconds; + set => this._gatewayModeMaxRetryWaitTimeInSeconds = value; + } + + public int MaxConnectionLimit + { + get => this._maxConnectionLimit; + set => this._maxConnectionLimit = value; + } + + public int RetryAttemptsOnThrottledRequests + { + get => this._retryAttemptsOnThrottledRequests; + set => this._retryAttemptsOnThrottledRequests = value; + } + + public int RetryWaitTimeInSeconds + { + get => this._retryWaitTimeInSeconds; + set => this._retryWaitTimeInSeconds = value; + } + + public JsonSerializerOptions SerializerOptions + { + get => this._serializerOptions; + set => this._serializerOptions = value; + } + + public bool UseMultipleWriteLocations + { + get => this._useMultipleWriteLocations; + set => this._useMultipleWriteLocations = value; + } + + public static CosmosDbConnectionStringBuilder ParseConnectionString(string connectionString) + { + CosmosDbConnectionStringBuilder builder = new CosmosDbConnectionStringBuilder(); + + if (string.IsNullOrWhiteSpace(connectionString)) + { + throw new ArgumentException("Connection string cannot be null or empty.", nameof(connectionString)); + } + + string[] parts = connectionString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + + foreach (string part in parts) + { + //string[] keyValue = part.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); + + var keyValue = new string[2]; + var index = part.IndexOf("="); // Find the index of the first occurrence of the separator + if (index == -1) + { + throw new ArgumentException($"Invalid key-value pair: {part}", nameof(connectionString)); + } + else + { + + keyValue[0] = part.Substring(0, index); // Extract the substring before the separator + keyValue[1] = part.Substring(index + 1); // Extract the substring after the separator + } + + + var key = keyValue[0].Trim().ToLowerInvariant(); + var value = keyValue[1].Trim(); + + switch (key) + { + case "accountendpoint": + builder.AccountEndpoint = value; + break; + + case "accountkey": + builder.AccountKey = value; + break; + + case "connectionmode": + builder.ConnectionMode = value; + break; + + case "consistencylevel": + builder.ConsistencyLevel = value; + break; + + case "database": + case "databasename": + builder.DatabaseName = value; + break; + + case "gatewaymodemaxconnectionlimit": + if (!int.TryParse(value, out int gatewayModeMaxConnectionLimit)) + { + throw new ArgumentException($"Invalid value for {key}: {value}", nameof(connectionString)); + } + + builder.GatewayModeMaxConnectionLimit = gatewayModeMaxConnectionLimit; + break; + + case "gatewaymodemaxretryattempts": + if (!int.TryParse(value, out int gatewayModeMaxRetryAttempts)) + { + throw new ArgumentException($"Invalid value for {key}: {value}", nameof(connectionString)); + } + + builder.GatewayModeMaxRetryAttempts = gatewayModeMaxRetryAttempts; + break; + + case "gatewaymodemaxretrywaittimeinseconds": + if (!int.TryParse(value, out int gatewayModeMaxRetryWaitTimeInSeconds)) + { + throw new ArgumentException($"Invalid value for {key}: {value}", nameof(connectionString)); + } + + builder.GatewayModeMaxRetryWaitTimeInSeconds = gatewayModeMaxRetryWaitTimeInSeconds; + break; + + case "maxconnectionlimit": + if (!int.TryParse(value, out int maxConnectionLimit)) + { + throw new ArgumentException($"Invalid value for {key}: {value}", nameof(connectionString)); + } + + builder.MaxConnectionLimit = maxConnectionLimit; + break; + + case "retryattemptsonthrottledrequests": + if (!int.TryParse(value, out int retryAttemptsOnThrottledRequests)) + { + throw new ArgumentException($"Invalid value for {key}: {value}", nameof(connectionString)); + } + + builder.RetryAttemptsOnThrottledRequests = retryAttemptsOnThrottledRequests; + break; + + case "retrywaittimeinseconds": + if (!int.TryParse(value, out int retryWaitTimeInSeconds)) + { + throw new ArgumentException($"Invalid value for {key}: {value}", nameof(connectionString)); + } + + builder.RetryWaitTimeInSeconds = retryWaitTimeInSeconds; + break; + + //case "serializeroptions": + // try + // { + // builder.SerializerOptions = JsonSerializerOptions.Parse(value); + // } + // catch (JsonException ex) + // { + // throw new ArgumentException($"Invalid value for {key}: {value}. {ex.Message}", + // nameof(connectionString)); + // } + + // break; + + case "usemultiplewritelocations": + if (!bool.TryParse(value, out bool useMultipleWriteLocations)) + { + throw new ArgumentException($"Invalid value for {key}: {value}", nameof(connectionString)); + } + + builder.UseMultipleWriteLocations = useMultipleWriteLocations; + break; + default: + { + throw new Exception("value not recognised"); + } + } + } + return builder; + } + } +} + diff --git a/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbEventData.cs b/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbEventData.cs new file mode 100644 index 0000000..e9e4b1f --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbEventData.cs @@ -0,0 +1,78 @@ +using Azure; +using Newtonsoft.Json.Linq; + +namespace EventSourcingCQRS.EventStore.CosmosDb +{ + public record CosmosDbEventData + { + /// + /// this is the Aggregate id + /// + //public string PartitionKey { get; set; } + + public string Id { get; set; } + + /// + /// aggregate version on the event + /// + //public string RowKey { get; set; } + + /// + /// the event type + /// + public string EventType { get; init; } + + /// + /// serialized event data + /// + //public byte[] EventData { get; init; } + public JObject EventData { get; init; } + + /// + /// aggregate version on the event + /// + //public long AggregateVersion { get; init; } + + public DateTimeOffset? Timestamp { get; set; } + public ETag ETag { get; set; } + } +} + +//using Azure; + +//namespace EventSourcingCQRS.EventStore.CosmosDb +//{ +// public record CosmosDbEventData +// { +// /// +// /// this is the Aggregate id +// /// +// public string PartitionKey { get; set; } + +// public string Id{ get; set; } + +// /// +// /// aggregate version on the event +// /// +// public string RowKey { get; set; } + +// /// +// /// the event type +// /// +// public string EventType { get; init; } + +// /// +// /// serialized event data +// /// +// //public byte[] EventData { get; init; } +// public string EventData { get; init; } + +// /// +// /// aggregate version on the event +// /// +// public long AggregateVersion { get; init; } + +// public DateTimeOffset? Timestamp { get; set; } +// public ETag ETag { get; set; } +// } +//} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbEventStore.cs b/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbEventStore.cs new file mode 100644 index 0000000..34d9b9b --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbEventStore.cs @@ -0,0 +1,197 @@ +using EventSourcingCQRS.Eventing; +using Microsoft.Azure.Cosmos; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace EventSourcingCQRS.EventStore.CosmosDb +{ + public class CosmosDbEventStore : IEventStore + { + private readonly CosmosClient _client; + private readonly Database _database; + private readonly Container _container; + private readonly IDomainEventSerializer _eventSerializer; + + public CosmosDbEventStore(CosmosClient cosmosClient, IDomainEventSerializer eventSerializer, string databaseName, string containerName) + { + _client = cosmosClient ?? throw new ArgumentNullException(nameof(cosmosClient)); + _database = _client.GetDatabase(databaseName); + _container = _database.GetContainer(containerName); + _eventSerializer = eventSerializer ?? throw new ArgumentNullException(nameof(eventSerializer)); + } + + public CosmosDbEventStore(CosmosClient cosmosClient, IDomainEventSerializer eventSerializer, Database database, Container container) + { + _client = cosmosClient ?? throw new ArgumentNullException(nameof(cosmosClient)); + _database = database; + _container = container; + _eventSerializer = eventSerializer ?? throw new ArgumentNullException(nameof(eventSerializer)); + } + + private CosmosDbEventData SerializeEvents(DomainEvent @event)//, IDomainEventSerializer eventSerializer) + { + if (@event is null) + throw new ArgumentNullException(nameof(@event)); + + //if (eventSerializer is null) + // throw new ArgumentNullException(nameof(eventSerializer)); + + var json = _eventSerializer.Serialize(@event); + //var data = Encoding.UTF8.GetBytes(json); + var eventType = @event.GetType(); + + return new CosmosDbEventData() + { + //PartitionKey = @event.AggregateRootId.ToString(), + //RowKey = @event.Sequence.ToString("00000000000"), + //AggregateVersion = @event.Sequence, + Id = @event.Sequence.ToString("00000000000"), + EventType = eventType.AssemblyQualifiedName, + //EventData = json + EventData = JObject.Parse(json) + }; + } + + private DomainEvent DeserializeEvents(CosmosDbEventData cosmosDbEvent)//, IDomainEventSerializer eventSerializer) + { + if (cosmosDbEvent is null) + throw new ArgumentNullException(nameof(cosmosDbEvent)); + + //if (eventSerializer is null) + // throw new ArgumentNullException(nameof(eventSerializer)); + + //var domainEvent = eventSerializer.Deserialize(typeof(DomainEvent), @cosmosDbEvent.EventData); + var domainEvent = _eventSerializer.Deserialize(typeof(DomainEvent), cosmosDbEvent.EventData); + + return domainEvent; + } + + public async Task Insert(IEnumerable domainEvents) + { + //TODO: change method to work in a transaction + /* + * var items = new List(); + foreach (var json in jsonDocuments) + { + var item = new { Id = Guid.NewGuid().ToString(), EventData = json }; + items.Add(item); + } + + await _container.CreateTransactionalBatch(new PartitionKey(items[0].Id)) + .CreateItems(items) + .ExecuteAsync(); + */ + foreach (var domainEvent in domainEvents) + { + var json = SerializeEvents(domainEvent);//, _eventSerializer); + //var item = new { Id = Guid.NewGuid().ToString(), Data = json }; + await _container.CreateItemAsync(json); + } + } + + public async Task> GetEvents(Guid aggregateRootId, int startSequence) + { + + var events = new List(); + var query = new QueryDefinition("SELECT * FROM c WHERE c.eventData.AggregateRootId = @id") + .WithParameter("@id", aggregateRootId.ToString()); + var iterator = _container.GetItemQueryIterator(query); + + if (iterator.HasMoreResults) + { + var response = await iterator.ReadNextAsync(); + var item = response.FirstOrDefault(); + + if (item != null) + { + var type = item.EventType; + var data = item.EventData; + + try + { + events.Add(_eventSerializer.Deserialize(Type.GetType(type), data)); + } + catch (ArgumentNullException ex) + { + throw new Exception( + $"Cannot find type '{type.Split(',')[0]}', yet the type is in the event store. Are you sure you haven't changed a class name or something arising from mental dullness?", ex.InnerException); + } + + + + ////////var obj = JsonConvert.DeserializeObject(item.EventData.ToString()); + ////////events.Add(obj); + } + } + + return events; + } + + + //public async Task> GetEvents(Guid aggregateRootId, int startSequence) + //{ + + // var events = new List(); + // //var query = new QueryDefinition("SELECT * FROM c WHERE c.id = @id") + // var query = new QueryDefinition("SELECT * FROM c WHERE c.eventData.AggregateRootId = @id") + + // .WithParameter("@id", aggregateRootId.ToString()); + // var iterator = _container.GetItemQueryIterator(query); + + // if (iterator.HasMoreResults) + // { + // var response = await iterator.ReadNextAsync(); + // var item = response.FirstOrDefault(); + + // if (item != null) + // { + // var obj = JsonConvert.DeserializeObject(item.EventData.ToString()); + // events.Add(obj); + // } + // } + + // return events; + //} + + + public Task> GetDistinctAggregateRootsId() + { + throw new NotImplementedException(); + } + + public Task> GetEventsUpToSequence(Guid aggregateRootId, int sequence) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByEventTypes(IEnumerable domainEventTypes) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByEventTypes(IEnumerable domainEventTypes, Guid aggregateRootId) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByEventTypesUpToSequence(IEnumerable domainEventTypes, Guid aggregateRootId, int sequence) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByEventTypes(IEnumerable domainEventTypes, DateTime startDate, DateTime endDate) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByCriteria(Dictionary criteria) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByCriteria(List criteria) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbSnapshotStore.cs b/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbSnapshotStore.cs new file mode 100644 index 0000000..ddc1a98 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.CosmosDb/CosmosDbSnapshotStore.cs @@ -0,0 +1,20 @@ +using EventSourcingCQRS.Domain; +using EventSourcingCQRS.Eventing; + +namespace EventSourcingCQRS.EventStore.CosmosDb +{ + public class CosmosDbSnapshotStore : ISnapshotStore + { + public Task GetSnapshot(Guid aggregateRootId, CancellationToken cancellationToken) + { + Snapshot documents = null; + return Task.FromResult(documents) ; + + } + + public Task SaveSnapshot(TSnapshot snapshot, CancellationToken cancellationToken) where TSnapshot : Snapshot + { + throw new NotImplementedException(); + } + } +} diff --git a/src/EventSourcingCQRS.EventStore.CosmosDb/EventSourcingCQRS.EventStore.CosmosDb.csproj b/src/EventSourcingCQRS.EventStore.CosmosDb/EventSourcingCQRS.EventStore.CosmosDb.csproj new file mode 100644 index 0000000..0da2a34 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.CosmosDb/EventSourcingCQRS.EventStore.CosmosDb.csproj @@ -0,0 +1,29 @@ + + + + net7.0 + enable + enable + True + Event Sourcing CQRS Cosmos DB Event Store + A Cosmos DB based event store for EventSourcingCQRS + https://github.com/LyndseyPaxton/EventSourcingCQRS + EventSourcing CQRS EventSourced Cosmos DB + EventSourcingCQRS.EventStore.CosmosDb.Beta + $([System.DateTime]::Now.ToString("yyyy.MM.dd.HHmm")) + Lyndsey Paxton + Mental Monkey Software + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.CosmosDb/IDomainEventSerializer.cs b/src/EventSourcingCQRS.EventStore.CosmosDb/IDomainEventSerializer.cs new file mode 100644 index 0000000..bb43c66 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.CosmosDb/IDomainEventSerializer.cs @@ -0,0 +1,12 @@ +using EventSourcingCQRS.Eventing; +using Newtonsoft.Json.Linq; + +namespace EventSourcingCQRS.EventStore.CosmosDb +{ + public interface IDomainEventSerializer + { + string Serialize(DomainEvent domainEvent); + //DomainEvent Deserialize(Type targetType, string serializedDomainEvent); + DomainEvent Deserialize(Type targetType, JObject serializedDomainEvent); + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.CosmosDb/JsonDomainEventSerializer.cs b/src/EventSourcingCQRS.EventStore.CosmosDb/JsonDomainEventSerializer.cs new file mode 100644 index 0000000..22bef13 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.CosmosDb/JsonDomainEventSerializer.cs @@ -0,0 +1,110 @@ +//using ServiceStack.Text; +//using SimpleCqrs.Eventing; + +using EventSourcingCQRS.Eventing; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +//using System.Text.Json; + +//using JsonSerializer = System.Text.Json.JsonSerializer; + +namespace EventSourcingCQRS.EventStore.CosmosDb +{ + public class JsonDomainEventSerializer : IDomainEventSerializer + { + public string Serialize(DomainEvent domainEvent) + { + //// return $"Cannot find type '{domainEvent.GetType()}', yet the type is in the event store. Are you sure you haven't changed a class name or something arising from mental dullness?"; + //var options = new JsonSerializerOptions { WriteIndented = true }; + ////using var stream = new MemoryStream(); + ////JsonSerializer.Serialize(stream, domainEvent, options); + ////var reader = new StreamReader(stream); + ////var text = reader.ReadToEnd(); + ////return text; + + //return JsonSerializer.Serialize(domainEvent,domainEvent.GetType(), options); + + + + var settings = new Newtonsoft.Json.JsonSerializerSettings + { + TypeNameAssemblyFormatHandling = Newtonsoft.Json.TypeNameAssemblyFormatHandling.Simple, + TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects, + }; + + var json = JsonConvert.SerializeObject(domainEvent, settings); + + return json; + + } + + public DomainEvent Deserialize(Type targetType, JObject serializedDomainEvent) + { + JsonSerializerSettings settings = new JsonSerializerSettings + { + ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver + { + NamingStrategy = new Newtonsoft.Json.Serialization.CamelCaseNamingStrategy() + }, + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + TypeNameHandling = TypeNameHandling.Auto + }; + + var eventString = serializedDomainEvent.ToString(); + DomainEvent domainEvent = JsonConvert.DeserializeObject(eventString, settings); + return domainEvent; + } + + public DomainEvent Deserialize(Type targetType, string serializedDomainEvent) + { + //var options = new JsonSerializerOptions + //{ + // IncludeFields=true, + // PropertyNameCaseInsensitive = true, + + //}; + //var domainEvent = JsonSerializer.Deserialize(serializedDomainEvent, targetType, options); + //return domainEvent as DomainEvent; + JsonSerializerSettings settings = new JsonSerializerSettings + { + ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver + { + NamingStrategy = new Newtonsoft.Json.Serialization.CamelCaseNamingStrategy() + }, + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + TypeNameHandling = TypeNameHandling.Auto + }; + + DomainEvent domainEvent = JsonConvert.DeserializeObject(serializedDomainEvent, settings); + return domainEvent; + } + } + + public class BinaryDomainEventSerializer : IDomainEventSerializer + { + public string Serialize(DomainEvent domainEvent) + { + throw new NotImplementedException(); + + //var options = new JsonSerializerOptions { WriteIndented = true }; + //using var stream = new MemoryStream(); + //JsonSerializer.Serialize(stream, domainEvent, options); + //return Convert.ToBase64String(stream.ToArray()); + } + + public DomainEvent Deserialize(Type targetType, JObject serializedDomainEvent) + { + throw new NotImplementedException(); + } + + public DomainEvent Deserialize(Type targetType, string serializedDomainEvent) + { + throw new NotImplementedException(); + //var formatter = new BinaryFormatter(); + //using var stream = new MemoryStream(Convert.FromBase64String(serializedDomainEvent)); + //var domainEvent = JsonSerializer.Deserialize(stream); + //return domainEvent as DomainEvent; + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.CosmosDb/ServiceCollectionExtensions.cs b/src/EventSourcingCQRS.EventStore.CosmosDb/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..cf13399 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.CosmosDb/ServiceCollectionExtensions.cs @@ -0,0 +1,77 @@ +using EventSourcingCQRS.Eventing; +using Microsoft.Azure.Cosmos; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace EventSourcingCQRS.EventStore.CosmosDb +{ + public static class ServiceCollectionExtensions + { + public static void AddCosmosDbEventStore(this IServiceCollection services, IConfiguration configuration) + { + services + .AddSingleton(); + + var cosmosClientOptions = new CosmosClientOptions() + { + //Allow insecure (non https) access to the Emulator + HttpClientFactory = () => + { + HttpMessageHandler httpMessageHandler = new HttpClientHandler() + { + ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator + }; + + return new HttpClient(httpMessageHandler); + }, + ConnectionMode = ConnectionMode.Gateway, + SerializerOptions = new CosmosSerializationOptions() + { + PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase + } + }; + + services + .AddSingleton(s => + new CosmosDbConfiguration( + configuration.GetConnectionString("EventStore"))); + + services + .AddSingleton(serviceProvider => + { + var cosmosDbConfig = new CosmosDbConfiguration(configuration.GetConnectionString("EventStore")); + var cosmosDbConnectionStringBuilder = CosmosDbConnectionStringBuilder.ParseConnectionString(cosmosDbConfig.ConnectionString); + var cosmosClient = new CosmosClient(cosmosDbConfig.ConnectionString, cosmosClientOptions); + var databaseName = cosmosDbConnectionStringBuilder.DatabaseName; + + //The Cosmos library only has async methods which we need to run from here, a sync method + // The solution chosen is documented on stack overflow + //https://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c + var databaseResponse = Task.Run(() => cosmosClient.CreateDatabaseIfNotExistsAsync(databaseName)).GetAwaiter().GetResult(); + + var database = cosmosClient.GetDatabase(databaseName); + + //////var uniqueKey = new UniqueKey(); + //////uniqueKey.Paths.Add("/eventData/Sequence"); + var containerProperties = new ContainerProperties() + { + Id = "Events", //Equates to table name + //////UniqueKeyPolicy = new UniqueKeyPolicy() + //////{ + ////// UniqueKeys = { uniqueKey } + //////}, + PartitionKeyPath = "/eventData/AggregateRootId" + }; + + var containerResponse = Task.Run(() => database.CreateContainerIfNotExistsAsync(containerProperties)).GetAwaiter().GetResult(); + + var container = database.GetContainer(containerProperties.Id); + var serialiser = new JsonDomainEventSerializer(); + return new CosmosDbEventStore(cosmosClient, serialiser, database, container); + }); + + services + .AddTransient(); + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.MongoDb/EventSourcingCQRS.EventStore.MongoDb.csproj b/src/EventSourcingCQRS.EventStore.MongoDb/EventSourcingCQRS.EventStore.MongoDb.csproj new file mode 100644 index 0000000..02f5cdd --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.MongoDb/EventSourcingCQRS.EventStore.MongoDb.csproj @@ -0,0 +1,53 @@ + + + + net7.0 + enable + enable + True + Event Sourcing CQRS MongoDB Event Store + A MongoDb based event store for EventSourcingCQRS + https://github.com/LyndseyPaxton/EventSourcingCQRS + EventSourcing CQRS EventSourced MongoDb + EventSourcingCQRS.EventStore.MongoDb.Beta + $([System.DateTime]::Now.ToString("yyyy.MM.dd.HHmm")) + Lyndsey Paxton + Mental Monkey Software + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/EventSourcingCQRS.EventStore.MongoDb/IMongoEventStoreConfiguration.cs b/src/EventSourcingCQRS.EventStore.MongoDb/IMongoEventStoreConfiguration.cs new file mode 100644 index 0000000..611704b --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.MongoDb/IMongoEventStoreConfiguration.cs @@ -0,0 +1,7 @@ +namespace EventSourcingCQRS.EventStore.MongoDb +{ + public interface IMongoEventStoreConfiguration + { + void Configure(); + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.MongoDb/IMongoSnapshotStoreConfiguration.cs b/src/EventSourcingCQRS.EventStore.MongoDb/IMongoSnapshotStoreConfiguration.cs new file mode 100644 index 0000000..2194e94 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.MongoDb/IMongoSnapshotStoreConfiguration.cs @@ -0,0 +1,7 @@ +namespace EventSourcingCQRS.EventStore.MongoDb +{ + public interface IMongoSnapshotStoreConfiguration + { + void Configure(); + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.MongoDb/MongoEventStore.cs b/src/EventSourcingCQRS.EventStore.MongoDb/MongoEventStore.cs new file mode 100644 index 0000000..fe48c9b --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.MongoDb/MongoEventStore.cs @@ -0,0 +1,201 @@ +using EventSourcingCQRS.Eventing; +using EventSourcingCQRS.EventStore.MongoDb.RetryPolicies; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using MongoDB.Bson; +using MongoDB.Driver; +using Polly.Registry; +using Polly.Wrap; + +namespace EventSourcingCQRS.EventStore.MongoDb +{ + public class MongoEventStore : IEventStore + { + private const string EventsCollection = "Events"; + private readonly string _className; + private readonly ILogger _logger; + private readonly IMongoCollection _mongoCollection; + private readonly IMongoDatabase _mongoDatabase; + private readonly AsyncPolicyWrap _asyncRetryPolicy; + + public MongoEventStore( + ILogger logger, + IMongoClient mongoClient, + IMongoEventStoreConfiguration mongoEventStoreConfiguration, + IConfiguration configuration, + IReadOnlyPolicyRegistry policyRegistry) + { + _className = GetType().FullName; + _logger = logger; + var databaseName = configuration.GetSection("Databases:EventStore").Value; + mongoEventStoreConfiguration.Configure(); + _mongoDatabase = mongoClient.GetDatabase(databaseName); + _mongoCollection = _mongoDatabase.GetCollection(EventsCollection); + _asyncRetryPolicy = policyRegistry.Get(EventStoreRetryPolicy.RetryPolicyName); + } + + public async Task> GetDistinctAggregateRootsId() + { + var filter = new BsonDocument(); + var documents = await _mongoCollection.DistinctAsync("AggregateRootId", filter); + return documents.ToList(); + } + + public async Task> GetEvents(Guid aggregateRootId, int startSequence) + { + var filter = Builders.Filter.Eq("AggregateRootId", aggregateRootId); + filter &= Builders.Filter.Gt("Sequence", startSequence); + + List documents = null; + await _asyncRetryPolicy.ExecuteAsync(async () => + { + documents = await _mongoCollection.Find(filter).ToListAsync(); + }); + return documents; + } + + public async Task> GetEventsUpToSequence(Guid aggregateRootId, int sequence) + { + var filter = Builders.Filter.Eq("AggregateRootId", aggregateRootId); + filter &= Builders.Filter.Lte("Sequence", sequence); + List documents = null; + await _asyncRetryPolicy.ExecuteAsync(async () => + { + documents = await _mongoCollection.Find(filter).ToListAsync(); + }); + return documents; + } + + public async Task Insert(IEnumerable domainEvents) + { + var enumerable = domainEvents.ToList(); + _logger.LogInformation("{ClassName} Inserting {NumberOfEvents} Events ", _className, enumerable.Count()); + foreach (var e in enumerable) + { + _logger.LogInformation("{ClassName} Inserting {@Event}", _className, e); + } + + await _asyncRetryPolicy.ExecuteAsync(async () => + { + await _mongoCollection.InsertManyAsync(enumerable); + }); + } + + public async Task> GetEventsByEventTypes(IEnumerable domainEventTypes) + { + var filter = Builders.Filter.In("_t", domainEventTypes.Select(t => t.Name).ToArray()); + List documents = null; + await _asyncRetryPolicy.ExecuteAsync(async () => + { + documents = await _mongoDatabase.GetCollection(EventsCollection).Find(filter).ToListAsync(); + }); + return documents; + } + + public async Task> GetEventsByEventTypes(IEnumerable domainEventTypes, + Guid aggregateRootId) + { + var filter = Builders.Filter.Eq("AggregateRootId", aggregateRootId); + filter &= Builders.Filter.In("_t", domainEventTypes.Select(t => t.Name).ToArray()); + List documents = null; + await _asyncRetryPolicy.ExecuteAsync(async () => + { + documents = await _mongoDatabase.GetCollection(EventsCollection).Find(filter).ToListAsync(); + }); + return documents; + } + + public async Task> GetEventsByEventTypesUpToSequence(IEnumerable domainEventTypes, Guid aggregateRootId, int sequence) + { + var eventsByType = await GetEventsByEventTypes(domainEventTypes, aggregateRootId); + return eventsByType.TakeWhile(eventType => eventType.Sequence <= sequence).ToList(); + } + + public async Task> GetEventsByEventTypes(IEnumerable domainEventTypes, + DateTime startDate, DateTime endDate) + { + var filter = Builders.Filter.Gt("EventDate", startDate); + filter &= Builders.Filter.Lt("EventDate", endDate); + filter &= Builders.Filter.In("_t", domainEventTypes.Select(t => t.Name).ToArray()); + List documents = null; + await _asyncRetryPolicy.ExecuteAsync(async () => + { + documents = await _mongoDatabase.GetCollection(EventsCollection).Find(filter).ToListAsync(); + }); + return documents; + } + + public async Task> GetEventsByCriteria(Dictionary criteria) + { + var filter = Builders.Filter.Empty; + + foreach (var (key, value) in criteria) + { + filter &= Builders.Filter.Eq(key, value); + } + List documents = null; + await _asyncRetryPolicy.ExecuteAsync(async () => + { + documents = await _mongoDatabase.GetCollection(EventsCollection).Find(filter).ToListAsync(); + }); + return documents; + } + + public async Task> GetEventsByCriteria(List criteria) + { + var filter = Builders.Filter.Empty; + + foreach (var item in criteria) + { + + //var itemType = item.GetType(); + var itemType = typeof(EventQueryCriteria<>); + var genericTypeArguments = item.GetType().GenericTypeArguments; + if (genericTypeArguments.Length > 1) + { + throw new Exception("Multiple generic type arguments are not supported."); + } + + var genericTypeArgument = genericTypeArguments[0]; + var itemGeneric = itemType.MakeGenericType(genericTypeArguments); + var instance = Activator.CreateInstance(itemGeneric); + instance = item; + + var value = ((dynamic)Convert.ChangeType(item, itemGeneric)).Value; + + filter &= Builders.Filter.Eq(item.Name, value); + } + List documents = null; + await _asyncRetryPolicy.ExecuteAsync(async () => + { + documents = await _mongoDatabase.GetCollection(EventsCollection).Find(filter).ToListAsync(); + }); + return documents; + } + + public async Task> GetEventsBySelector(BsonDocument selector) + { + List documents = null; + await _asyncRetryPolicy.ExecuteAsync(async () => + { + documents = await _mongoDatabase.GetCollection(EventsCollection).Find(selector).ToListAsync(); + }); + return documents; + } + + public async Task> GetEventsBySelector(BsonDocument selector, int skip, int limit, + CancellationToken cancellationToken) + { + var documents = new List(); + await _asyncRetryPolicy.ExecuteAsync(async () => + { + await _mongoDatabase.GetCollection(EventsCollection) + .Find(selector) + .Skip(skip) + .Limit(limit) + .ForEachAsync(document => { documents.Add(document); }, cancellationToken); + }); + return documents; + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.MongoDb/MongoEventStoreConfiguration.cs b/src/EventSourcingCQRS.EventStore.MongoDb/MongoEventStoreConfiguration.cs new file mode 100644 index 0000000..0c18e93 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.MongoDb/MongoEventStoreConfiguration.cs @@ -0,0 +1,30 @@ +using EventSourcingCQRS.Domain; +using MongoDB.Bson.Serialization; +using MongoDB.Bson.Serialization.Conventions; + +namespace EventSourcingCQRS.EventStore.MongoDb +{ + public class MongoEventStoreConfiguration : IMongoEventStoreConfiguration + { + private readonly ITypeCatalog _typeCatalog; + + public MongoEventStoreConfiguration(ITypeCatalog typeCatalog) + { + _typeCatalog = typeCatalog; + } + + public void Configure() + { + var conventionPack = new ConventionPack { new IgnoreExtraElementsConvention(true) }; + ConventionRegistry.Register("IgnoreExtraElements", conventionPack, type => true); + + foreach (var t in _typeCatalog.LoadedTypes) + { + if (t.FullName != null && t.FullName.EndsWith("Event", StringComparison.InvariantCultureIgnoreCase)) + { + BsonClassMap.LookupClassMap(t); + } + } + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.MongoDb/MongoSnapshotStore.cs b/src/EventSourcingCQRS.EventStore.MongoDb/MongoSnapshotStore.cs new file mode 100644 index 0000000..ae55b74 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.MongoDb/MongoSnapshotStore.cs @@ -0,0 +1,61 @@ +using EventSourcingCQRS.Domain; +using EventSourcingCQRS.Eventing; +using EventSourcingCQRS.EventStore.MongoDb.RetryPolicies; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using MongoDB.Driver; +using Polly.Registry; +using Polly.Wrap; + +namespace EventSourcingCQRS.EventStore.MongoDb +{ + public class MongoSnapshotStore : ISnapshotStore + { + private const string SnapshotsCollection = "Snapshots"; + + private readonly string _className; + private readonly ILogger _logger; + private readonly IMongoCollection _mongoCollection; + private readonly IMongoDatabase _mongoDatabase; + private readonly AsyncPolicyWrap _asyncRetryPolicy; + + public MongoSnapshotStore(ILogger logger, IMongoClient mongoClient, + IMongoSnapshotStoreConfiguration mongoEventStoreConfiguration, IConfiguration configuration, + IReadOnlyPolicyRegistry policyRegistry) + { + _className = GetType().FullName; + _logger = logger; + var databaseName = configuration.GetSection("Databases:EventStore").Value; + mongoEventStoreConfiguration.Configure(); + _mongoDatabase = mongoClient.GetDatabase(databaseName); + _mongoCollection = _mongoDatabase + .GetCollection(SnapshotsCollection); + _asyncRetryPolicy = policyRegistry.Get(EventStoreRetryPolicy.RetryPolicyName); + } + + public async Task GetSnapshot(Guid aggregateRootId, CancellationToken cancellationToken) + { + Snapshot documents = null; + await _asyncRetryPolicy.ExecuteAsync(async () => + { + documents = await _mongoCollection + .Find(x => x.AggregateRootId == aggregateRootId) + .SingleOrDefaultAsync(cancellationToken); + }); + return documents; + } + + public async Task SaveSnapshot(TSnapshot snapshot, CancellationToken cancellationToken) where TSnapshot : Snapshot + { + var snapshotsCollection = _mongoDatabase.GetCollection("Snapshots"); + var replaceOptions = new ReplaceOptions + { + IsUpsert = true + }; + var filter = Builders.Filter.Eq("AggregateRootId", snapshot.AggregateRootId); + await snapshotsCollection.ReplaceOneAsync(filter, snapshot, replaceOptions, cancellationToken); + } + + + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.MongoDb/MongoSnapshotStoreConfiguration.cs b/src/EventSourcingCQRS.EventStore.MongoDb/MongoSnapshotStoreConfiguration.cs new file mode 100644 index 0000000..d005220 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.MongoDb/MongoSnapshotStoreConfiguration.cs @@ -0,0 +1,38 @@ +using EventSourcingCQRS.Domain; +using MongoDB.Bson.Serialization; +using MongoDB.Bson.Serialization.Conventions; + +namespace EventSourcingCQRS.EventStore.MongoDb +{ + public class MongoSnapshotStoreConfiguration : IMongoSnapshotStoreConfiguration + { + private readonly ITypeCatalog _typeCatalog; + + public MongoSnapshotStoreConfiguration(ITypeCatalog typeCatalog) + { + _typeCatalog = typeCatalog; + } + + public void Configure() + { + var conventionPack = new ConventionPack { new IgnoreExtraElementsConvention(true) }; + ConventionRegistry.Register("IgnoreExtraElements", conventionPack, type => true); + + var snapShotters = _typeCatalog.LoadedTypes.Where(t => + t.FullName != null && t.FullName.EndsWith("Snapshot", StringComparison.InvariantCultureIgnoreCase)); + + foreach (var t in snapShotters) + { + BsonClassMap.LookupClassMap(t); + } + + //foreach (var t in _typeCatalog.LoadedTypes) + //{ + // if (t.FullName != null && t.FullName.EndsWith("Snapshot", StringComparison.InvariantCultureIgnoreCase)) + // { + // BsonClassMap.LookupClassMap(t); + // } + //} + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.MongoDb/RetryPolicies/EventStoreRetryPolicy.cs b/src/EventSourcingCQRS.EventStore.MongoDb/RetryPolicies/EventStoreRetryPolicy.cs new file mode 100644 index 0000000..aed6309 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.MongoDb/RetryPolicies/EventStoreRetryPolicy.cs @@ -0,0 +1,224 @@ +using Microsoft.Extensions.Logging; +using MongoDB.Bson; +using MongoDB.Driver; +using Polly; + +namespace EventSourcingCQRS.EventStore.MongoDb.RetryPolicies +{ + public class EventStoreRetryPolicy + { + // This set of policies is based on this article, with customisation to allow for logging + // https://www.nuomiphp.com/eplan/en/10737.html + // + private readonly ILogger _logger; + public static string RetryPolicyName => $"{nameof(EventStoreRetryPolicy)}Name"; + + public const int HttpThrottleErrorCode = 429; + public const int HttpServiceIsUnavailable = 1; + public const int HttpOperationExceededTimeLimit = 50; + public const int RateLimitCode = 16500; + public const string RetryAfterToken = "RetryAfterMs="; + public const int MaxRetries = 10; + public static readonly int RetryAfterTokenLength = RetryAfterToken.Length; + + private static readonly Random JitterSeed = new Random(); + + public EventStoreRetryPolicy(ILogger logger) + { + _logger = logger; + } + + public IAsyncPolicy GetPolicy() + { + return Policy.WrapAsync( + MongoCommandExceptionPolicy(), + ExecutionTimeoutPolicy(), + MongoWriteExceptionPolicy(), + MongoBulkWriteExceptionPolicy()); + } + + public IAsyncPolicy MongoCommandExceptionPolicy() + { + return Policy + .Handle(e => + { + if (e.Code != RateLimitCode || !(e.Result is BsonDocument bsonDocument)) + { + return false; + } + + if (bsonDocument.TryGetValue("StatusCode", out var statusCode) && statusCode.IsInt32) + { + switch (statusCode.AsInt32) + { + case HttpThrottleErrorCode: + case HttpServiceIsUnavailable: + case HttpOperationExceededTimeLimit: + return true; + + default: + return false; + } + } + + if (bsonDocument.TryGetValue("IsValid", out var isValid) && isValid.IsBoolean) + { + return isValid.AsBoolean; + } + + return true; + }) + .WaitAndRetryAsync( + retryCount: MaxRetries, + DefaultSleepDurationProviderWithJitter, + onRetryAsync: (exception, timeSpan, retryCount, context) => + { + var methodThatRaisedException = string.Empty; + if (context.ContainsKey("methodName")) + { + methodThatRaisedException = context["methodName"].ToString(); + } + _logger.LogWarning( + exception, + "Error talking to Event store database in {methodThatRaisedException}, retrying after {RetryTimeSpan}. Retry attempt {RetryCount}", + timeSpan, retryCount, methodThatRaisedException + + ); + return Task.CompletedTask; + } + ); + } + + public IAsyncPolicy ExecutionTimeoutPolicy() + { + return Policy + .Handle(e => + e.Code == RateLimitCode || e.Code == HttpOperationExceededTimeLimit + ) + .WaitAndRetryAsync( + retryCount: MaxRetries, + DefaultSleepDurationProviderWithJitter, + onRetryAsync: (exception, timeSpan, retryCount, context) => + { + var methodThatRaisedException = string.Empty; + if (context.ContainsKey("methodName")) + { + methodThatRaisedException = context["methodName"].ToString(); + } + _logger.LogWarning( + exception, + "Error talking to Event store database in {methodThatRaisedException}, retrying after {RetryTimeSpan}. Retry attempt {RetryCount}", + timeSpan, retryCount, methodThatRaisedException + + ); + return Task.CompletedTask; + }); + } + + public IAsyncPolicy MongoWriteExceptionPolicy() + { + return Policy + .Handle(e => + { + return e.WriteError?.Code == RateLimitCode + || (e.InnerException is MongoBulkWriteException bulkException && + bulkException.WriteErrors.Any(error => error.Code == RateLimitCode)); + }) + .WaitAndRetryAsync( + retryCount: MaxRetries, + sleepDurationProvider: (retryAttempt, e, ctx) => + { + var timeToWaitInMs = ExtractTimeToWait(e.Message); + if (!timeToWaitInMs.HasValue && e.InnerException != null) + { + timeToWaitInMs = ExtractTimeToWait(e.InnerException.Message); + } + + return timeToWaitInMs ?? DefaultSleepDurationProviderWithJitter(retryAttempt); + }, + onRetryAsync: (exception, timeSpan, retryCount, context) => + { + var methodThatRaisedException = string.Empty; + if (context.ContainsKey("methodName")) + { + methodThatRaisedException = context["methodName"].ToString(); + } + _logger.LogWarning( + exception, + "Error talking to Event store database in {methodThatRaisedException}, retrying after {RetryTimeSpan}. Retry attempt {RetryCount}", + timeSpan, retryCount, methodThatRaisedException + + ); + return Task.CompletedTask; + }); + } + + public IAsyncPolicy MongoBulkWriteExceptionPolicy() + { + return Policy + .Handle(e => + { + return e.WriteErrors.Any(error => error.Code == RateLimitCode); + }) + .WaitAndRetryAsync( + retryCount: MaxRetries, + sleepDurationProvider: (retryAttempt, e, ctx) => + { + var timeToWaitInMs = ExtractTimeToWait(e.Message); + return timeToWaitInMs ?? DefaultSleepDurationProviderWithJitter(retryAttempt); + }, + onRetryAsync: (exception, timeSpan, retryCount, context) => + { + var methodThatRaisedException = string.Empty; + if (context.ContainsKey("methodName")) + { + methodThatRaisedException = context["methodName"].ToString(); + } + _logger.LogWarning( + exception, + "Error talking to Event store database in {methodThatRaisedException}, retrying after {RetryTimeSpan}. Retry attempt {RetryCount}", + timeSpan, retryCount, methodThatRaisedException + + ); + return Task.CompletedTask; + }); + } + + /// + /// It doesn't seem like RetryAfterMs is a property value - so unfortunately, we have to extract it from a string... (crazy??!) + /// + private static TimeSpan? ExtractTimeToWait(string messageToParse) + { + var retryPos = messageToParse.IndexOf(RetryAfterToken, StringComparison.OrdinalIgnoreCase); + if (retryPos < 0) + { + return default; + } + + retryPos += RetryAfterTokenLength; + var endPos = messageToParse.IndexOf(',', retryPos); + if (endPos <= 0) + { + return default; + } + + var timeToWaitInMsString = messageToParse.Substring(retryPos, endPos - retryPos); + if (int.TryParse(timeToWaitInMsString, out var timeToWaitInMs)) + { + return TimeSpan.FromMilliseconds(timeToWaitInMs) + + TimeSpan.FromMilliseconds(JitterSeed.Next(100, 1000)); + } + + return default; + } + + public static Func SleepDurationProviderWithJitter(double exponentialBackoffInSeconds, int maxBackoffTimeInSeconds) => + retryAttempt => + TimeSpan.FromSeconds(Math.Min(Math.Pow(exponentialBackoffInSeconds, retryAttempt), + maxBackoffTimeInSeconds)) // exponential back-off: 2, 4, 8 etc + + TimeSpan.FromMilliseconds(JitterSeed.Next(0, 1000)); // plus some jitter: up to 1 second + + public static readonly Func DefaultSleepDurationProviderWithJitter = + SleepDurationProviderWithJitter(1.5, 23); + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.MongoDb/ServiceCollectionExtensions.cs b/src/EventSourcingCQRS.EventStore.MongoDb/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..b6e3198 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.MongoDb/ServiceCollectionExtensions.cs @@ -0,0 +1,38 @@ +using EventSourcingCQRS.Eventing; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using MongoDB.Bson.Serialization.Serializers; +using MongoDB.Bson.Serialization; +using MongoDB.Bson; +using MongoDB.Driver; + +namespace EventSourcingCQRS.EventStore.MongoDb +{ + public static class ServiceCollectionExtensions + { + public static void AddMongoDbEventStore(this IServiceCollection services, IConfiguration configuration) + { + // MongoDB STUFF + //https://stackoverflow.com/questions/63443445/trouble-with-mongodb-c-sharp-driver-when-performing-queries-using-guidrepresenta + BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3; + BsonSerializer + .RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard)); + + services + .AddSingleton(s => + new MongoClient( + configuration.GetConnectionString( + "EventStore"))); + services + .AddSingleton(); + + services + .AddTransient(); + services + .AddTransient() + .AddSingleton(); + //services + // .AddPollyPolicies(); + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.SqlServer/EventSourcingCQRS.EventStore.SqlServer.csproj b/src/EventSourcingCQRS.EventStore.SqlServer/EventSourcingCQRS.EventStore.SqlServer.csproj new file mode 100644 index 0000000..8c0e2f5 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.SqlServer/EventSourcingCQRS.EventStore.SqlServer.csproj @@ -0,0 +1,33 @@ + + + net7.0 + enable + enable + True + Event Sourcing CQRS SQL Server Event Store + A SQL Server based event store for EventSourcingCQRS + https://github.com/LyndseyPaxton/EventSourcingCQRS + EventSourcing CQRS EventSourced SQL Server + EventSourcingCQRS.EventStore.SqlServer.Beta + $([System.DateTime]::Now.ToString("yyyy.MM.dd.HHmm")) + Lyndsey Paxton + Mental Monkey Software + + + + + + + + + + + + + + + + + + + diff --git a/src/EventStores/SimpleCqrs.EventStore.SqlServer/IDomainEventSerializer.cs b/src/EventSourcingCQRS.EventStore.SqlServer/IDomainEventSerializer.cs similarity index 52% rename from src/EventStores/SimpleCqrs.EventStore.SqlServer/IDomainEventSerializer.cs rename to src/EventSourcingCQRS.EventStore.SqlServer/IDomainEventSerializer.cs index 4750502..7225e08 100644 --- a/src/EventStores/SimpleCqrs.EventStore.SqlServer/IDomainEventSerializer.cs +++ b/src/EventSourcingCQRS.EventStore.SqlServer/IDomainEventSerializer.cs @@ -1,14 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.EventStore.SqlServer -{ - public interface IDomainEventSerializer - { - string Serialize(DomainEvent domainEvent); - DomainEvent Deserialize(Type targetType, string serializedDomainEvent); - } -} +using EventSourcingCQRS.Eventing; +//using SimpleCqrs.Eventing; + +namespace EventSourcingCQRS.EventStore.SqlServer +{ + public interface IDomainEventSerializer + { + string Serialize(DomainEvent domainEvent); + DomainEvent Deserialize(Type targetType, string serializedDomainEvent); + } +} diff --git a/src/EventStores/SimpleCqrs.EventStore.SqlServer/Properties/AssemblyInfo.cs b/src/EventSourcingCQRS.EventStore.SqlServer/Properties/AssemblyInfo.cs similarity index 97% rename from src/EventStores/SimpleCqrs.EventStore.SqlServer/Properties/AssemblyInfo.cs rename to src/EventSourcingCQRS.EventStore.SqlServer/Properties/AssemblyInfo.cs index c9d5148..7da0056 100644 --- a/src/EventStores/SimpleCqrs.EventStore.SqlServer/Properties/AssemblyInfo.cs +++ b/src/EventSourcingCQRS.EventStore.SqlServer/Properties/AssemblyInfo.cs @@ -1,36 +1,36 @@ -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("SimpleCqrs.EventStore.SqlServer")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SimpleCqrs.EventStore.SqlServer")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[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("8a0317f8-86db-46c7-b815-dd31b248091d")] - -// 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")] +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("SimpleCqrs.EventStore.SqlServer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("SimpleCqrs.EventStore.SqlServer")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] +[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("8a0317f8-86db-46c7-b815-dd31b248091d")] + +// 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/src/EventSourcingCQRS.EventStore.SqlServer/Serializers/JsonDomainEventSerializer.cs b/src/EventSourcingCQRS.EventStore.SqlServer/Serializers/JsonDomainEventSerializer.cs new file mode 100644 index 0000000..c589bf4 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.SqlServer/Serializers/JsonDomainEventSerializer.cs @@ -0,0 +1,60 @@ +using EventSourcingCQRS.Eventing; +using Newtonsoft.Json; + + +namespace EventSourcingCQRS.EventStore.SqlServer.Serializers +{ + public class JsonDomainEventSerializer : IDomainEventSerializer + { + public string Serialize(DomainEvent domainEvent) + { + + var settings = new Newtonsoft.Json.JsonSerializerSettings + { + TypeNameAssemblyFormatHandling = Newtonsoft.Json.TypeNameAssemblyFormatHandling.Simple, + TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects, + }; + + var json = JsonConvert.SerializeObject(domainEvent, settings); + return json; + } + + public DomainEvent Deserialize(Type targetType, string serializedDomainEvent) + { + var settings = new JsonSerializerSettings + { + ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver + { + NamingStrategy = new Newtonsoft.Json.Serialization.CamelCaseNamingStrategy() + }, + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + TypeNameHandling = TypeNameHandling.Auto + }; + + var domainEvent = JsonConvert.DeserializeObject(serializedDomainEvent, settings); + return domainEvent; + } + } + + public class BinaryDomainEventSerializer : IDomainEventSerializer + { + public string Serialize(DomainEvent domainEvent) + { + throw new NotImplementedException(); + + //var options = new JsonSerializerOptions { WriteIndented = true }; + //using var stream = new MemoryStream(); + //JsonSerializer.Serialize(stream, domainEvent, options); + //return Convert.ToBase64String(stream.ToArray()); + } + + public DomainEvent Deserialize(Type targetType, string serializedDomainEvent) + { + throw new NotImplementedException(); + //var formatter = new BinaryFormatter(); + //using var stream = new MemoryStream(Convert.FromBase64String(serializedDomainEvent)); + //var domainEvent = JsonSerializer.Deserialize(stream); + //return domainEvent as DomainEvent; + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.SqlServer/ServiceCollectionExtensions.cs b/src/EventSourcingCQRS.EventStore.SqlServer/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..9fb982c --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.SqlServer/ServiceCollectionExtensions.cs @@ -0,0 +1,29 @@ +using EventSourcingCQRS.Eventing; +using EventSourcingCQRS.EventStore.SqlServer.Serializers; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace EventSourcingCQRS.EventStore.SqlServer +{ + public static class ServiceCollectionExtensions + { + public static void AddSqlServerEventStore(this IServiceCollection services, IConfiguration configuration) + { + services + .AddSingleton(); + services + .AddTransient(); + + services + .AddSingleton(s => + new SqlServerConfiguration( + configuration.GetConnectionString("EventStore"))); + + services + .AddTransient(); + + services + .AddTransient(); + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.SqlServer/SqlServerConfiguration.cs b/src/EventSourcingCQRS.EventStore.SqlServer/SqlServerConfiguration.cs new file mode 100644 index 0000000..aa2f660 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.SqlServer/SqlServerConfiguration.cs @@ -0,0 +1,14 @@ +namespace EventSourcingCQRS.EventStore.SqlServer +{ + public class SqlServerConfiguration + { + private readonly string _connectionString; + + public SqlServerConfiguration(string connectionString) + { + this._connectionString = connectionString; + } + + public string ConnectionString => _connectionString; + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.SqlServer/SqlServerEventStore.cs b/src/EventSourcingCQRS.EventStore.SqlServer/SqlServerEventStore.cs new file mode 100644 index 0000000..7948960 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.SqlServer/SqlServerEventStore.cs @@ -0,0 +1,140 @@ +//using ServiceStack.Text; + +using System.Data.SqlClient; +using System.Text; +using EventSourcingCQRS.Eventing; + +namespace EventSourcingCQRS.EventStore.SqlServer +{ + public class SqlServerEventStore : IEventStore + { + private readonly IDomainEventSerializer _serializer; + private readonly SqlServerConfiguration _configuration; + + public SqlServerEventStore(SqlServerConfiguration configuration, IDomainEventSerializer serializer) + { + this._serializer = serializer; + this._configuration = configuration; + Init(); + } + + public void Init() + { + using var connection = new SqlConnection(_configuration.ConnectionString); + connection.Open(); + var sql = string.Format(SqlStatements.CreateTheEventStoreTable, "EventStore"); + using (var command = new SqlCommand(sql, connection)) + command.ExecuteNonQuery(); + connection.Close(); + } + + + + public Task> GetDistinctAggregateRootsId() + { + throw new NotImplementedException(); + } + + public async Task> GetEvents(Guid aggregateRootId, int startSequence) + { + var events = new List(); + await using var connection = new SqlConnection(_configuration.ConnectionString); + connection.Open(); + var sql = string.Format(SqlStatements.GetEventsByAggregateRootAndSequence, "", "EventStore", aggregateRootId, + startSequence); + await using (var command = new SqlCommand(sql, connection)) + await using (var reader = await command.ExecuteReaderAsync()) + while (reader.Read()) + { + var type = reader["EventType"].ToString(); + var data = reader["data"].ToString(); + + try + { + events.Add(_serializer.Deserialize(Type.GetType(type), data)); + } + catch (ArgumentNullException ex) + { + throw new Exception( + $"Cannot find type '{type.Split(',')[0]}', yet the type is in the event store. Are you sure you haven't changed a class name or something arising from mental dullness?", ex.InnerException); + } + } + connection.Close(); + return events; + } + + public Task> GetEventsUpToSequence(Guid aggregateRootId, int sequence) + { + throw new NotImplementedException(); + } + + public Task Insert(IEnumerable domainEvents) + { + var sql = new StringBuilder(); + foreach (var domainEvent in domainEvents) + sql.AppendFormat(SqlStatements.InsertEvents, "EventStore", TypeToStringHelperMethods.GetString(domainEvent.GetType()), domainEvent.AggregateRootId, domainEvent.EventDate.ToUniversalTime().ToString("dd MMM yyyy HH:mm:ss"), domainEvent.Sequence, + (_serializer.Serialize(domainEvent) ?? string.Empty) + .Replace("'", "''")); + + if (sql.Length <= 0) return Task.CompletedTask; + + using (var connection = new SqlConnection(_configuration.ConnectionString)) + { + connection.Open(); + using (var command = new SqlCommand(sql.ToString(), connection)) + command.ExecuteNonQuery(); + connection.Close(); + } + + return Task.CompletedTask; + } + + public async Task> GetEventsByEventTypes(IEnumerable domainEventTypes) + { + var events = new List(); + + var eventParameters = String.Join("','", domainEventTypes.Select(TypeToStringHelperMethods.GetString)); + + await using var connection = new SqlConnection(_configuration.ConnectionString); + connection.Open(); + var sql = string.Format(SqlStatements.GetEventsByType, "EventStore", eventParameters); + await using (var command = new SqlCommand(sql, connection)) + await using (var reader = await command.ExecuteReaderAsync()) + while (reader.Read()) + { + var type = reader["EventType"].ToString(); + var data = reader["data"].ToString(); + + var domainEvent = _serializer.Deserialize(Type.GetType(type), data); + events.Add(domainEvent); + } + connection.Close(); + return events; + } + + public Task> GetEventsByEventTypes(IEnumerable domainEventTypes, Guid aggregateRootId) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByEventTypesUpToSequence(IEnumerable domainEventTypes, Guid aggregateRootId, int sequence) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByEventTypes(IEnumerable domainEventTypes, DateTime startDate, DateTime endDate) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByCriteria(Dictionary criteria) + { + throw new NotImplementedException(); + } + + public Task> GetEventsByCriteria(List criteria) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS.EventStore.SqlServer/SqlServerSnapshotStore.cs b/src/EventSourcingCQRS.EventStore.SqlServer/SqlServerSnapshotStore.cs new file mode 100644 index 0000000..dfbead7 --- /dev/null +++ b/src/EventSourcingCQRS.EventStore.SqlServer/SqlServerSnapshotStore.cs @@ -0,0 +1,25 @@ +using EventSourcingCQRS.Eventing; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using EventSourcingCQRS.Domain; + +namespace EventSourcingCQRS.EventStore.SqlServer +{ + public class SqlServerSnapshotStore : ISnapshotStore + { + public Task GetSnapshot(Guid aggregateRootId, CancellationToken cancellationToken) + { + Snapshot documents = null; + return Task.FromResult(documents) ; + + } + + public Task SaveSnapshot(TSnapshot snapshot, CancellationToken cancellationToken) where TSnapshot : Snapshot + { + throw new NotImplementedException(); + } + } +} diff --git a/src/EventStores/SimpleCqrs.EventStore.SqlServer/SqlStatements.cs b/src/EventSourcingCQRS.EventStore.SqlServer/SqlStatements.cs similarity index 72% rename from src/EventStores/SimpleCqrs.EventStore.SqlServer/SqlStatements.cs rename to src/EventSourcingCQRS.EventStore.SqlServer/SqlStatements.cs index d1ab2ba..79bdcd4 100644 --- a/src/EventStores/SimpleCqrs.EventStore.SqlServer/SqlStatements.cs +++ b/src/EventSourcingCQRS.EventStore.SqlServer/SqlStatements.cs @@ -1,20 +1,20 @@ -namespace SimpleCqrs.EventStore.SqlServer -{ - public class SqlStatements - { - internal const string GetEventsByType = "select eventtype, data from {0} where eventtype in ('{1}')"; - internal const string InsertEvents = "insert into {0} values ('{1}', '{2}', '{3}', {4}, '{5}')"; - internal const string GetEventsByAggregateRootAndSequence = "select eventtype, data from {1} where aggregaterootid = '{2}' and sequence >= {3}"; - internal const string CreateTheEventStoreTable = @"IF not EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[{0}]') AND type in (N'U')) -begin -create table dbo.[{0}]( - EventId int identity not null primary key, - EventType nvarchar(255), - AggregateRootId uniqueidentifier not null, - EventDate datetime not null, - Sequence int not null, - Data nvarchar(max) -) -end"; - } +namespace EventSourcingCQRS.EventStore.SqlServer +{ + public class SqlStatements + { + internal const string GetEventsByType = "select eventtype, data from {0} where eventtype in ('{1}')"; + internal const string InsertEvents = "insert into {0} values ('{1}', '{2}', '{3}', {4}, '{5}')"; + internal const string GetEventsByAggregateRootAndSequence = "select eventtype, data from {1} where aggregaterootid = '{2}' and sequence >= {3} order by sequence"; + internal const string CreateTheEventStoreTable = @"IF not EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[{0}]') AND type in (N'U')) +begin +create table dbo.[{0}]( + EventId bigint identity not null primary key, + EventType nvarchar(255) not null, + AggregateRootId uniqueidentifier not null, + EventDate datetimeoffset not null, + Sequence int not null, + Data nvarchar(max) not null +) +end"; + } } \ No newline at end of file diff --git a/src/EventStores/SimpleCqrs.EventStore.SqlServer/TypeToStringHelperMethods.cs b/src/EventSourcingCQRS.EventStore.SqlServer/TypeToStringHelperMethods.cs similarity index 81% rename from src/EventStores/SimpleCqrs.EventStore.SqlServer/TypeToStringHelperMethods.cs rename to src/EventSourcingCQRS.EventStore.SqlServer/TypeToStringHelperMethods.cs index 7fe4d40..f1ee35d 100644 --- a/src/EventStores/SimpleCqrs.EventStore.SqlServer/TypeToStringHelperMethods.cs +++ b/src/EventSourcingCQRS.EventStore.SqlServer/TypeToStringHelperMethods.cs @@ -1,14 +1,12 @@ -using System; - -namespace SimpleCqrs.EventStore.SqlServer -{ - public static class TypeToStringHelperMethods - { - public static string GetString(Type type) - { - var typeArray = type.AssemblyQualifiedName.Split(" ".ToCharArray()); - var returnValue = typeArray[0] + " " + typeArray[1].Replace(",", ""); - return returnValue; - } - } +namespace EventSourcingCQRS.EventStore.SqlServer +{ + public static class TypeToStringHelperMethods + { + public static string GetString(Type type) + { + var typeArray = type.AssemblyQualifiedName.Split(" ".ToCharArray()); + var returnValue = typeArray[0] + " " + typeArray[1].Replace(",", ""); + return returnValue; + } + } } \ No newline at end of file diff --git a/src/SimpleCqrs/Commanding/AggregateRootCommandHandler.cs b/src/EventSourcingCQRS/Commanding/AggregateRootCommandHandler.cs similarity index 93% rename from src/SimpleCqrs/Commanding/AggregateRootCommandHandler.cs rename to src/EventSourcingCQRS/Commanding/AggregateRootCommandHandler.cs index 566d1ea..4b3f399 100644 --- a/src/SimpleCqrs/Commanding/AggregateRootCommandHandler.cs +++ b/src/EventSourcingCQRS/Commanding/AggregateRootCommandHandler.cs @@ -1,49 +1,49 @@ -using SimpleCqrs.Domain; - -namespace SimpleCqrs.Commanding -{ - public abstract class AggregateRootCommandHandler : IHandleCommands - where TCommand : ICommandWithAggregateRootId - where TAggregateRoot : AggregateRoot, new() - { - private readonly IDomainRepository domainRepository; - - protected AggregateRootCommandHandler() : this(ServiceLocator.Current.Resolve()) - { - } - - protected AggregateRootCommandHandler(IDomainRepository domainRepository) - { - this.domainRepository = domainRepository; - } - - void IHandleCommands.Handle(ICommandHandlingContext handlingContext) - { - var command = handlingContext.Command; - - var aggregateRoot = domainRepository.GetById(command.AggregateRootId); - - ValidateTheCommand(handlingContext, command, aggregateRoot); - - Handle(command, aggregateRoot); - - if(aggregateRoot != null) - domainRepository.Save(aggregateRoot); - } - - private void ValidateTheCommand(ICommandHandlingContext handlingContext, TCommand command, TAggregateRoot aggregateRoot) - { - ValidationResult = ValidateCommand(command, aggregateRoot); - handlingContext.Return(ValidationResult); - } - - protected int ValidationResult { get; private set; } - - public virtual int ValidateCommand(TCommand command, TAggregateRoot aggregateRoot) - { - return 0; - } - - public abstract void Handle(TCommand command, TAggregateRoot aggregateRoot); - } +using EventSourcingCQRS.Domain; + +namespace EventSourcingCQRS.Commanding +{ + public abstract class AggregateRootCommandHandler : IHandleCommands + where TCommand : ICommandWithAggregateRootId + where TAggregateRoot : AggregateRoot, new() + { + private readonly IDomainRepository domainRepository; + + protected AggregateRootCommandHandler() : this(ServiceLocator.Current.Resolve()) + { + } + + protected AggregateRootCommandHandler(IDomainRepository domainRepository) + { + this.domainRepository = domainRepository; + } + + void IHandleCommands.Handle(ICommandHandlingContext handlingContext) + { + var command = handlingContext.Command; + + var aggregateRoot = domainRepository.GetById(command.AggregateRootId); + + ValidateTheCommand(handlingContext, command, aggregateRoot); + + Handle(command, aggregateRoot); + + if(aggregateRoot != null) + domainRepository.Save(aggregateRoot); + } + + private void ValidateTheCommand(ICommandHandlingContext handlingContext, TCommand command, TAggregateRoot aggregateRoot) + { + ValidationResult = ValidateCommand(command, aggregateRoot); + handlingContext.Return(ValidationResult); + } + + protected int ValidationResult { get; private set; } + + public virtual int ValidateCommand(TCommand command, TAggregateRoot aggregateRoot) + { + return 0; + } + + public abstract void Handle(TCommand command, TAggregateRoot aggregateRoot); + } } \ No newline at end of file diff --git a/src/EventSourcingCQRS/Commanding/CommandDispatcher.cs b/src/EventSourcingCQRS/Commanding/CommandDispatcher.cs new file mode 100644 index 0000000..947c172 --- /dev/null +++ b/src/EventSourcingCQRS/Commanding/CommandDispatcher.cs @@ -0,0 +1,17 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace EventSourcingCQRS.Commanding +{ + public class CommandDispatcher : ICommandDispatcher + { + private readonly IServiceProvider _serviceProvider; + + public CommandDispatcher(IServiceProvider serviceProvider) => this._serviceProvider = serviceProvider; + + public Task Dispatch(TCommand command, CancellationToken cancellation) + { + var handler = _serviceProvider.GetRequiredService>(); + return handler.Handle(command, cancellation); + } + } +} \ No newline at end of file diff --git a/src/SimpleCqrs/Commanding/CommandHandler.cs b/src/EventSourcingCQRS/Commanding/CommandHandler.cs similarity index 89% rename from src/SimpleCqrs/Commanding/CommandHandler.cs rename to src/EventSourcingCQRS/Commanding/CommandHandler.cs index 67dffed..45c03a6 100644 --- a/src/SimpleCqrs/Commanding/CommandHandler.cs +++ b/src/EventSourcingCQRS/Commanding/CommandHandler.cs @@ -1,27 +1,25 @@ -using System; - -namespace SimpleCqrs.Commanding -{ - public abstract class CommandHandler : IHandleCommands where TCommand : ICommand - { - private ICommandHandlingContext context; - - void IHandleCommands.Handle(ICommandHandlingContext handlingContext) - { - context = handlingContext; - Handle(handlingContext.Command); - } - - public abstract void Handle(TCommand command); - - protected void Return(int value) - { - context.Return(value); - } - - protected void Return(Enum value) - { - context.Return(Convert.ToInt32(value)); - } - } +namespace EventSourcingCQRS.Commanding +{ + public abstract class CommandHandler : IHandleCommands where TCommand : ICommand + { + private ICommandHandlingContext context; + + void IHandleCommands.Handle(ICommandHandlingContext handlingContext) + { + context = handlingContext; + Handle(handlingContext.Command); + } + + public abstract void Handle(TCommand command); + + protected void Return(int value) + { + context.Return(value); + } + + protected void Return(Enum value) + { + context.Return(Convert.ToInt32(value)); + } + } } \ No newline at end of file diff --git a/src/SimpleCqrs/Commanding/CommandHandlerNotFoundException.cs b/src/EventSourcingCQRS/Commanding/CommandHandlerNotFoundException.cs similarity index 83% rename from src/SimpleCqrs/Commanding/CommandHandlerNotFoundException.cs rename to src/EventSourcingCQRS/Commanding/CommandHandlerNotFoundException.cs index ebf7c18..299b5d9 100644 --- a/src/SimpleCqrs/Commanding/CommandHandlerNotFoundException.cs +++ b/src/EventSourcingCQRS/Commanding/CommandHandlerNotFoundException.cs @@ -1,6 +1,4 @@ -using System; - -namespace SimpleCqrs.Commanding +namespace EventSourcingCQRS.Commanding { public class CommandHandlerNotFoundException : Exception { diff --git a/src/SimpleCqrs/Commanding/CommandInvokerDictionaryBuilderHelpers.cs b/src/EventSourcingCQRS/Commanding/CommandInvokerDictionaryBuilderHelpers.cs similarity index 93% rename from src/SimpleCqrs/Commanding/CommandInvokerDictionaryBuilderHelpers.cs rename to src/EventSourcingCQRS/Commanding/CommandInvokerDictionaryBuilderHelpers.cs index 3a31840..c3fe14a 100644 --- a/src/SimpleCqrs/Commanding/CommandInvokerDictionaryBuilderHelpers.cs +++ b/src/EventSourcingCQRS/Commanding/CommandInvokerDictionaryBuilderHelpers.cs @@ -1,50 +1,46 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace SimpleCqrs.Commanding -{ - internal static class CommandInvokerDictionaryBuilderHelpers - { - public static IDictionary CreateADictionaryOfCommandInvokers( - ITypeCatalog typeCatalog, IServiceLocator serviceLocator) - { - var types = GetAllCommandHandlerTypes(typeCatalog); - return CreateCommandInvokersForTheseTypes(types, serviceLocator); - } - - private static IEnumerable GetAllCommandHandlerTypes(ITypeCatalog typeCatalog) - { - return typeCatalog.GetGenericInterfaceImplementations(typeof (IHandleCommands<>)); - } - - private static IDictionary CreateCommandInvokersForTheseTypes( - IEnumerable commandHandlerTypes, IServiceLocator serviceLocator) - { - var commandInvokerDictionary = new Dictionary(); - foreach (var commandHandlerType in commandHandlerTypes) - { - var commandTypes = GetCommandTypesForCommandHandler(commandHandlerType); - foreach (var commandType in commandTypes) - { - if (commandInvokerDictionary.ContainsKey(commandType)) - throw new DuplicateCommandHandlersException(commandType); - - commandInvokerDictionary.Add(commandType, - new LocalCommandBus.CommandHandlerInvoker(serviceLocator, commandType, - commandHandlerType)); - } - } - return commandInvokerDictionary; - } - - private static IEnumerable GetCommandTypesForCommandHandler(Type commandHandlerType) - { - return (from interfaceType in commandHandlerType.GetInterfaces() - where - interfaceType.IsGenericType && - interfaceType.GetGenericTypeDefinition() == typeof (IHandleCommands<>) - select interfaceType.GetGenericArguments()[0]).ToArray(); - } - } +namespace EventSourcingCQRS.Commanding +{ + internal static class CommandInvokerDictionaryBuilderHelpers + { + public static IDictionary CreateADictionaryOfCommandInvokers( + ITypeCatalog typeCatalog, IServiceLocator serviceLocator) + { + var types = GetAllCommandHandlerTypes(typeCatalog); + return CreateCommandInvokersForTheseTypes(types, serviceLocator); + } + + private static IEnumerable GetAllCommandHandlerTypes(ITypeCatalog typeCatalog) + { + return typeCatalog.GetGenericInterfaceImplementations(typeof (IHandleCommands<>)); + } + + private static IDictionary CreateCommandInvokersForTheseTypes( + IEnumerable commandHandlerTypes, IServiceLocator serviceLocator) + { + var commandInvokerDictionary = new Dictionary(); + foreach (var commandHandlerType in commandHandlerTypes) + { + var commandTypes = GetCommandTypesForCommandHandler(commandHandlerType); + foreach (var commandType in commandTypes) + { + if (commandInvokerDictionary.ContainsKey(commandType)) + throw new DuplicateCommandHandlersException(commandType); + + commandInvokerDictionary.Add(commandType, + new LocalCommandBus.CommandHandlerInvoker(serviceLocator, commandType, + commandHandlerType)); + } + } + return commandInvokerDictionary; + } + + private static IEnumerable GetCommandTypesForCommandHandler(Type commandHandlerType) + { + return (from interfaceType in commandHandlerType.GetInterfaces() + where + interfaceType.IsGenericType && + interfaceType.GetGenericTypeDefinition() == typeof (IHandleCommands<>) + select interfaceType.GetGenericArguments()[0]).ToArray(); + } + } } \ No newline at end of file diff --git a/src/SimpleCqrs/Commanding/CommandWithAggregateRootId.cs b/src/EventSourcingCQRS/Commanding/CommandWithAggregateRootId.cs similarity index 72% rename from src/SimpleCqrs/Commanding/CommandWithAggregateRootId.cs rename to src/EventSourcingCQRS/Commanding/CommandWithAggregateRootId.cs index 218f492..36fb540 100644 --- a/src/SimpleCqrs/Commanding/CommandWithAggregateRootId.cs +++ b/src/EventSourcingCQRS/Commanding/CommandWithAggregateRootId.cs @@ -1,10 +1,8 @@ -using System; - -namespace SimpleCqrs.Commanding -{ - [Serializable] - public class CommandWithAggregateRootId : ICommandWithAggregateRootId - { - public Guid AggregateRootId { get; set; } - } +namespace EventSourcingCQRS.Commanding +{ + [Serializable] + public class CommandWithAggregateRootId : ICommandWithAggregateRootId + { + public Guid AggregateRootId { get; set; } + } } \ No newline at end of file diff --git a/src/SimpleCqrs/Commanding/CreateCommandHandler.cs b/src/EventSourcingCQRS/Commanding/CreateCommandHandler.cs similarity index 88% rename from src/SimpleCqrs/Commanding/CreateCommandHandler.cs rename to src/EventSourcingCQRS/Commanding/CreateCommandHandler.cs index b9f352a..02044a7 100644 --- a/src/SimpleCqrs/Commanding/CreateCommandHandler.cs +++ b/src/EventSourcingCQRS/Commanding/CreateCommandHandler.cs @@ -1,24 +1,24 @@ -using SimpleCqrs.Domain; - -namespace SimpleCqrs.Commanding -{ - public abstract class CreateCommandHandler : CommandHandler where TCommand : ICommand - { - public override void Handle(TCommand command) - { - var aggregateRoot = CreateAggregateRoot(command); - - Handle(command, aggregateRoot); - - var domainRepository = ServiceLocator.Current.Resolve(); - - domainRepository.Save(aggregateRoot); - } - - public abstract AggregateRoot CreateAggregateRoot(TCommand command); - - public virtual void Handle(TCommand command, AggregateRoot aggregateRoot) - { - } - } +using EventSourcingCQRS.Domain; + +namespace EventSourcingCQRS.Commanding +{ + public abstract class CreateCommandHandler : CommandHandler where TCommand : ICommand + { + public override void Handle(TCommand command) + { + var aggregateRoot = CreateAggregateRoot(command); + + Handle(command, aggregateRoot); + + var domainRepository = ServiceLocator.Current.Resolve(); + + domainRepository.Save(aggregateRoot); + } + + public abstract AggregateRoot CreateAggregateRoot(TCommand command); + + public virtual void Handle(TCommand command, AggregateRoot aggregateRoot) + { + } + } } \ No newline at end of file diff --git a/src/SimpleCqrs/Commanding/DuplicateCommandHandlersException.cs b/src/EventSourcingCQRS/Commanding/DuplicateCommandHandlersException.cs similarity index 83% rename from src/SimpleCqrs/Commanding/DuplicateCommandHandlersException.cs rename to src/EventSourcingCQRS/Commanding/DuplicateCommandHandlersException.cs index a6a801d..773bc2d 100644 --- a/src/SimpleCqrs/Commanding/DuplicateCommandHandlersException.cs +++ b/src/EventSourcingCQRS/Commanding/DuplicateCommandHandlersException.cs @@ -1,6 +1,4 @@ -using System; - -namespace SimpleCqrs.Commanding +namespace EventSourcingCQRS.Commanding { public class DuplicateCommandHandlersException : Exception { diff --git a/src/SimpleCqrs/Commanding/ExecuteTimeoutException.cs b/src/EventSourcingCQRS/Commanding/ExecuteTimeoutException.cs similarity index 84% rename from src/SimpleCqrs/Commanding/ExecuteTimeoutException.cs rename to src/EventSourcingCQRS/Commanding/ExecuteTimeoutException.cs index 4d23230..d23853f 100644 --- a/src/SimpleCqrs/Commanding/ExecuteTimeoutException.cs +++ b/src/EventSourcingCQRS/Commanding/ExecuteTimeoutException.cs @@ -1,26 +1,25 @@ -using System; -using System.Runtime.Serialization; - -namespace SimpleCqrs.Commanding -{ - [Serializable] - public class ExecuteTimeoutException : Exception - { - public ExecuteTimeoutException() - : base("The allotted time for the ICommandBus.Execute method has expired.") - { - } - - public ExecuteTimeoutException(string message) : base(message) - { - } - - public ExecuteTimeoutException(string message, Exception inner) : base(message, inner) - { - } - - protected ExecuteTimeoutException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - } +using System.Runtime.Serialization; + +namespace EventSourcingCQRS.Commanding +{ + [Serializable] + public class ExecuteTimeoutException : Exception + { + public ExecuteTimeoutException() + : base("The allotted time for the ICommandBus.Execute method has expired.") + { + } + + public ExecuteTimeoutException(string message) : base(message) + { + } + + public ExecuteTimeoutException(string message, Exception inner) : base(message, inner) + { + } + + protected ExecuteTimeoutException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } + } } \ No newline at end of file diff --git a/src/SimpleCqrs/Commanding/ICommand.cs b/src/EventSourcingCQRS/Commanding/ICommand.cs similarity index 51% rename from src/SimpleCqrs/Commanding/ICommand.cs rename to src/EventSourcingCQRS/Commanding/ICommand.cs index db4145d..efd099b 100644 --- a/src/SimpleCqrs/Commanding/ICommand.cs +++ b/src/EventSourcingCQRS/Commanding/ICommand.cs @@ -1,6 +1,6 @@ -namespace SimpleCqrs.Commanding -{ - public interface ICommand - { - } +namespace EventSourcingCQRS.Commanding +{ + public interface ICommand + { + } } \ No newline at end of file diff --git a/src/SimpleCqrs/Commanding/ICommandBus.cs b/src/EventSourcingCQRS/Commanding/ICommandBus.cs similarity index 82% rename from src/SimpleCqrs/Commanding/ICommandBus.cs rename to src/EventSourcingCQRS/Commanding/ICommandBus.cs index c99bd60..c7f867c 100644 --- a/src/SimpleCqrs/Commanding/ICommandBus.cs +++ b/src/EventSourcingCQRS/Commanding/ICommandBus.cs @@ -1,8 +1,8 @@ -namespace SimpleCqrs.Commanding -{ - public interface ICommandBus - { - int Execute(TCommand command) where TCommand : ICommand; - void Send(TCommand command) where TCommand : ICommand; - } +namespace EventSourcingCQRS.Commanding +{ + public interface ICommandBus + { + int Execute(TCommand command) where TCommand : ICommand; + void Send(TCommand command) where TCommand : ICommand; + } } \ No newline at end of file diff --git a/src/EventSourcingCQRS/Commanding/ICommandDispatcher.cs b/src/EventSourcingCQRS/Commanding/ICommandDispatcher.cs new file mode 100644 index 0000000..624ea88 --- /dev/null +++ b/src/EventSourcingCQRS/Commanding/ICommandDispatcher.cs @@ -0,0 +1,7 @@ +namespace EventSourcingCQRS.Commanding +{ + public interface ICommandDispatcher + { + Task Dispatch(TCommand command, CancellationToken cancellation); + } +} \ No newline at end of file diff --git a/src/SimpleCqrs/Commanding/ICommandErrorHandler.cs b/src/EventSourcingCQRS/Commanding/ICommandErrorHandler.cs similarity index 76% rename from src/SimpleCqrs/Commanding/ICommandErrorHandler.cs rename to src/EventSourcingCQRS/Commanding/ICommandErrorHandler.cs index 51f829d..e8ca091 100644 --- a/src/SimpleCqrs/Commanding/ICommandErrorHandler.cs +++ b/src/EventSourcingCQRS/Commanding/ICommandErrorHandler.cs @@ -1,9 +1,7 @@ -using System; - -namespace SimpleCqrs.Commanding -{ - public interface ICommandErrorHandler where TCommand : ICommand - { - void Handle(ICommandHandlingContext handlingContext, Exception exception); - } +namespace EventSourcingCQRS.Commanding +{ + public interface ICommandErrorHandler where TCommand : ICommand + { + void Handle(ICommandHandlingContext handlingContext, Exception exception); + } } \ No newline at end of file diff --git a/src/EventSourcingCQRS/Commanding/ICommandHandler.cs b/src/EventSourcingCQRS/Commanding/ICommandHandler.cs new file mode 100644 index 0000000..d291183 --- /dev/null +++ b/src/EventSourcingCQRS/Commanding/ICommandHandler.cs @@ -0,0 +1,7 @@ +namespace EventSourcingCQRS.Commanding +{ + public interface ICommandHandler + { + Task Handle(TCommand command, CancellationToken cancellation); + } +} \ No newline at end of file diff --git a/src/SimpleCqrs/Commanding/ICommandHandlingContext.cs b/src/EventSourcingCQRS/Commanding/ICommandHandlingContext.cs similarity index 79% rename from src/SimpleCqrs/Commanding/ICommandHandlingContext.cs rename to src/EventSourcingCQRS/Commanding/ICommandHandlingContext.cs index 2d30e75..15b89e5 100644 --- a/src/SimpleCqrs/Commanding/ICommandHandlingContext.cs +++ b/src/EventSourcingCQRS/Commanding/ICommandHandlingContext.cs @@ -1,4 +1,4 @@ -namespace SimpleCqrs.Commanding +namespace EventSourcingCQRS.Commanding { public interface ICommandHandlingContext where TCommand : ICommand { diff --git a/src/SimpleCqrs/Commanding/ICommandWithAggregateRootId.cs b/src/EventSourcingCQRS/Commanding/ICommandWithAggregateRootId.cs similarity index 66% rename from src/SimpleCqrs/Commanding/ICommandWithAggregateRootId.cs rename to src/EventSourcingCQRS/Commanding/ICommandWithAggregateRootId.cs index 55e741a..900cce2 100644 --- a/src/SimpleCqrs/Commanding/ICommandWithAggregateRootId.cs +++ b/src/EventSourcingCQRS/Commanding/ICommandWithAggregateRootId.cs @@ -1,9 +1,7 @@ -using System; - -namespace SimpleCqrs.Commanding -{ - public interface ICommandWithAggregateRootId : ICommand - { - Guid AggregateRootId { get; } - } +namespace EventSourcingCQRS.Commanding +{ + public interface ICommandWithAggregateRootId : ICommand + { + Guid AggregateRootId { get; } + } } \ No newline at end of file diff --git a/src/SimpleCqrs/Commanding/IHandleCommands.cs b/src/EventSourcingCQRS/Commanding/IHandleCommands.cs similarity index 79% rename from src/SimpleCqrs/Commanding/IHandleCommands.cs rename to src/EventSourcingCQRS/Commanding/IHandleCommands.cs index 5f57bb6..b5d9d1e 100644 --- a/src/SimpleCqrs/Commanding/IHandleCommands.cs +++ b/src/EventSourcingCQRS/Commanding/IHandleCommands.cs @@ -1,7 +1,7 @@ -namespace SimpleCqrs.Commanding -{ - public interface IHandleCommands where TCommand : ICommand - { - void Handle(ICommandHandlingContext handlingContext); - } +namespace EventSourcingCQRS.Commanding +{ + public interface IHandleCommands where TCommand : ICommand + { + void Handle(ICommandHandlingContext handlingContext); + } } \ No newline at end of file diff --git a/src/SimpleCqrs/Commanding/LocalCommandBus.cs b/src/EventSourcingCQRS/Commanding/LocalCommandBus.cs similarity index 95% rename from src/SimpleCqrs/Commanding/LocalCommandBus.cs rename to src/EventSourcingCQRS/Commanding/LocalCommandBus.cs index 5c69f4c..e9ed9b5 100644 --- a/src/SimpleCqrs/Commanding/LocalCommandBus.cs +++ b/src/EventSourcingCQRS/Commanding/LocalCommandBus.cs @@ -1,130 +1,128 @@ -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace SimpleCqrs.Commanding -{ - public class LocalCommandBus : ICommandBus, IHaveATestMode - { - private readonly IDictionary commandInvokers; - - public LocalCommandBus(ITypeCatalog typeCatalog, IServiceLocator serviceLocator) - { - commandInvokers = CommandInvokerDictionaryBuilderHelpers.CreateADictionaryOfCommandInvokers(typeCatalog, serviceLocator); - } - - bool IHaveATestMode.IsInTestMode { get; set; } - - public int Execute(TCommand command) where TCommand : ICommand - { - var commandHandler = GetTheCommandHandler(command); - return commandHandler == null ? 0 : commandHandler.Execute(command); - } - - public void Send(TCommand command) where TCommand : ICommand - { - var commandHandler = GetTheCommandHandler(command); - - if (commandHandler == null) return; - - commandHandler.Send(command); - } - - private CommandHandlerInvoker GetTheCommandHandler(ICommand command) - { - CommandHandlerInvoker commandInvoker; - if(!commandInvokers.TryGetValue(command.GetType(), out commandInvoker) && !((IHaveATestMode)this).IsInTestMode) - throw new CommandHandlerNotFoundException(command.GetType()); - return commandInvoker; - } - - public class CommandHandlerInvoker - { - private readonly Type commandHandlerType; - private readonly Type commandType; - private readonly IServiceLocator serviceLocator; - - public CommandHandlerInvoker(IServiceLocator serviceLocator, Type commandType, Type commandHandlerType) - { - this.serviceLocator = serviceLocator; - this.commandType = commandType; - this.commandHandlerType = commandHandlerType; - } - - public int Execute(ICommand command) - { - var handlingContext = CreateTheCommandHandlingContext(command); - ExecuteTheCommandHandler(handlingContext); - return ((ICommandHandlingContext)handlingContext).ReturnValue; - } - - public void Send(ICommand command) - { - var handlingContext = CreateTheCommandHandlingContext(command); - ExecuteTheCommandHandler(handlingContext); - } - - private void ExecuteTheCommandHandler(ICommandHandlingContext handlingContext) - { - var handleMethod = GetTheHandleMethod(); - var commandHandler = CreateTheCommandHandler(); - - try - { - handleMethod.Invoke(commandHandler, new object[] { handlingContext }); - } - catch(TargetInvocationException ex) - { - throw new Exception( - string.Format("Command handler '{0}' for '{1}' failed. Inspect inner exception.", commandHandler.GetType().Name, handlingContext.Command.GetType().Name), - ex.InnerException); - } - } - - private ICommandHandlingContext CreateTheCommandHandlingContext(ICommand command) - { - var handlingContextType = typeof(CommandHandlingContext<>).MakeGenericType(commandType); - return (ICommandHandlingContext)Activator.CreateInstance(handlingContextType, command); - } - - private object CreateTheCommandHandler() - { - return serviceLocator.Resolve(commandHandlerType); - } - - private MethodInfo GetTheHandleMethod() - { - return typeof(IHandleCommands<>).MakeGenericType(commandType).GetMethod("Handle"); - } - } - - private interface ICommandHandlingContext - { - ICommand Command { get; } - int ReturnValue { get; } - } - - private class CommandHandlingContext : ICommandHandlingContext, ICommandHandlingContext - where TCommand : ICommand - { - public CommandHandlingContext(TCommand command) - { - Command = command; - } - - public TCommand Command { get; private set; } - - ICommand ICommandHandlingContext.Command - { - get { return Command; } - } - - public int ReturnValue { get; private set; } - - public void Return(int value) - { - ReturnValue = value; - } - } - } +using System.Reflection; + +namespace EventSourcingCQRS.Commanding +{ + public class LocalCommandBus : ICommandBus, IHaveATestMode + { + private readonly IDictionary commandInvokers; + + public LocalCommandBus(ITypeCatalog typeCatalog, IServiceLocator serviceLocator) + { + commandInvokers = CommandInvokerDictionaryBuilderHelpers.CreateADictionaryOfCommandInvokers(typeCatalog, serviceLocator); + } + + bool IHaveATestMode.IsInTestMode { get; set; } + + public int Execute(TCommand command) where TCommand : ICommand + { + var commandHandler = GetTheCommandHandler(command); + return commandHandler == null ? 0 : commandHandler.Execute(command); + } + + public void Send(TCommand command) where TCommand : ICommand + { + var commandHandler = GetTheCommandHandler(command); + + if (commandHandler == null) return; + + commandHandler.Send(command); + } + + private CommandHandlerInvoker GetTheCommandHandler(ICommand command) + { + CommandHandlerInvoker commandInvoker; + if(!commandInvokers.TryGetValue(command.GetType(), out commandInvoker) && !((IHaveATestMode)this).IsInTestMode) + throw new CommandHandlerNotFoundException(command.GetType()); + return commandInvoker; + } + + public class CommandHandlerInvoker + { + private readonly Type commandHandlerType; + private readonly Type commandType; + private readonly IServiceLocator serviceLocator; + + public CommandHandlerInvoker(IServiceLocator serviceLocator, Type commandType, Type commandHandlerType) + { + this.serviceLocator = serviceLocator; + this.commandType = commandType; + this.commandHandlerType = commandHandlerType; + } + + public int Execute(ICommand command) + { + var handlingContext = CreateTheCommandHandlingContext(command); + ExecuteTheCommandHandler(handlingContext); + return ((ICommandHandlingContext)handlingContext).ReturnValue; + } + + public void Send(ICommand command) + { + var handlingContext = CreateTheCommandHandlingContext(command); + ExecuteTheCommandHandler(handlingContext); + } + + private void ExecuteTheCommandHandler(ICommandHandlingContext handlingContext) + { + var handleMethod = GetTheHandleMethod(); + var commandHandler = CreateTheCommandHandler(); + + try + { + handleMethod.Invoke(commandHandler, new object[] { handlingContext }); + } + catch(TargetInvocationException ex) + { + throw new Exception( + string.Format("Command handler '{0}' for '{1}' failed. Inspect inner exception.", commandHandler.GetType().Name, handlingContext.Command.GetType().Name), + ex.InnerException); + } + } + + private ICommandHandlingContext CreateTheCommandHandlingContext(ICommand command) + { + var handlingContextType = typeof(CommandHandlingContext<>).MakeGenericType(commandType); + return (ICommandHandlingContext)Activator.CreateInstance(handlingContextType, command); + } + + private object CreateTheCommandHandler() + { + return serviceLocator.Resolve(commandHandlerType); + } + + private MethodInfo GetTheHandleMethod() + { + return typeof(IHandleCommands<>).MakeGenericType(commandType).GetMethod("Handle"); + } + } + + private interface ICommandHandlingContext + { + ICommand Command { get; } + int ReturnValue { get; } + } + + private class CommandHandlingContext : ICommandHandlingContext, ICommandHandlingContext + where TCommand : ICommand + { + public CommandHandlingContext(TCommand command) + { + Command = command; + } + + public TCommand Command { get; private set; } + + ICommand ICommandHandlingContext.Command + { + get { return Command; } + } + + public int ReturnValue { get; private set; } + + public void Return(int value) + { + ReturnValue = value; + } + } + } } \ No newline at end of file diff --git a/src/SimpleCqrs/Domain/AggregateRoot.cs b/src/EventSourcingCQRS/Domain/AggregateRoot.cs similarity index 52% rename from src/SimpleCqrs/Domain/AggregateRoot.cs rename to src/EventSourcingCQRS/Domain/AggregateRoot.cs index 9faeca0..edbfc5e 100644 --- a/src/SimpleCqrs/Domain/AggregateRoot.cs +++ b/src/EventSourcingCQRS/Domain/AggregateRoot.cs @@ -1,99 +1,98 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Reflection; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.Domain -{ - public abstract class AggregateRoot - { - private readonly Queue uncommittedEvents = new Queue(); - private readonly List entities = new List(); - - public Guid Id { get; protected internal set; } - public int LastEventSequence { get; protected internal set; } - - public ReadOnlyCollection UncommittedEvents - { - get { return new ReadOnlyCollection(uncommittedEvents.ToList()); } - } - - public void LoadFromHistoricalEvents(params DomainEvent[] domainEvents) - { - if(domainEvents.Length == 0) return; - - var domainEventList = domainEvents.OrderBy(domainEvent => domainEvent.Sequence).ToList(); - LastEventSequence = domainEventList.Last().Sequence; - - domainEventList.ForEach(ApplyEventToInternalState); - } - - public void Apply(DomainEvent domainEvent) - { - domainEvent.Sequence = ++LastEventSequence; - ApplyEventToInternalState(domainEvent); - domainEvent.AggregateRootId = Id; - domainEvent.EventDate = DateTime.Now; - - EventModifier.Modify(domainEvent); - - uncommittedEvents.Enqueue(domainEvent); - } - - public void CommitEvents() - { - uncommittedEvents.Clear(); - entities.ForEach(entity => entity.CommitEvents()); - } - - public void RegisterEntity(Entity entity) - { - entity.AggregateRoot = this; - entities.Add(entity); - } - - private void ApplyEventToInternalState(DomainEvent domainEvent) - { - var domainEventType = domainEvent.GetType(); - var domainEventTypeName = domainEventType.Name; - var aggregateRootType = GetType(); - - var eventHandlerMethodName = GetEventHandlerMethodName(domainEventTypeName); - var methodInfo = aggregateRootType.GetMethod(eventHandlerMethodName, - BindingFlags.Instance | BindingFlags.Public | - BindingFlags.NonPublic, null, new[] {domainEventType}, null); - - if(methodInfo != null && EventHandlerMethodInfoHasCorrectParameter(methodInfo, domainEventType)) - { - methodInfo.Invoke(this, new[] {domainEvent}); - } - - ApplyEventToEntities(domainEvent); - } - - private void ApplyEventToEntities(DomainEvent domainEvent) - { - var entityDomainEvent = domainEvent as EntityDomainEvent; - if (entityDomainEvent == null) return; - - var list = entities - .Where(entity => entity.Id == entityDomainEvent.EntityId).ToList(); - list - .ForEach(entity => entity.ApplyHistoricalEvents(entityDomainEvent)); - } - - private static string GetEventHandlerMethodName(string domainEventTypeName) - { - var eventIndex = domainEventTypeName.LastIndexOf("Event"); - return "On" + domainEventTypeName.Remove(eventIndex, 5); - } - - private static bool EventHandlerMethodInfoHasCorrectParameter(MethodInfo eventHandlerMethodInfo, Type domainEventType) - { - var parameters = eventHandlerMethodInfo.GetParameters(); - return parameters.Length == 1 && parameters[0].ParameterType == domainEventType; - } - } +using System.Collections.ObjectModel; +using System.Reflection; +using EventSourcingCQRS.Eventing; + +namespace EventSourcingCQRS.Domain +{ + public abstract class AggregateRoot + { + private readonly List _entities = new List(); + private readonly Queue _uncommittedEvents = new Queue(); + + public Guid Id { get; protected internal set; } + public int LastEventSequence { get; protected internal set; } + + public ReadOnlyCollection UncommittedEvents => + new ReadOnlyCollection(_uncommittedEvents.ToList()); + + public void LoadFromHistoricalEvents(params DomainEvent[] domainEvents) + { + if (domainEvents.Length == 0) + { + return; + } + + var domainEventList = domainEvents.OrderBy(domainEvent => domainEvent.Sequence).ToList(); + LastEventSequence = domainEventList.Last().Sequence; + + domainEventList.ForEach(ApplyEventToInternalState); + } + + public void Apply(DomainEvent domainEvent) + { + domainEvent.Sequence = ++LastEventSequence; + ApplyEventToInternalState(domainEvent); + domainEvent.AggregateRootId = Id; + domainEvent.EventDate = DateTime.UtcNow; + + EventModifier.Modify(domainEvent); + + _uncommittedEvents.Enqueue(domainEvent); + } + + public void CommitEvents() + { + _uncommittedEvents.Clear(); + _entities.ForEach(entity => entity.CommitEvents()); + } + + public void RegisterEntity(Entity entity) + { + entity.AggregateRoot = this; + _entities.Add(entity); + } + + private void ApplyEventToInternalState(DomainEvent domainEvent) + { + var domainEventType = domainEvent.GetType(); + var domainEventTypeName = domainEventType.Name; + var aggregateRootType = GetType(); + + var eventHandlerMethodName = GetEventHandlerMethodName(domainEventTypeName); + var methodInfo = aggregateRootType.GetMethod(eventHandlerMethodName, + BindingFlags.Instance | BindingFlags.Public | + BindingFlags.NonPublic, null, new[] { domainEventType }, null); + + if (methodInfo != null && EventHandlerMethodInfoHasCorrectParameter(methodInfo, domainEventType)) + { + methodInfo.Invoke(this, new[] { domainEvent }); + } + + ApplyEventToEntities(domainEvent); + } + + private void ApplyEventToEntities(DomainEvent domainEvent) + { + if (!(domainEvent is EntityDomainEvent entityDomainEvent)) + { + return; + } + + var list = _entities.Where(entity => entity.Id == entityDomainEvent.EntityId).ToList(); + list.ForEach(entity => entity.ApplyHistoricalEvents(entityDomainEvent)); + } + + private static string GetEventHandlerMethodName(string domainEventTypeName) + { + var eventIndex = domainEventTypeName.LastIndexOf("Event"); + return "On" + domainEventTypeName.Remove(eventIndex, 5); + } + + private static bool EventHandlerMethodInfoHasCorrectParameter(MethodBase eventHandlerMethodInfo, + Type domainEventType) + { + var parameters = eventHandlerMethodInfo.GetParameters(); + return parameters.Length == 1 && parameters[0].ParameterType == domainEventType; + } + } } \ No newline at end of file diff --git a/src/EventSourcingCQRS/Domain/AggregateRootNotFoundException.cs b/src/EventSourcingCQRS/Domain/AggregateRootNotFoundException.cs new file mode 100644 index 0000000..fd862c2 --- /dev/null +++ b/src/EventSourcingCQRS/Domain/AggregateRootNotFoundException.cs @@ -0,0 +1,18 @@ +namespace EventSourcingCQRS.Domain +{ + public class AggregateRootNotFoundException : Exception + { + public AggregateRootNotFoundException() + { + + } + public AggregateRootNotFoundException(Guid aggregateRootId, Type type) + { + AggregateRootId = aggregateRootId; + Type = type; + } + + public Guid AggregateRootId { get; } + public Type Type { get; } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Domain/AssemblyTypeCatalog.cs b/src/EventSourcingCQRS/Domain/AssemblyTypeCatalog.cs new file mode 100644 index 0000000..693d177 --- /dev/null +++ b/src/EventSourcingCQRS/Domain/AssemblyTypeCatalog.cs @@ -0,0 +1,110 @@ +using System.Diagnostics; +using System.Reflection; + +namespace EventSourcingCQRS.Domain +{ + public class AssemblyTypeCatalog : ITypeCatalog + { + private readonly IEnumerable _loadedTypes; + + //public AssemblyTypeCatalog(IEnumerable assemblies) + //{ + // assemblies = AppDomain.CurrentDomain.GetAssemblies() + // .Where(a => a.FullName.Contains("EventSourcingCQRS")); + // _loadedTypes = LoadTypes(assemblies); + //} + + public AssemblyTypeCatalog(IEnumerable types) + { + _loadedTypes = LoadTypes(types); + } + + public Type[] LoadedTypes => _loadedTypes.ToArray(); + + //public Type[] GetDerivedTypes(Type type) + //{ + // return ( + // from derivedType in _loadedTypes + // where type != derivedType + // where type.IsAssignableFrom(derivedType) + // select derivedType).ToArray(); + //} + + //public Type[] GetDerivedTypes() + //{ + // return GetDerivedTypes(typeof(T)); + //} + + //public Type[] GetGenericInterfaceImplementations(Type type) + //{ + // return (from derivedType in _loadedTypes + // from interfaceType in derivedType.GetInterfaces() + // where interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == type + // select derivedType).Distinct().ToArray(); + //} + + //public Type[] GetInterfaceImplementations(Type type) + //{ + // return (from derivedType in _loadedTypes + // where !derivedType.IsInterface + // from interfaceType in derivedType.GetInterfaces() + // where interfaceType == type + // select derivedType).Distinct().ToArray(); + //} + + //public Type[] GetInterfaceImplementations() + //{ + // return GetInterfaceImplementations(typeof(T)); + //} + + //public Type GetTypeFromUnqualifiedTypeName(string unqualifiedTypeName) + //{ + // var assembly = + // LoadedTypes.FirstOrDefault(c => c.FullName != null && c.FullName.EndsWith(unqualifiedTypeName)); + // if (assembly == null || string.IsNullOrWhiteSpace(assembly.AssemblyQualifiedName)) + // { + // return null; + // } + + // return Type.GetType(assembly.AssemblyQualifiedName); + //} + + //public Type GetTypeFromQualifiedTypeName(string qualifiedTypeName) + //{ + // var assembly = LoadedTypes.FirstOrDefault(c => c.AssemblyQualifiedName == qualifiedTypeName); + // if (assembly == null || string.IsNullOrWhiteSpace(assembly.AssemblyQualifiedName)) + // { + // return null; + // } + + // return Type.GetType(assembly.AssemblyQualifiedName); + //} + + private static IEnumerable LoadTypes(IEnumerable types) + { + return types; + } + + private static IEnumerable LoadTypes(IEnumerable assemblies) + { + var loadedTypes = new List(); + foreach (var assembly in assemblies) + { + try + { + var types = assembly.GetTypes(); + loadedTypes.AddRange(types); + } + catch (ReflectionTypeLoadException exception) + { + exception.LoaderExceptions + .Select(e => e.Message) + .Distinct().ToList() + .ForEach(message => Debug.WriteLine(message)); + } + } + + return loadedTypes; + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Domain/DomainRepository.cs b/src/EventSourcingCQRS/Domain/DomainRepository.cs new file mode 100644 index 0000000..e753e9e --- /dev/null +++ b/src/EventSourcingCQRS/Domain/DomainRepository.cs @@ -0,0 +1,136 @@ +using System.Collections.ObjectModel; +using EventSourcingCQRS.Eventing; + +namespace EventSourcingCQRS.Domain +{ + public class DomainRepository : IDomainRepository + { + private readonly IEventBus _eventBus; + private readonly IEventStore _eventStore; + private readonly ISnapshotStore _snapshotStore; + + public DomainRepository(IEventStore eventStore, ISnapshotStore snapshotStore, IEventBus eventBus) + { + _eventStore = eventStore; + _snapshotStore = snapshotStore; + _eventBus = eventBus; + } + + public virtual async Task GetById(Guid aggregateRootId, + CancellationToken cancellationToken) where TAggregateRoot : AggregateRoot, new() + { + var aggregateRoot = new TAggregateRoot(); + var snapshot = await GetSnapshotFromSnapshotStore(aggregateRootId, cancellationToken); + var lastEventSequence = snapshot == null || (aggregateRoot is not ISnapshotOriginator) + ? 0 + : snapshot.LastEventSequence; + var domainEventsAsync = await _eventStore.GetEvents(aggregateRootId, lastEventSequence); + var domainEvents = domainEventsAsync.ToArray(); + + if (lastEventSequence == 0 && domainEvents.Length == 0) + { + return null; + } + + LoadSnapshot(aggregateRoot, snapshot); + aggregateRoot.LoadFromHistoricalEvents(domainEvents); + + return aggregateRoot; + } + + public virtual async Task GetExistingById(Guid aggregateRootId, + CancellationToken cancellationToken) where TAggregateRoot : AggregateRoot, new() + { + var aggregateRoot = await GetById(aggregateRootId, cancellationToken); + + if (aggregateRoot == null) + { + throw new AggregateRootNotFoundException(aggregateRootId, typeof(TAggregateRoot)); + } + + return aggregateRoot; + } + + public async Task GetExistingByIdUpToSequence(Guid aggregateRootId, + int sequence, + CancellationToken cancellationToken) where TAggregateRoot : AggregateRoot, new() + { + var aggregateRoot = new TAggregateRoot(); + var snapshot = await GetSnapshotFromSnapshotStore(aggregateRootId, cancellationToken); + + var lastEventSequence = sequence; + + var domainEventsAsync = await _eventStore.GetEventsUpToSequence(aggregateRootId, lastEventSequence); + var domainEvents = domainEventsAsync.ToArray(); + + if (lastEventSequence == 0 && domainEvents.Length == 0) + { + return null; + } + + aggregateRoot.LoadFromHistoricalEvents(domainEvents); + + return aggregateRoot; + } + + public virtual async Task Save(AggregateRoot aggregateRoot, CancellationToken cancellationToken) + { + if (aggregateRoot.UncommittedEvents.Count == 0) + { + return; + } + + var domainEvents = aggregateRoot.UncommittedEvents; + + await _eventStore.Insert(domainEvents); + await _eventBus.PublishEvents(domainEvents, cancellationToken); + + aggregateRoot.CommitEvents(); + + await SaveSnapshot(aggregateRoot, domainEvents, cancellationToken); + } + + private async Task SaveSnapshot(AggregateRoot aggregateRoot, ReadOnlyCollection domainEvents, CancellationToken cancellationToken) + { + if (aggregateRoot is not ISnapshotOriginator snapshotOriginator) + { + return; + } + + var previousSnapshot = await _snapshotStore.GetSnapshot(aggregateRoot.Id, cancellationToken); + + if (!snapshotOriginator.ShouldTakeSnapshot(previousSnapshot, domainEvents)) + { + return; + } + + var snapshot = snapshotOriginator.GetSnapshot(); + snapshot.AggregateRootId = aggregateRoot.Id; + snapshot.LastEventSequence = aggregateRoot.LastEventSequence; + + await _snapshotStore.SaveSnapshot(snapshot, cancellationToken); + } + + private static void LoadSnapshot(AggregateRoot aggregateRoot, Snapshot snapshot) + { + if (snapshot == null || !(aggregateRoot is ISnapshotOriginator snapshotOriginator)) + { + return; + } + + snapshotOriginator.LoadSnapshot(snapshot); + aggregateRoot.Id = snapshot.AggregateRootId; + aggregateRoot.LastEventSequence = snapshot.LastEventSequence; + } + + public async Task GetSnapshotFromSnapshotStore(Guid aggregateRootId, CancellationToken cancellationToken) + { + return await _snapshotStore.GetSnapshot(aggregateRootId, cancellationToken); + } + + public async Task SaveSnapshotToSnapshotStore(Snapshot snapshot, CancellationToken cancellationToken) + { + await _snapshotStore.SaveSnapshot(snapshot, cancellationToken); + } + } +} \ No newline at end of file diff --git a/src/SimpleCqrs/Domain/Entity.cs b/src/EventSourcingCQRS/Domain/Entity.cs similarity index 51% rename from src/SimpleCqrs/Domain/Entity.cs rename to src/EventSourcingCQRS/Domain/Entity.cs index 5a38600..2033775 100644 --- a/src/SimpleCqrs/Domain/Entity.cs +++ b/src/EventSourcingCQRS/Domain/Entity.cs @@ -1,74 +1,72 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Reflection; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.Domain -{ - public abstract class Entity : IHaveATestMode - { - private readonly Queue uncommittedEvents = new Queue(); - - public AggregateRoot AggregateRoot { get; set; } - public Guid Id { get; protected set; } - bool IHaveATestMode.IsInTestMode { get; set; } - - public ReadOnlyCollection UncommittedEvents - { - get { return new ReadOnlyCollection(uncommittedEvents.ToList()); } - } - - public void Apply(EntityDomainEvent domainEvent) - { - domainEvent.EntityId = Id; - - if(!((IHaveATestMode)this).IsInTestMode) - AggregateRoot.Apply(domainEvent); - - uncommittedEvents.Enqueue(domainEvent); - ApplyEventToInternalState(domainEvent); - } - - public void ApplyHistoricalEvents(params EntityDomainEvent[] entityDomainEvents) - { - foreach(var entityDomainEvent in entityDomainEvents) - { - ApplyEventToInternalState(entityDomainEvent); - } - } - - public void CommitEvents() - { - uncommittedEvents.Clear(); - } - - private void ApplyEventToInternalState(EntityDomainEvent domainEvent) - { - var domainEventType = domainEvent.GetType(); - var domainEventTypeName = domainEventType.Name; - var entityType = GetType(); - - var methodInfo = entityType.GetMethod(GetEventHandlerMethodName(domainEventTypeName), - BindingFlags.Instance | BindingFlags.Public | - BindingFlags.NonPublic, null, new[] {domainEventType}, null); - - if(methodInfo == null || !EventHandlerMethodInfoHasCorrectParameter(methodInfo, domainEventType)) return; - - methodInfo.Invoke(this, new[] {domainEvent}); - } - - private static string GetEventHandlerMethodName(string domainEventTypeName) - { - var eventIndex = domainEventTypeName.LastIndexOf("Event"); - return "On" + domainEventTypeName.Remove(eventIndex, 5); - } - - private static bool EventHandlerMethodInfoHasCorrectParameter(MethodInfo eventHandlerMethodInfo, Type domainEventType) - { - var parameters = eventHandlerMethodInfo.GetParameters(); - return parameters.Length == 1 && parameters[0].ParameterType == domainEventType; - } - } +using System.Collections.ObjectModel; +using System.Reflection; +using EventSourcingCQRS.Eventing; + +namespace EventSourcingCQRS.Domain +{ + public abstract class Entity + { + private readonly Queue _uncommittedEvents = new Queue(); + + public AggregateRoot AggregateRoot { get; set; } + + public Guid Id { get; protected set; } + + public ReadOnlyCollection UncommittedEvents => + new ReadOnlyCollection(_uncommittedEvents.ToList()); + + public void Apply(EntityDomainEvent domainEvent) + { + domainEvent.EntityId = Id; + + AggregateRoot.Apply(domainEvent); + + _uncommittedEvents.Enqueue(domainEvent); + ApplyEventToInternalState(domainEvent); + } + + public void ApplyHistoricalEvents(params EntityDomainEvent[] entityDomainEvents) + { + foreach (var entityDomainEvent in entityDomainEvents) + { + ApplyEventToInternalState(entityDomainEvent); + } + } + + public void CommitEvents() + { + _uncommittedEvents.Clear(); + } + + private void ApplyEventToInternalState(EntityDomainEvent domainEvent) + { + var domainEventType = domainEvent.GetType(); + var domainEventTypeName = domainEventType.Name; + var entityType = GetType(); + + var methodInfo = entityType.GetMethod(GetEventHandlerMethodName(domainEventTypeName), + BindingFlags.Instance | BindingFlags.Public | + BindingFlags.NonPublic, null, new[] { domainEventType }, null); + + if (methodInfo == null || !EventHandlerMethodInfoHasCorrectParameter(methodInfo, domainEventType)) + { + return; + } + + methodInfo.Invoke(this, new[] { domainEvent }); + } + + private static string GetEventHandlerMethodName(string domainEventTypeName) + { + var eventIndex = domainEventTypeName.LastIndexOf("Event"); + return "On" + domainEventTypeName.Remove(eventIndex, 5); + } + + private static bool EventHandlerMethodInfoHasCorrectParameter(MethodInfo eventHandlerMethodInfo, + Type domainEventType) + { + var parameters = eventHandlerMethodInfo.GetParameters(); + return parameters.Length == 1 && parameters[0].ParameterType == domainEventType; + } + } } \ No newline at end of file diff --git a/src/SimpleCqrs/Domain/EntityCollection.cs b/src/EventSourcingCQRS/Domain/EntityCollection.cs similarity index 61% rename from src/SimpleCqrs/Domain/EntityCollection.cs rename to src/EventSourcingCQRS/Domain/EntityCollection.cs index 32af5f3..ccb0599 100644 --- a/src/SimpleCqrs/Domain/EntityCollection.cs +++ b/src/EventSourcingCQRS/Domain/EntityCollection.cs @@ -1,27 +1,25 @@ -using System; -using System.Collections.ObjectModel; -using System.Linq; - -namespace SimpleCqrs.Domain -{ - public class EntityCollection : Collection where TEntity : Entity - { - private readonly AggregateRoot aggregateRoot; - - public EntityCollection(AggregateRoot aggregateRoot) - { - this.aggregateRoot = aggregateRoot; - } - - public TEntity FindById(Guid id) - { - return this.SingleOrDefault(entity => entity.Id == id); - } - - protected override void InsertItem(int index, TEntity entity) - { - aggregateRoot.RegisterEntity(entity); - base.InsertItem(index, entity); - } - } +using System.Collections.ObjectModel; + +namespace EventSourcingCQRS.Domain +{ + public class EntityCollection : Collection where TEntity : Entity + { + private readonly AggregateRoot _aggregateRoot; + + public EntityCollection(AggregateRoot aggregateRoot) + { + _aggregateRoot = aggregateRoot; + } + + public TEntity FindById(Guid id) + { + return this.SingleOrDefault(entity => entity.Id == id); + } + + protected override void InsertItem(int index, TEntity entity) + { + _aggregateRoot.RegisterEntity(entity); + base.InsertItem(index, entity); + } + } } \ No newline at end of file diff --git a/src/EventSourcingCQRS/Domain/Enumeration.cs b/src/EventSourcingCQRS/Domain/Enumeration.cs new file mode 100644 index 0000000..2075d60 --- /dev/null +++ b/src/EventSourcingCQRS/Domain/Enumeration.cs @@ -0,0 +1,84 @@ +using System.Reflection; + +namespace EventSourcingCQRS.Domain +{ + public abstract class Enumeration : IComparable + { + protected Enumeration(int id, string name) + { + Id = id; + Name = name; + } + + public string Name { get; } + + public int Id { get; } + + public int CompareTo(object other) + { + return Id.CompareTo(((Enumeration)other).Id); + } + + public override string ToString() + { + return Name; + } + + public static IEnumerable GetAll() where T : Enumeration + { + var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly); + + return fields.Select(f => f.GetValue(null)).Cast(); + } + + public override bool Equals(object obj) + { + var otherValue = obj as Enumeration; + + if (otherValue == null) + { + return false; + } + + var typeMatches = GetType().Equals(obj.GetType()); + var valueMatches = Id.Equals(otherValue.Id); + + return typeMatches && valueMatches; + } + + public override int GetHashCode() + { + return Id.GetHashCode(); + } + + public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue) + { + var absoluteDifference = Math.Abs(firstValue.Id - secondValue.Id); + return absoluteDifference; + } + + public static T FromValue(int value) where T : Enumeration + { + var matchingItem = Parse(value, "value", item => item.Id == value); + return matchingItem; + } + + public static T FromDisplayName(string displayName) where T : Enumeration + { + var matchingItem = Parse(displayName, "display name", item => item.Name == displayName); + return matchingItem; + } + + public static T Parse(TK value, string description, Func predicate) where T : Enumeration + { + var matchingItem = GetAll().FirstOrDefault(predicate); + + if (matchingItem == null) + { + throw new InvalidOperationException($"'{value}' is not a valid {description} in {typeof(T)}"); + } + + return matchingItem; + } + } +} \ No newline at end of file diff --git a/src/SimpleCqrs/Domain/EventModifier.cs b/src/EventSourcingCQRS/Domain/EventModifier.cs similarity index 72% rename from src/SimpleCqrs/Domain/EventModifier.cs rename to src/EventSourcingCQRS/Domain/EventModifier.cs index 6cfd1c2..85da3de 100644 --- a/src/SimpleCqrs/Domain/EventModifier.cs +++ b/src/EventSourcingCQRS/Domain/EventModifier.cs @@ -1,16 +1,17 @@ -using System; -using SimpleCqrs.Eventing; +using EventSourcingCQRS.Eventing; -namespace SimpleCqrs.Domain +namespace EventSourcingCQRS.Domain { public static class EventModifier { public static IEventModification Modification; - + public static void Modify(DomainEvent e) { if (Modification != null) + { Modification.Apply(e); + } } } } \ No newline at end of file diff --git a/src/EventSourcingCQRS/Domain/IAggregateRoot.cs b/src/EventSourcingCQRS/Domain/IAggregateRoot.cs new file mode 100644 index 0000000..3c3a814 --- /dev/null +++ b/src/EventSourcingCQRS/Domain/IAggregateRoot.cs @@ -0,0 +1,6 @@ +namespace EventSourcingCQRS.Domain +{ + public interface IAggregateRoot + { + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Domain/IDomainRepository.cs b/src/EventSourcingCQRS/Domain/IDomainRepository.cs new file mode 100644 index 0000000..8175fa2 --- /dev/null +++ b/src/EventSourcingCQRS/Domain/IDomainRepository.cs @@ -0,0 +1,20 @@ +namespace EventSourcingCQRS.Domain +{ + public interface IDomainRepository + { + Task GetById(Guid aggregateRootId, CancellationToken cancellationToken) + where TAggregateRoot : AggregateRoot, new(); + + Task GetExistingById(Guid aggregateRootId, CancellationToken cancellationToken) + where TAggregateRoot : AggregateRoot, new(); + + Task GetExistingByIdUpToSequence(Guid aggregateRootId, int sequence, + CancellationToken cancellationToken) where TAggregateRoot : AggregateRoot, new(); + + Task Save(AggregateRoot aggregateRoot, CancellationToken cancellationToken); + + Task GetSnapshotFromSnapshotStore(Guid aggregateRootId, CancellationToken cancellationToken); + + Task SaveSnapshotToSnapshotStore(Snapshot snapshot, CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/src/SimpleCqrs/Domain/IEventModification.cs b/src/EventSourcingCQRS/Domain/IEventModification.cs similarity index 56% rename from src/SimpleCqrs/Domain/IEventModification.cs rename to src/EventSourcingCQRS/Domain/IEventModification.cs index 15748be..b650092 100644 --- a/src/SimpleCqrs/Domain/IEventModification.cs +++ b/src/EventSourcingCQRS/Domain/IEventModification.cs @@ -1,6 +1,6 @@ -using SimpleCqrs.Eventing; +using EventSourcingCQRS.Eventing; -namespace SimpleCqrs.Domain +namespace EventSourcingCQRS.Domain { public interface IEventModification { diff --git a/src/EventSourcingCQRS/Domain/IRepository.cs b/src/EventSourcingCQRS/Domain/IRepository.cs new file mode 100644 index 0000000..2b14c3e --- /dev/null +++ b/src/EventSourcingCQRS/Domain/IRepository.cs @@ -0,0 +1,7 @@ +namespace EventSourcingCQRS.Domain +{ + public interface IRepository where T : IAggregateRoot + { + IUnitOfWork UnitOfWork { get; } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Domain/ISnapshotOriginator.cs b/src/EventSourcingCQRS/Domain/ISnapshotOriginator.cs new file mode 100644 index 0000000..57fe697 --- /dev/null +++ b/src/EventSourcingCQRS/Domain/ISnapshotOriginator.cs @@ -0,0 +1,14 @@ +using System.Collections.ObjectModel; +using EventSourcingCQRS.Eventing; + +namespace EventSourcingCQRS.Domain +{ + public interface ISnapshotOriginator + { + Snapshot GetSnapshot(); + + void LoadSnapshot(Snapshot snapshot); + + bool ShouldTakeSnapshot(Snapshot previousSnapshot, ReadOnlyCollection domainEvents); + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Domain/ITypeCatalog.cs b/src/EventSourcingCQRS/Domain/ITypeCatalog.cs new file mode 100644 index 0000000..8f95bad --- /dev/null +++ b/src/EventSourcingCQRS/Domain/ITypeCatalog.cs @@ -0,0 +1,21 @@ +namespace EventSourcingCQRS.Domain +{ + public interface ITypeCatalog + { + Type[] LoadedTypes { get; } + + //Type[] GetDerivedTypes(Type type); + + //Type[] GetDerivedTypes(); + + //Type[] GetGenericInterfaceImplementations(Type type); + + //Type[] GetInterfaceImplementations(Type type); + + //Type[] GetInterfaceImplementations(); + + //Type GetTypeFromUnqualifiedTypeName(string unqualifiedTypeName); + + //Type GetTypeFromQualifiedTypeName(string qualifiedTypeName); + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Domain/IUnitOfWork.cs b/src/EventSourcingCQRS/Domain/IUnitOfWork.cs new file mode 100644 index 0000000..ec74b19 --- /dev/null +++ b/src/EventSourcingCQRS/Domain/IUnitOfWork.cs @@ -0,0 +1,9 @@ +namespace EventSourcingCQRS.Domain +{ + public interface IUnitOfWork : IDisposable + { + Task SaveChangesAsync(CancellationToken cancellationToken = default); + + Task SaveEntitiesAsync(CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/SimpleCqrs/Domain/Snapshot.cs b/src/EventSourcingCQRS/Domain/Snapshot.cs similarity index 57% rename from src/SimpleCqrs/Domain/Snapshot.cs rename to src/EventSourcingCQRS/Domain/Snapshot.cs index acb011d..ed9d872 100644 --- a/src/SimpleCqrs/Domain/Snapshot.cs +++ b/src/EventSourcingCQRS/Domain/Snapshot.cs @@ -1,10 +1,11 @@ -using System; - -namespace SimpleCqrs.Domain -{ - public class Snapshot - { - public Guid AggregateRootId { get; set; } - public int LastEventSequence { get; set; } - } +using System.Diagnostics.CodeAnalysis; + +namespace EventSourcingCQRS.Domain +{ + [ExcludeFromCodeCoverage] + public class Snapshot + { + public Guid AggregateRootId { get; set; } + public int LastEventSequence { get; set; } + } } \ No newline at end of file diff --git a/src/EventSourcingCQRS/Domain/SnapshotAggregateRoot.cs b/src/EventSourcingCQRS/Domain/SnapshotAggregateRoot.cs new file mode 100644 index 0000000..16aa088 --- /dev/null +++ b/src/EventSourcingCQRS/Domain/SnapshotAggregateRoot.cs @@ -0,0 +1,28 @@ +namespace EventSourcingCQRS.Domain +{ + /// + /// + /// Class to inherit aggregates that should be snapshotted from. + /// + /// Type of memento object capturing aggregate state + public abstract class SnapshotAggregateRoot : AggregateRoot where T : Snapshot + { + public T GetSnapshot() + { + var snapshot = CreateSnapshot(); + snapshot.AggregateRootId = Id; + return snapshot; + } + + public void Restore(T snapshot) + { + Id = snapshot.AggregateRootId; + LastEventSequence = snapshot.LastEventSequence; + RestoreFromSnapshot(snapshot); + } + + protected abstract T CreateSnapshot(); + + protected abstract void RestoreFromSnapshot(T snapshot); + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Domain/ValueObject.cs b/src/EventSourcingCQRS/Domain/ValueObject.cs new file mode 100644 index 0000000..d2ce4cb --- /dev/null +++ b/src/EventSourcingCQRS/Domain/ValueObject.cs @@ -0,0 +1,60 @@ +namespace EventSourcingCQRS.Domain +{ + public abstract class ValueObject + { + protected static bool EqualOperator(ValueObject left, ValueObject right) + { + if (ReferenceEquals(left, null) ^ ReferenceEquals(right, null)) + { + return false; + } + + return ReferenceEquals(left, null) || left.Equals(right); + } + + protected static bool NotEqualOperator(ValueObject left, ValueObject right) + { + return !EqualOperator(left, right); + } + + protected abstract IEnumerable GetAtomicValues(); + + public override bool Equals(object obj) + { + if (obj == null || obj.GetType() != GetType()) + { + return false; + } + + var other = (ValueObject)obj; + var thisValues = GetAtomicValues().GetEnumerator(); + var otherValues = other.GetAtomicValues().GetEnumerator(); + while (thisValues.MoveNext() && otherValues.MoveNext()) + { + if (ReferenceEquals(thisValues.Current, null) ^ ReferenceEquals(otherValues.Current, null)) + { + return false; + } + + if (thisValues.Current != null && !thisValues.Current.Equals(otherValues.Current)) + { + return false; + } + } + + return !thisValues.MoveNext() && !otherValues.MoveNext(); + } + + public override int GetHashCode() + { + return GetAtomicValues() + .Select(x => x != null ? x.GetHashCode() : 0) + .Aggregate((x, y) => x ^ y); + } + + public ValueObject GetCopy() + { + return MemberwiseClone() as ValueObject; + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/EventSourcingCQRS.csproj b/src/EventSourcingCQRS/EventSourcingCQRS.csproj new file mode 100644 index 0000000..879337f --- /dev/null +++ b/src/EventSourcingCQRS/EventSourcingCQRS.csproj @@ -0,0 +1,42 @@ + + + + net7.0 + enable + enable + True + Event Sourcing CQRS + A simple framework to allow the creation of Event Sourced applications using the CQRS pattern. + https://github.com/LyndseyPaxton/EventSourcingCQRS + EventSourcing CQRS EventSourced + EventSourcingCQRS.Beta + $([System.DateTime]::Now.ToString("yyyy.MM.dd.HHmm")) + Lyndsey Paxton + Mental Monkey Software + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/EventSourcingCQRS/EventSourcingCqrsRegistration.cs b/src/EventSourcingCQRS/EventSourcingCqrsRegistration.cs new file mode 100644 index 0000000..97a4de6 --- /dev/null +++ b/src/EventSourcingCQRS/EventSourcingCqrsRegistration.cs @@ -0,0 +1,69 @@ +using EventSourcingCQRS.Commanding; +using EventSourcingCQRS.Eventing; +using EventSourcingCQRS.Querying; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace EventSourcingCQRS +{ + public static class EventSourcingCqrsRegistration + { + public static IServiceCollection AddCommandHandlers(this IServiceCollection services) + { + services + .TryAddSingleton(); + + services + .Scan(selector => + { + selector.FromApplicationDependencies() + .AddClasses(filter => + { + filter.AssignableTo(typeof(ICommandHandler<,>)); + }) + .AsImplementedInterfaces() + .WithSingletonLifetime(); + }); + + return services; + } + + public static IServiceCollection AddEventHandlers(this IServiceCollection services) + { + services + .Scan(selector => + { + selector.FromApplicationDependencies() + .AddClasses(filter => + { + filter.AssignableTo(typeof(IHandleDomainEvents<>)); + }) + .AsImplementedInterfaces() + //.WithSingletonLifetime(); + .WithScopedLifetime(); + }); + + return services; + } + + public static IServiceCollection AddQueryHandlers(this IServiceCollection services) + { + services + .TryAddSingleton(); + + services + .Scan(selector => + { + selector.FromAssemblies() + .AddClasses(filter => + { + filter.AssignableTo(typeof(IQueryHandler<,>)); + }) + .AsImplementedInterfaces() + .WithSingletonLifetime(); + }); + + return services; + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Eventing/DomainEvent.cs b/src/EventSourcingCQRS/Eventing/DomainEvent.cs new file mode 100644 index 0000000..de2b5ca --- /dev/null +++ b/src/EventSourcingCQRS/Eventing/DomainEvent.cs @@ -0,0 +1,13 @@ +using System.Diagnostics.CodeAnalysis; + +namespace EventSourcingCQRS.Eventing +{ + [ExcludeFromCodeCoverage] + [Serializable] + public partial class DomainEvent + { + public Guid AggregateRootId { get; set; } + public int Sequence { get; set; } + public DateTimeOffset EventDate { get; set; } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Eventing/DomainEventHandlerFactory.cs b/src/EventSourcingCQRS/Eventing/DomainEventHandlerFactory.cs new file mode 100644 index 0000000..e93904d --- /dev/null +++ b/src/EventSourcingCQRS/Eventing/DomainEventHandlerFactory.cs @@ -0,0 +1,40 @@ +using System.Diagnostics.CodeAnalysis; +using Microsoft.Extensions.DependencyInjection; + +namespace EventSourcingCQRS.Eventing +{ + [ExcludeFromCodeCoverage] + public class DomainEventHandlerFactory : IDomainEventHandlerFactory + { + private readonly IServiceProvider _serviceLocator; + private readonly IServiceScopeFactory _serviceScopeFactory; + + public DomainEventHandlerFactory(IServiceProvider serviceLocator, IServiceScopeFactory serviceScopeFactory) + { + _serviceLocator = serviceLocator; + _serviceScopeFactory = serviceScopeFactory; + } + + public object Create(Type domainEventHandlerType) + { + //return _serviceLocator.GetService(domainEventHandlerType); + + try + { + var eventHandler = _serviceLocator.GetService(domainEventHandlerType); + + if (eventHandler == null) + { + eventHandler = ActivatorUtilities.CreateInstance(_serviceLocator, domainEventHandlerType); + } + + return eventHandler; + } + catch + { + using var scope = _serviceScopeFactory.CreateScope(); + return scope.ServiceProvider.GetService(domainEventHandlerType); + } + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Eventing/DomainEventReplayer.cs b/src/EventSourcingCQRS/Eventing/DomainEventReplayer.cs new file mode 100644 index 0000000..c294743 --- /dev/null +++ b/src/EventSourcingCQRS/Eventing/DomainEventReplayer.cs @@ -0,0 +1,58 @@ +namespace EventSourcingCQRS.Eventing +{ + public class DomainEventReplayer : IDomainEventReplayer + { + private readonly IEventStore _eventStore; + private readonly IEventBus _eventBus; + + public DomainEventReplayer(IEventStore eventStore, IEventBus eventBus) + { + _eventStore = eventStore; + _eventBus = eventBus; + } + + public async Task ReplayEventsForHandlerType(Type handlerType, CancellationToken cancellationToken) + { + await ReplayEventsForHandlerType(handlerType, DateTime.MinValue, DateTime.MaxValue, cancellationToken); + } + + public async Task ReplayEventsForHandlerType(Type handlerType, Guid aggregateRootId, CancellationToken cancellationToken) + { + var domainEventTypes = GetDomainEventTypesHandledByHandler(handlerType); + var domainEvents = await _eventStore.GetEventsByEventTypes(domainEventTypes, aggregateRootId); + await _eventBus.PublishEvents(domainEvents, cancellationToken); + } + + public async Task ReplayEventsForHandlerType(Type handlerType, Guid aggregateRootId, int lastSequenceNo, + CancellationToken cancellationToken) + { + var domainEventTypes = GetDomainEventTypesHandledByHandler(handlerType); + var domainEvents = await _eventStore.GetEventsByEventTypesUpToSequence(domainEventTypes, aggregateRootId, lastSequenceNo); + await _eventBus.PublishEvents(domainEvents, cancellationToken); + } + + public async Task ReplayEventsForHandlerType(Type handlerType, DateTime startDate, DateTime endDate, CancellationToken cancellationToken) + { + var domainEventTypes = GetDomainEventTypesHandledByHandler(handlerType); + var domainEvents = await _eventStore.GetEventsByEventTypes(domainEventTypes, startDate, endDate); + await _eventBus.PublishEvents(domainEvents, cancellationToken); + } + + private static IEnumerable GetDomainEventTypesHandledByHandler(Type handlerType) + { + + var interfaces = handlerType.GetInterfaces(); + var zero = interfaces[0]; + var genericType = zero.IsGenericType; + var t = zero.GetGenericTypeDefinition(); + var isSame = t == typeof(IHandleDomainEvents<>); + + + + return (from i in handlerType.GetInterfaces() + where i.IsGenericType + where i.GetGenericTypeDefinition() == typeof(IHandleDomainEvents<>) + select i.GetGenericArguments()[0]).ToList(); + } + } +} \ No newline at end of file diff --git a/src/SimpleCqrs/Eventing/EntityDomainEvent.cs b/src/EventSourcingCQRS/Eventing/EntityDomainEvent.cs similarity index 53% rename from src/SimpleCqrs/Eventing/EntityDomainEvent.cs rename to src/EventSourcingCQRS/Eventing/EntityDomainEvent.cs index 6f37c33..cb773a7 100644 --- a/src/SimpleCqrs/Eventing/EntityDomainEvent.cs +++ b/src/EventSourcingCQRS/Eventing/EntityDomainEvent.cs @@ -1,10 +1,11 @@ -using System; - -namespace SimpleCqrs.Eventing -{ - [Serializable] - public class EntityDomainEvent : DomainEvent - { - public Guid EntityId { get; set; } - } +using System.Diagnostics.CodeAnalysis; + +namespace EventSourcingCQRS.Eventing +{ + [ExcludeFromCodeCoverage] + [Serializable] + public class EntityDomainEvent : DomainEvent + { + public Guid EntityId { get; set; } + } } \ No newline at end of file diff --git a/src/EventSourcingCQRS/Eventing/EventQueryCriteria.cs b/src/EventSourcingCQRS/Eventing/EventQueryCriteria.cs new file mode 100644 index 0000000..fb44db7 --- /dev/null +++ b/src/EventSourcingCQRS/Eventing/EventQueryCriteria.cs @@ -0,0 +1,18 @@ +namespace EventSourcingCQRS.Eventing +{ + public class EventQueryCriteria + { + public string Name { get; set; } + public Type Type { get; protected set; } + } + + public class EventQueryCriteria : EventQueryCriteria + { + public EventQueryCriteria() + { + Type = typeof(T); + } + public T Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/SimpleCqrs/Eventing/IDomainEventHandlerFactory.cs b/src/EventSourcingCQRS/Eventing/IDomainEventHandlerFactory.cs similarity index 67% rename from src/SimpleCqrs/Eventing/IDomainEventHandlerFactory.cs rename to src/EventSourcingCQRS/Eventing/IDomainEventHandlerFactory.cs index 9221115..bcdd413 100644 --- a/src/SimpleCqrs/Eventing/IDomainEventHandlerFactory.cs +++ b/src/EventSourcingCQRS/Eventing/IDomainEventHandlerFactory.cs @@ -1,9 +1,7 @@ -using System; - -namespace SimpleCqrs.Eventing -{ - public interface IDomainEventHandlerFactory - { - object Create(Type domainEventHandlerType); - } +namespace EventSourcingCQRS.Eventing +{ + public interface IDomainEventHandlerFactory + { + object Create(Type domainEventHandlerType); + } } \ No newline at end of file diff --git a/src/EventSourcingCQRS/Eventing/IDomainEventReplayer.cs b/src/EventSourcingCQRS/Eventing/IDomainEventReplayer.cs new file mode 100644 index 0000000..7fe6981 --- /dev/null +++ b/src/EventSourcingCQRS/Eventing/IDomainEventReplayer.cs @@ -0,0 +1,10 @@ +namespace EventSourcingCQRS.Eventing +{ + public interface IDomainEventReplayer + { + Task ReplayEventsForHandlerType(Type handlerType, CancellationToken cancellationToken); + Task ReplayEventsForHandlerType(Type handlerType, Guid aggregateRootId, CancellationToken cancellationToken); + Task ReplayEventsForHandlerType(Type handlerType, Guid aggregateRootId, int lastSequenceNo, CancellationToken cancellationToken); + Task ReplayEventsForHandlerType(Type handlerType, DateTime startDate, DateTime endDate, CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Eventing/IEventBus.cs b/src/EventSourcingCQRS/Eventing/IEventBus.cs new file mode 100644 index 0000000..822dd21 --- /dev/null +++ b/src/EventSourcingCQRS/Eventing/IEventBus.cs @@ -0,0 +1,9 @@ +namespace EventSourcingCQRS.Eventing +{ + public interface IEventBus + { + Task Publish(DomainEvent domainEvent, CancellationToken cancellationToken); + + Task PublishEvents(IEnumerable domainEvents, CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Eventing/IEventStore.cs b/src/EventSourcingCQRS/Eventing/IEventStore.cs new file mode 100644 index 0000000..04d82c6 --- /dev/null +++ b/src/EventSourcingCQRS/Eventing/IEventStore.cs @@ -0,0 +1,23 @@ +namespace EventSourcingCQRS.Eventing +{ + public interface IEventStore + { + Task> GetDistinctAggregateRootsId(); + Task> GetEvents(Guid aggregateRootId, int startSequence); + + Task> GetEventsUpToSequence(Guid aggregateRootId, int sequence); + + Task Insert(IEnumerable domainEvents); + + Task> GetEventsByEventTypes(IEnumerable domainEventTypes); + + Task> GetEventsByEventTypes(IEnumerable domainEventTypes, Guid aggregateRootId); + Task> GetEventsByEventTypesUpToSequence(IEnumerable domainEventTypes, Guid aggregateRootId, int sequence); + + Task> GetEventsByEventTypes(IEnumerable domainEventTypes, DateTime startDate, + DateTime endDate); + + Task> GetEventsByCriteria(Dictionary criteria); + Task> GetEventsByCriteria(List criteria); + } +} \ No newline at end of file diff --git a/src/SimpleCqrs/Eventing/IHandleDomainEvents.cs b/src/EventSourcingCQRS/Eventing/IHandleDomainEvents.cs similarity index 54% rename from src/SimpleCqrs/Eventing/IHandleDomainEvents.cs rename to src/EventSourcingCQRS/Eventing/IHandleDomainEvents.cs index d976936..bc10dff 100644 --- a/src/SimpleCqrs/Eventing/IHandleDomainEvents.cs +++ b/src/EventSourcingCQRS/Eventing/IHandleDomainEvents.cs @@ -1,7 +1,7 @@ -namespace SimpleCqrs.Eventing +namespace EventSourcingCQRS.Eventing { public interface IHandleDomainEvents where TDomainEvent : DomainEvent { - void Handle(TDomainEvent domainEvent); + Task Handle(TDomainEvent domainEvent); } } \ No newline at end of file diff --git a/src/EventSourcingCQRS/Eventing/ISnapshotStore.cs b/src/EventSourcingCQRS/Eventing/ISnapshotStore.cs new file mode 100644 index 0000000..041ffc6 --- /dev/null +++ b/src/EventSourcingCQRS/Eventing/ISnapshotStore.cs @@ -0,0 +1,11 @@ +using EventSourcingCQRS.Domain; + +namespace EventSourcingCQRS.Eventing +{ + public interface ISnapshotStore + { + Task GetSnapshot(Guid aggregateRootId, CancellationToken cancellationToken); + + Task SaveSnapshot(TSnapshot snapshot, CancellationToken cancellationToken) where TSnapshot : Snapshot; + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Eventing/LocalEventBus.cs b/src/EventSourcingCQRS/Eventing/LocalEventBus.cs new file mode 100644 index 0000000..77a006a --- /dev/null +++ b/src/EventSourcingCQRS/Eventing/LocalEventBus.cs @@ -0,0 +1,90 @@ +namespace EventSourcingCQRS.Eventing +{ + public class LocalEventBus : IEventBus + { + private readonly IDomainEventHandlerFactory _eventHandlerBuilder; + private IDictionary _eventHandlerInvokers; + + public LocalEventBus(IEnumerable eventHandlerTypes, IDomainEventHandlerFactory eventHandlerBuilder) + { + _eventHandlerBuilder = eventHandlerBuilder; + BuildEventInvokers(eventHandlerTypes); + } + + public Task Publish(DomainEvent domainEvent, CancellationToken cancellationToken) + { + var domainEventType = domainEvent.GetType(); + var invokers = (from entry in _eventHandlerInvokers + where entry.Key.IsAssignableFrom(domainEventType) + select entry.Value).ToList(); + + invokers.ForEach(i => i.Publish(domainEvent)); + + return Task.CompletedTask; + } + + public async Task PublishEvents(IEnumerable domainEvents, CancellationToken cancellationToken) + { + foreach (var domainEvent in domainEvents) + { + await Publish(domainEvent, cancellationToken); + } + } + + private void BuildEventInvokers(IEnumerable eventHandlerTypes) + { + _eventHandlerInvokers = new Dictionary(); + foreach (var eventHandlerType in eventHandlerTypes) + { + foreach (var domainEventType in GetDomainEventTypes(eventHandlerType)) + { + if (!_eventHandlerInvokers.TryGetValue(domainEventType, out var eventInvoker)) + { + eventInvoker = new EventHandlerInvoker(_eventHandlerBuilder, domainEventType); + } + + eventInvoker.AddEventHandlerType(eventHandlerType); + _eventHandlerInvokers[domainEventType] = eventInvoker; + } + } + } + + private static IEnumerable GetDomainEventTypes(Type eventHandlerType) + { + + return from interfaceType in eventHandlerType.GetInterfaces() + where interfaceType.IsGenericType && + interfaceType.GetGenericTypeDefinition() == typeof(IHandleDomainEvents<>) + select interfaceType.GetGenericArguments()[0]; + } + + private class EventHandlerInvoker + { + private readonly Type _domainEventType; + private readonly IDomainEventHandlerFactory _eventHandlerFactory; + private readonly List _eventHandlerTypes; + + public EventHandlerInvoker(IDomainEventHandlerFactory eventHandlerFactory, Type domainEventType) + { + _eventHandlerFactory = eventHandlerFactory; + _domainEventType = domainEventType; + _eventHandlerTypes = new List(); + } + + public void AddEventHandlerType(Type eventHandlerType) + { + _eventHandlerTypes.Add(eventHandlerType); + } + + public void Publish(DomainEvent domainEvent) + { + var handleMethod = typeof(IHandleDomainEvents<>).MakeGenericType(_domainEventType).GetMethod("Handle"); + foreach (var eventHandlerType in _eventHandlerTypes) + { + var eventHandler = _eventHandlerFactory.Create(eventHandlerType); + handleMethod.Invoke(eventHandler, new object[] { domainEvent }); + } + } + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Eventing/NullSnapshotStore.cs b/src/EventSourcingCQRS/Eventing/NullSnapshotStore.cs new file mode 100644 index 0000000..d59b45e --- /dev/null +++ b/src/EventSourcingCQRS/Eventing/NullSnapshotStore.cs @@ -0,0 +1,20 @@ +using System.Diagnostics.CodeAnalysis; +using EventSourcingCQRS.Domain; + +namespace EventSourcingCQRS.Eventing +{ + [ExcludeFromCodeCoverage] + public class NullSnapshotStore : ISnapshotStore + { + Task ISnapshotStore.GetSnapshot(Guid aggregateRootId, CancellationToken cancellationToken) + + { + return null; + } + + Task ISnapshotStore.SaveSnapshot(TSnapshot snapshot, CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Querying/IQueryDispatcher.cs b/src/EventSourcingCQRS/Querying/IQueryDispatcher.cs new file mode 100644 index 0000000..c658e8e --- /dev/null +++ b/src/EventSourcingCQRS/Querying/IQueryDispatcher.cs @@ -0,0 +1,7 @@ +namespace EventSourcingCQRS.Querying +{ + public interface IQueryDispatcher + { + Task Dispatch(TQuery query, CancellationToken cancellation); + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Querying/IQueryHandler.cs b/src/EventSourcingCQRS/Querying/IQueryHandler.cs new file mode 100644 index 0000000..f7e52d8 --- /dev/null +++ b/src/EventSourcingCQRS/Querying/IQueryHandler.cs @@ -0,0 +1,7 @@ +namespace EventSourcingCQRS.Querying +{ + public interface IQueryHandler + { + Task Handle(TQuery query, CancellationToken cancellation); + } +} \ No newline at end of file diff --git a/src/EventSourcingCQRS/Querying/QueryDispatcher.cs b/src/EventSourcingCQRS/Querying/QueryDispatcher.cs new file mode 100644 index 0000000..305e2a6 --- /dev/null +++ b/src/EventSourcingCQRS/Querying/QueryDispatcher.cs @@ -0,0 +1,17 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace EventSourcingCQRS.Querying +{ + public class QueryDispatcher : IQueryDispatcher + { + private readonly IServiceProvider _serviceProvider; + + public QueryDispatcher(IServiceProvider serviceProvider) => this._serviceProvider = serviceProvider; + + public Task Dispatch(TQuery query, CancellationToken cancellation) + { + var handler = _serviceProvider.GetRequiredService>(); + return handler.Handle(query, cancellation); + } + } +} \ No newline at end of file diff --git a/src/EventStores/SimpleCqrs.EventStore.File/FileEventStore.cs b/src/EventStores/SimpleCqrs.EventStore.File/FileEventStore.cs deleted file mode 100644 index 1b00fef..0000000 --- a/src/EventStores/SimpleCqrs.EventStore.File/FileEventStore.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.Serialization; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.EventStore.File -{ - public class FileEventStore : IEventStore - { - private readonly string baseDirectory; - private readonly DataContractSerializer serializer; - - public FileEventStore(string baseDirectory, ITypeCatalog typeCatalog) - { - this.baseDirectory = baseDirectory; - if (!Directory.Exists(baseDirectory)) - Directory.CreateDirectory(baseDirectory); - - var domainEventDerivedTypes = typeCatalog.GetDerivedTypes(typeof(DomainEvent)); - serializer = new DataContractSerializer(typeof(DomainEvent), domainEventDerivedTypes); - } - - public IEnumerable GetEvents(Guid aggregateRootId, int startSequence) - { - var eventInfos = GetEventInfosForAggregateRoot(aggregateRootId, startSequence); - var domainEvents = new List(); - foreach (var eventInfo in eventInfos) - { - using (var stream = System.IO.File.OpenRead(eventInfo.FilePath)) - { - var domainEvent = (DomainEvent)serializer.ReadObject(stream); - domainEvents.Add(domainEvent); - } - } - - return domainEvents; - } - - public void Insert(IEnumerable domainEvents) - { - foreach (var domainEvent in domainEvents) - { - var aggregateRootDirectory = Path.Combine(baseDirectory, domainEvent.AggregateRootId.ToString()); - if (!Directory.Exists(aggregateRootDirectory)) - Directory.CreateDirectory(aggregateRootDirectory); - - var eventPath = Path.Combine(aggregateRootDirectory, string.Format("{0}.xml", domainEvent.Sequence)); - using(var stream = new FileStream(eventPath, FileMode.Create)) - { - serializer.WriteObject(stream, domainEvent); - } - } - } - - public IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes) - { - throw new NotImplementedException(); - } - - public IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes, Guid aggregateRootId) - { - throw new NotImplementedException(); - } - - public IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes, DateTime startDate, DateTime endDate) - { - throw new NotImplementedException(); - } - - private IEnumerable GetEventInfosForAggregateRoot(Guid aggregateRootId, int startSequence) - { - var aggregateRootDirectory = Path.Combine(baseDirectory, aggregateRootId.ToString()); - return from filePath in Directory.GetFiles(aggregateRootDirectory) - let fileName = Path.GetFileNameWithoutExtension(filePath) - where fileName != null - let sequence = int.Parse(fileName) - where sequence > startSequence - select new { Sequence = sequence, FilePath = filePath }; - } - } -} \ No newline at end of file diff --git a/src/EventStores/SimpleCqrs.EventStore.File/FileSnapshotStore.cs b/src/EventStores/SimpleCqrs.EventStore.File/FileSnapshotStore.cs deleted file mode 100644 index f34906a..0000000 --- a/src/EventStores/SimpleCqrs.EventStore.File/FileSnapshotStore.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using SimpleCqrs.Domain; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.EventStore.File -{ - public class FileSnapshotStore : ISnapshotStore - { - public Snapshot GetSnapshot(Guid aggregateRootId) - { - throw new NotImplementedException(); - } - - public void SaveSnapshot(TSnapshot snapshot) where TSnapshot : Snapshot - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/src/EventStores/SimpleCqrs.EventStore.File/Properties/AssemblyInfo.cs b/src/EventStores/SimpleCqrs.EventStore.File/Properties/AssemblyInfo.cs deleted file mode 100644 index 411c6f8..0000000 --- a/src/EventStores/SimpleCqrs.EventStore.File/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("SimpleCqrs.EventStore.File")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SimpleCqrs.EventStore.File")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] -[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("b1207f2f-9b75-4614-8b60-76a42bfe4c14")] - -// 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/src/EventStores/SimpleCqrs.EventStore.File/SimpleCqrs.EventStore.File.csproj b/src/EventStores/SimpleCqrs.EventStore.File/SimpleCqrs.EventStore.File.csproj deleted file mode 100644 index 34207c5..0000000 --- a/src/EventStores/SimpleCqrs.EventStore.File/SimpleCqrs.EventStore.File.csproj +++ /dev/null @@ -1,60 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {65B52205-E45D-4D6B-8F48-AFBC4406BEE8} - Library - Properties - SimpleCqrs.EventStore.File - SimpleCqrs.EventStore.File - v4.0 - 512 - - - true - full - false - ..\..\..\binaries\eventstores\file\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - {E04C12B5-A6D3-4D64-9F38-896BEE68162E} - SimpleCqrs - False - - - - - \ No newline at end of file diff --git a/src/EventStores/SimpleCqrs.EventStore.MongoDb/MongoEventStore.cs b/src/EventStores/SimpleCqrs.EventStore.MongoDb/MongoEventStore.cs deleted file mode 100644 index 9d18d8e..0000000 --- a/src/EventStores/SimpleCqrs.EventStore.MongoDb/MongoEventStore.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using MongoDB; -using MongoDB.Configuration; -using MongoDB.Configuration.Builders; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.EventStore.MongoDb -{ - public class MongoEventStore : IEventStore - { - private static readonly MethodInfo MapMethod = typeof(MappingStoreBuilder).GetMethod("Map", Type.EmptyTypes); - private readonly MongoConfiguration configuration; - private readonly string databaseName; - - public MongoEventStore(string connectionString, ITypeCatalog typeCatalog) - { - var connectionStringBuilder = new MongoConnectionStringBuilder(connectionString); - databaseName = connectionStringBuilder.Database; - configuration = BuildMongoConfiguration(typeCatalog, connectionString); - } - - private static MongoConfiguration BuildMongoConfiguration(ITypeCatalog domainEventTypeCatalog, string connectionString) - { - var configurationBuilder = new MongoConfigurationBuilder(); - configurationBuilder.ConnectionString(connectionString); - configurationBuilder.Mapping(mapping => - { - mapping.DefaultProfile(profile => profile.SubClassesAre(t => t.IsSubclassOf(typeof(DomainEvent)))); - domainEventTypeCatalog - .GetDerivedTypes(typeof(DomainEvent)) - .ToList() - .ForEach(type => MapEventType(type, mapping)); - }); - - return configurationBuilder.BuildConfiguration(); - } - - public IEnumerable GetEvents(Guid aggregateRootId, int startSequence) - { - using(var mongo = new Mongo(configuration)) - { - mongo.Connect(); - - var database = mongo.GetDatabase(databaseName); - var eventsCollection = database.GetCollection("events").Linq(); - - return (from domainEvent in eventsCollection - where domainEvent.AggregateRootId == aggregateRootId - where domainEvent.Sequence > startSequence - select domainEvent).ToList(); - } - } - - public void Insert(IEnumerable domainEvents) - { - using(var mongo = new Mongo(configuration)) - { - mongo.Connect(); - - var database = mongo.GetDatabase(databaseName); - var eventsCollection = database.GetCollection("events"); - eventsCollection.Insert(domainEvents); - } - } - - public IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes) - { - using(var mongo = new Mongo(configuration)) - { - mongo.Connect(); - - var database = mongo.GetDatabase(databaseName); - var selector = new Document {{"_t", new Document {{"$in", domainEventTypes.Select(t => t.Name).ToArray()}}}}; - - var cursor = database.GetCollection("events").Find(selector); - - return cursor.Documents.ToList(); - } - } - - public IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes, Guid aggregateRootId) - { - using (var mongo = new Mongo(configuration)) - { - mongo.Connect(); - - var database = mongo.GetDatabase(databaseName); - var selector = new Document - { - {"_t", new Document {{"$in", domainEventTypes.Select(t => t.Name).ToArray()}}}, - {"AggregateRootId", aggregateRootId} - }; - - var cursor = database.GetCollection("events").Find(selector); - - return cursor.Documents.ToList(); - } - } - - public IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes, DateTime startDate, DateTime endDate) - { - using(var mongo = new Mongo(configuration)) - { - mongo.Connect(); - - var database = mongo.GetDatabase(databaseName); - var selector = new Document - { - {"_t", new Document {{"$in", domainEventTypes.Select(t => t.Name).ToArray()}}}, - {"EventDate", new Document {{"$gte", startDate}, {"$lte", endDate}}} - }; - - var cursor = database.GetCollection("events").Find(selector); - - return cursor.Documents.ToList(); - } - } - - public IEnumerable GetEventsBySelector(Document selector) - { - using(var mongo = new Mongo(configuration)) - { - mongo.Connect(); - - var database = mongo.GetDatabase(databaseName); - var cursor = database.GetCollection("events").Find(selector); - return cursor.Documents.ToList(); - } - } - - public IEnumerable GetEventsBySelector(Document selector, int skip, int limit) - { - using(var mongo = new Mongo(configuration)) - { - mongo.Connect(); - - var database = mongo.GetDatabase(databaseName); - var cursor = database.GetCollection("events").Find(selector); - return cursor.Skip(skip).Limit(limit).Documents.ToList(); - } - } - - private static void MapEventType(Type type, MappingStoreBuilder mapping) - { - MapMethod.MakeGenericMethod(type) - .Invoke(mapping, new object[] {}); - } - } -} \ No newline at end of file diff --git a/src/EventStores/SimpleCqrs.EventStore.MongoDb/MongoSnapshotStore.cs b/src/EventStores/SimpleCqrs.EventStore.MongoDb/MongoSnapshotStore.cs deleted file mode 100644 index 1bd44ca..0000000 --- a/src/EventStores/SimpleCqrs.EventStore.MongoDb/MongoSnapshotStore.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Linq; -using System.Reflection; -using MongoDB; -using MongoDB.Configuration; -using MongoDB.Configuration.Builders; -using SimpleCqrs.Domain; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.EventStore.MongoDb -{ - public class MongoSnapshotStore : ISnapshotStore - { - private static readonly MethodInfo MapMethod = typeof(MappingStoreBuilder).GetMethod("Map", Type.EmptyTypes); - private readonly IMongoDatabase database; - - public MongoSnapshotStore(string connectionString, ITypeCatalog snapshotTypeCatalog) - { - var configuration = BuildMongoConfiguration(snapshotTypeCatalog, connectionString); - var mongo = new Mongo(configuration); - mongo.Connect(); - - database = mongo.GetDatabase("snapshotstore"); - } - - public Snapshot GetSnapshot(Guid aggregateRootId) - { - var snapshotsCollection = database.GetCollection("snapshots").Linq(); - return (from snapshot in snapshotsCollection - where snapshot.AggregateRootId == aggregateRootId - select snapshot).SingleOrDefault(); - } - - public void SaveSnapshot(TSnapshot snapshot) where TSnapshot : Snapshot - { - var snapshotsCollection = database.GetCollection("snapshots"); - snapshotsCollection.Update(snapshot, new { snapshot.AggregateRootId }, UpdateFlags.Upsert); - } - - private static MongoConfiguration BuildMongoConfiguration(ITypeCatalog snapshotTypeCatalog, string connectionString) - { - var configurationBuilder = new MongoConfigurationBuilder(); - configurationBuilder.ConnectionString(connectionString); - configurationBuilder.Mapping(mapping => - { - mapping.DefaultProfile(profile => profile.SubClassesAre(type => type.IsSubclassOf(typeof(Snapshot)))); - snapshotTypeCatalog - .GetDerivedTypes(typeof(Snapshot)) - .ToList() - .ForEach(type => MapEventType(type, mapping)); - }); - - return configurationBuilder.BuildConfiguration(); - } - - private static void MapEventType(Type type, MappingStoreBuilder mapping) - { - MapMethod.MakeGenericMethod(type) - .Invoke(mapping, new object[] {}); - } - } -} \ No newline at end of file diff --git a/src/EventStores/SimpleCqrs.EventStore.MongoDb/Properties/AssemblyInfo.cs b/src/EventStores/SimpleCqrs.EventStore.MongoDb/Properties/AssemblyInfo.cs deleted file mode 100644 index 6d6213c..0000000 --- a/src/EventStores/SimpleCqrs.EventStore.MongoDb/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("SimpleCqrs.EventStore.MongoDb")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SimpleCqrs.EventStore.MongoDb")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] -[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("aa0268b0-e3a1-46a0-b8ba-6de440edd9b1")] - -// 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/src/EventStores/SimpleCqrs.EventStore.MongoDb/SimpleCqrs.EventStore.MongoDb.csproj b/src/EventStores/SimpleCqrs.EventStore.MongoDb/SimpleCqrs.EventStore.MongoDb.csproj deleted file mode 100644 index 71a5c25..0000000 --- a/src/EventStores/SimpleCqrs.EventStore.MongoDb/SimpleCqrs.EventStore.MongoDb.csproj +++ /dev/null @@ -1,68 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {201A4DF5-2217-4202-80E8-E784737366BC} - Library - Properties - SimpleCqrs.EventStore.MongoDb - SimpleCqrs.EventStore.MongoDb - v4.0 - 512 - - - - true - full - false - ..\..\..\binaries\eventstores\mongodb\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - False - ..\..\..\lib\MongoDB.dll - - - False - ..\..\..\lib\MongoDB.GridFS.dll - - - - - - - - - - - - - - {E04C12B5-A6D3-4D64-9F38-896BEE68162E} - SimpleCqrs - False - - - - - \ No newline at end of file diff --git a/src/EventStores/SimpleCqrs.EventStore.SqlServer/Serializers/JsonDomainEventSerializer.cs b/src/EventStores/SimpleCqrs.EventStore.SqlServer/Serializers/JsonDomainEventSerializer.cs deleted file mode 100644 index 11f7a2c..0000000 --- a/src/EventStores/SimpleCqrs.EventStore.SqlServer/Serializers/JsonDomainEventSerializer.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.IO; -using System.Runtime.Serialization.Formatters.Binary; -using System.Text; -using ServiceStack.Text; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.EventStore.SqlServer.Serializers -{ - public class JsonDomainEventSerializer : IDomainEventSerializer - { - - public string Serialize(DomainEvent domainEvent) - { - return JsonSerializer.SerializeToString(domainEvent, domainEvent.GetType()); - } - - public DomainEvent Deserialize(Type targetType, string serializedDomainEvent) - { - return (DomainEvent)JsonSerializer.DeserializeFromString(serializedDomainEvent, targetType); - } - } - - public class BinaryDomainEventSerializer : IDomainEventSerializer - { - public string Serialize(DomainEvent domainEvent) { - var formatter = new BinaryFormatter(); - using (var stream = new MemoryStream()) { - formatter.Serialize(stream, domainEvent); - stream.Flush(); - stream.Position = 0; - return Convert.ToBase64String(stream.ToArray()); - } - } - - public DomainEvent Deserialize(Type targetType, string serializedDomainEvent) { - var formatter = new BinaryFormatter(); - using (var stream = new MemoryStream(Convert.FromBase64String(serializedDomainEvent))) { - return (DomainEvent)formatter.Deserialize(stream); - } - } - } - -} \ No newline at end of file diff --git a/src/EventStores/SimpleCqrs.EventStore.SqlServer/SimpleCqrs.EventStore.SqlServer.csproj b/src/EventStores/SimpleCqrs.EventStore.SqlServer/SimpleCqrs.EventStore.SqlServer.csproj deleted file mode 100644 index ae10b8f..0000000 --- a/src/EventStores/SimpleCqrs.EventStore.SqlServer/SimpleCqrs.EventStore.SqlServer.csproj +++ /dev/null @@ -1,70 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {BEEBFC8E-91EC-4E24-8223-395C2302C1B3} - Library - Properties - SimpleCqrs.EventStore.SqlServer - SimpleCqrs.EventStore.SqlServer - v4.0 - 512 - - - true - full - false - ..\..\..\binaries\eventstores\sqlserver\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - False - ..\..\..\lib\ServiceStack.Text.dll - - - - - - - - - - - - - - - - - - - - - {E04C12B5-A6D3-4D64-9F38-896BEE68162E} - SimpleCqrs - - - - - - \ No newline at end of file diff --git a/src/EventStores/SimpleCqrs.EventStore.SqlServer/SqlServerConfiguration.cs b/src/EventStores/SimpleCqrs.EventStore.SqlServer/SqlServerConfiguration.cs deleted file mode 100644 index 9c83891..0000000 --- a/src/EventStores/SimpleCqrs.EventStore.SqlServer/SqlServerConfiguration.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace SimpleCqrs.EventStore.SqlServer -{ - public class SqlServerConfiguration - { - private readonly string connectionString; - - public SqlServerConfiguration(string connectionString) - { - this.connectionString = connectionString; - } - - public string ConnectionString - { - get { return connectionString; } - } - } -} \ No newline at end of file diff --git a/src/EventStores/SimpleCqrs.EventStore.SqlServer/SqlServerEventStore.cs b/src/EventStores/SimpleCqrs.EventStore.SqlServer/SqlServerEventStore.cs deleted file mode 100644 index 4955553..0000000 --- a/src/EventStores/SimpleCqrs.EventStore.SqlServer/SqlServerEventStore.cs +++ /dev/null @@ -1,117 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data.SqlClient; -using System.Linq; -using System.Text; -using ServiceStack.Text; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.EventStore.SqlServer -{ - public class SqlServerEventStore : IEventStore - { - private readonly IDomainEventSerializer serializer; - private readonly SqlServerConfiguration configuration; - - public SqlServerEventStore(SqlServerConfiguration configuration, IDomainEventSerializer serializer) - { - this.serializer = serializer; - this.configuration = configuration; - Init(); - } - - public void Init() - { - using (var connection = new SqlConnection(configuration.ConnectionString)) - { - connection.Open(); - var sql = string.Format(SqlStatements.CreateTheEventStoreTable, "EventStore"); - using (var command = new SqlCommand(sql, connection)) - command.ExecuteNonQuery(); - connection.Close(); - } - } - - public IEnumerable GetEvents(Guid aggregateRootId, int startSequence) - { - var events = new List(); - using (var connection = new SqlConnection(configuration.ConnectionString)) - { - connection.Open(); - var sql = string.Format(SqlStatements.GetEventsByAggregateRootAndSequence, "", "EventStore", aggregateRootId, - startSequence); - using (var command = new SqlCommand(sql, connection)) - using (var reader = command.ExecuteReader()) - while (reader.Read()) - { - var type = reader["EventType"].ToString(); - var data = reader["data"].ToString(); - - try - { - events.Add(serializer.Deserialize(Type.GetType(type), data)); - } catch(ArgumentNullException ex) - { - throw new Exception(string.Format("Cannot find type '{0}', yet the type is in the event store. Are you sure you haven't changed a class name or something arising from mental dullness?", type.Split(',')[0]), ex.InnerException); - } - } - connection.Close(); - } - return events; - } - - public void Insert(IEnumerable domainEvents) - { - var sql = new StringBuilder(); - foreach (var domainEvent in domainEvents) - sql.AppendFormat(SqlStatements.InsertEvents, "EventStore", TypeToStringHelperMethods.GetString(domainEvent.GetType()), domainEvent.AggregateRootId, domainEvent.EventDate, domainEvent.Sequence, - (serializer.Serialize(domainEvent) ?? string.Empty) - .Replace("'", "''")); - - if (sql.Length <= 0) return; - - using (var connection = new SqlConnection(configuration.ConnectionString)) - { - connection.Open(); - using (var command = new SqlCommand(sql.ToString(), connection)) - command.ExecuteNonQuery(); - connection.Close(); - } - } - - public IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes) - { - var events = new List(); - - var eventParameters = domainEventTypes.Select(TypeToStringHelperMethods.GetString).Join("','"); - - using (var connection = new SqlConnection(configuration.ConnectionString)) - { - connection.Open(); - var sql = string.Format(SqlStatements.GetEventsByType, "EventStore", eventParameters); - using (var command = new SqlCommand(sql, connection)) - using (var reader = command.ExecuteReader()) - while (reader.Read()) - { - var type = reader["EventType"].ToString(); - var data = reader["data"].ToString(); - - var domainEvent = serializer.Deserialize(Type.GetType(type), data); - events.Add(domainEvent); - } - connection.Close(); - } - return events; - } - - public IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes, Guid aggregateRootId) - { - throw new NotImplementedException(); - } - - public IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes, DateTime startDate, DateTime endDate) - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandBusExtensionMethods.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandBusExtensionMethods.cs deleted file mode 100644 index 721c39e..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandBusExtensionMethods.cs +++ /dev/null @@ -1,27 +0,0 @@ -using NServiceBus; -using SimpleCqrs.Commanding; - -namespace SimpleCqrs.NServiceBus.Commanding -{ - public static class CommandBusExtensionMethods - { - public static ICallback ExecuteWithCallback(this ICommandBus commandBus, TCommand command) where TCommand : ICommand - { - var bus = (NsbCommandBus)commandBus; - var destination = bus.GetDestinationForCommandType(); - return bus.InnerBus.Send(destination, message => message.Command = command); - } - - public static int ExecuteWeb(this ICommandBus commandBus, TCommand command) where TCommand : ICommand - { - var bus = (NsbCommandBus)commandBus; - var destination = bus.GetDestinationForCommandType(); - var returnValue = 0; - - bus.InnerBus.Send(destination, message => message.Command = command) - .RegisterWebCallback(errorCode => returnValue = errorCode, null); - - return returnValue; - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandMessage.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandMessage.cs deleted file mode 100644 index ed0cb77..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandMessage.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using NServiceBus; -using SimpleCqrs.Commanding; - -namespace SimpleCqrs.NServiceBus.Commanding -{ - [Serializable] - public class CommandMessage : IMessage - { - public ICommand Command { get; set; } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandMessageHandler.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandMessageHandler.cs deleted file mode 100644 index 0519190..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandMessageHandler.cs +++ /dev/null @@ -1,21 +0,0 @@ -using NServiceBus; -using SimpleCqrs.Commanding; -using SimpleCqrs.NServiceBus.Commanding; - -namespace SimpleCqrs.NServiceBus -{ - public class CommandMessageHandler : IHandleMessages - { - private readonly ICommandBus commandBus; - - public CommandMessageHandler(ICommandBus commandBus) - { - this.commandBus = commandBus; - } - - public void Handle(CommandMessage message) - { - commandBus.Send(message.Command); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandWithReturnValueMessage.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandWithReturnValueMessage.cs deleted file mode 100644 index 82e71f1..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandWithReturnValueMessage.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using NServiceBus; -using SimpleCqrs.Commanding; - -namespace SimpleCqrs.NServiceBus.Commanding -{ - [Serializable] - public class CommandWithReturnValueMessage : IMessage - { - public ICommand Command { get; set; } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandWithReturnValueMessageHandler.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandWithReturnValueMessageHandler.cs deleted file mode 100644 index 1a3a281..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/CommandWithReturnValueMessageHandler.cs +++ /dev/null @@ -1,23 +0,0 @@ -using NServiceBus; -using SimpleCqrs.Commanding; - -namespace SimpleCqrs.NServiceBus.Commanding -{ - public class CommandWithReturnValueMessageHandler : IHandleMessages - { - private readonly ICommandBus commandBus; - private readonly IBus bus; - - public CommandWithReturnValueMessageHandler(ICommandBus commandBus, IBus bus) - { - this.commandBus = commandBus; - this.bus = bus; - } - - public void Handle(CommandWithReturnValueMessage message) - { - var value = commandBus.Execute(message.Command); - bus.Return(value); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/Config/CommandBusConfig.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/Config/CommandBusConfig.cs deleted file mode 100644 index 89c616b..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/Config/CommandBusConfig.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Configuration; - -namespace SimpleCqrs.NServiceBus.Commanding.Config -{ - public class CommandBusConfig : ConfigurationSection - { - private const string CommandEndpointMappingsElementName = "CommandEndpointMappings"; - - [ConfigurationProperty(CommandEndpointMappingsElementName, IsRequired = false)] - public CommandEndpointMappingCollection CommandEndpointMappings - { - get { return (base[CommandEndpointMappingsElementName] as CommandEndpointMappingCollection); } - set { base[CommandEndpointMappingsElementName] = value; } - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/Config/CommandEndpointMapping.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/Config/CommandEndpointMapping.cs deleted file mode 100644 index 741502e..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/Config/CommandEndpointMapping.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Configuration; - -namespace SimpleCqrs.NServiceBus.Commanding.Config -{ - public class CommandEndpointMapping : ConfigurationElement - { - private const string CommandsPropertyName = "Commands"; - private const string EndpointPropertyName = "Endpoint"; - - [ConfigurationProperty(EndpointPropertyName, IsRequired = true, IsKey = true)] - public string Endpoint - { - get { return (string)base[EndpointPropertyName]; } - set { base[EndpointPropertyName] = value; } - } - - [ConfigurationProperty(CommandsPropertyName, IsRequired = false)] - public string Commands - { - get { return (string)base[CommandsPropertyName]; } - set { base[CommandsPropertyName] = value; } - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/Config/CommandEndpointMappingCollection.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/Config/CommandEndpointMappingCollection.cs deleted file mode 100644 index 2da3c3d..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/Config/CommandEndpointMappingCollection.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System.Configuration; - -namespace SimpleCqrs.NServiceBus.Commanding.Config -{ - public class CommandEndpointMappingCollection : ConfigurationElementCollection - { - public void Add(CommandEndpointMapping mapping) - { - BaseAdd(mapping); - } - - protected override void BaseAdd(ConfigurationElement element) - { - BaseAdd(element, true); - } - - public void Clear() - { - BaseClear(); - } - - protected override ConfigurationElement CreateNewElement() - { - return new CommandEndpointMapping(); - } - - protected override ConfigurationElement CreateNewElement(string elementName) - { - return new CommandEndpointMapping {Commands = elementName}; - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((CommandEndpointMapping)element).Commands; - } - - public int IndexOf(CommandEndpointMapping mapping) - { - return BaseIndexOf(mapping); - } - - public void Remove(CommandEndpointMapping mapping) - { - if(BaseIndexOf(mapping) >= 0) - { - BaseRemove(mapping.Commands); - } - } - - public void Remove(string name) - { - BaseRemove(name); - } - - public void RemoveAt(int index) - { - BaseRemoveAt(index); - } - - public override ConfigurationElementCollectionType CollectionType - { - get { return ConfigurationElementCollectionType.AddRemoveClearMap; } - } - - public CommandEndpointMapping this[int index] - { - get { return (CommandEndpointMapping)BaseGet(index); } - set - { - if(BaseGet(index) != null) - { - BaseRemoveAt(index); - } - BaseAdd(index, value); - } - } - - public new CommandEndpointMapping this[string name] - { - get { return (CommandEndpointMapping)BaseGet(name); } - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/ConfigCommandBus.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/ConfigCommandBus.cs deleted file mode 100644 index c88f42b..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/ConfigCommandBus.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using NServiceBus; -using SimpleCqrs.Commanding; -using SimpleCqrs.NServiceBus.Commanding.Config; - -namespace SimpleCqrs.NServiceBus.Commanding -{ - public class ConfigCommandBus : ConfigSimpleCqrs - { - private readonly ISimpleCqrsRuntime runtime; - private readonly IDictionary commandTypeToDestinationLookup = new Dictionary(); - - public ConfigCommandBus(ISimpleCqrsRuntime runtime) : base(runtime) - { - this.runtime = runtime; - } - - public IDictionary CommandTypeToDestinationLookup - { - get { return commandTypeToDestinationLookup; } - } - - public TimeSpan ExecuteCommandTimeout { get; set; } - - public new NsbCommandBus Configure(Configure config) - { - Configurer = config.Configurer; - Builder = config.Builder; - - ExecuteCommandTimeout = TimeSpan.FromSeconds(10); - var commandBusConfig = GetConfigSection(); - var commandTypes = TypesToScan - .Where(type => typeof(ICommand).IsAssignableFrom(type)) - .ToList(); - - RegisterAssemblyCommandDestinationMappings(commandBusConfig, commandTypes); - RegisterCommandDestinationMappings(commandBusConfig, commandTypes); - - return new NsbCommandBus(runtime.ServiceLocator, CommandTypeToDestinationLookup, ExecuteCommandTimeout); - } - - private void RegisterCommandDestinationMappings(CommandBusConfig commandBusConfig, IEnumerable commandTypes) - { - foreach (var mapping in GetCommandEndpointMappingsForCommand(commandBusConfig.CommandEndpointMappings, commandTypes)) - { - foreach (var commandType in commandTypes) - { - if (CommandTypeIsCommand(commandType, mapping.Commands)) - { - if (commandTypeToDestinationLookup.ContainsKey(commandType)) - commandTypeToDestinationLookup[commandType] = mapping.Endpoint; - else - commandTypeToDestinationLookup.Add(commandType, mapping.Endpoint); - } - } - } - } - - private void RegisterAssemblyCommandDestinationMappings(CommandBusConfig commandBusConfig, IEnumerable commandTypes) - { - foreach(var mapping in GetCommandEndpointMappingsForAssembly(commandBusConfig.CommandEndpointMappings, commandTypes)) - { - foreach(var commandType in commandTypes) - { - if(CommandTypeIsInCommandAssembly(commandType, mapping.Commands)) - { - commandTypeToDestinationLookup.Add(commandType, mapping.Endpoint); - } - } - } - } - - private static IEnumerable GetCommandEndpointMappingsForAssembly(CommandEndpointMappingCollection commandEndpointMappings, IEnumerable commandTypes) - { - return commandEndpointMappings - .Cast() - .Where(mapping => commandTypes.Any(t => t.Assembly.GetName().Name.Equals(mapping.Commands,StringComparison.InvariantCultureIgnoreCase))); - } - - private static IEnumerable GetCommandEndpointMappingsForCommand(CommandEndpointMappingCollection commandEndpointMappings, IEnumerable commandTypes) - { - return commandEndpointMappings - .Cast() - .Where(mapping => commandTypes.Any(t => t.FullName.Equals(mapping.Commands, StringComparison.InvariantCultureIgnoreCase) || t.Name.Equals(mapping.Commands, StringComparison.InvariantCultureIgnoreCase))); - } - - private static bool CommandTypeIsInCommandAssembly(Type commandType, string commandAssembly) - { - return commandType.Assembly.GetName().Name.ToLower() == commandAssembly.ToLower(); - } - - private static bool CommandTypeIsCommand(Type commandType, string command) - { - return commandType.FullName.ToLower() == command.ToLower() - || commandType.AssemblyQualifiedName.ToLower() == command.ToLower(); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/NsbCommandBus.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/NsbCommandBus.cs deleted file mode 100644 index df3d50b..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Commanding/NsbCommandBus.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Collections.Generic; -using NServiceBus; -using SimpleCqrs.Commanding; - -namespace SimpleCqrs.NServiceBus.Commanding -{ - public class NsbCommandBus : ICommandBus - { - private readonly IServiceLocator serviceLocator; - private readonly IDictionary commandTypeToDestinationLookup; - private readonly TimeSpan executeTimeout; - - public NsbCommandBus(IServiceLocator serviceLocator, IDictionary commandTypeToDestinationLookup, TimeSpan executeTimeout) - { - this.serviceLocator = serviceLocator; - this.commandTypeToDestinationLookup = commandTypeToDestinationLookup; - this.executeTimeout = executeTimeout; - } - - public IBus InnerBus - { - get { return serviceLocator.Resolve(); } - } - - public string GetDestinationForCommandType() - { - return commandTypeToDestinationLookup[typeof(TCommand)]; - } - - public int Execute(TCommand command) where TCommand : ICommand - { - var bus = serviceLocator.Resolve(); - var destination = GetDestinationForCommandType(); - var asyncResult = bus - .Send(destination, message => message.Command = command) - .Register(state => { }, null); - - if(!asyncResult.AsyncWaitHandle.WaitOne(executeTimeout)) - throw new ExecuteTimeoutException(); - - return ((CompletionResult)asyncResult.AsyncState).ErrorCode; - } - - public void Send(TCommand command) where TCommand : ICommand - { - var bus = serviceLocator.Resolve(); - var destination = commandTypeToDestinationLookup[typeof(TCommand)]; - bus.Send(destination, message => message.Command = command); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/ConfigSimpleCqrs.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/ConfigSimpleCqrs.cs deleted file mode 100644 index dd56a68..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/ConfigSimpleCqrs.cs +++ /dev/null @@ -1,77 +0,0 @@ -using NServiceBus; -using SimpleCqrs.Commanding; -using SimpleCqrs.Eventing; -using SimpleCqrs.NServiceBus.Commanding; -using SimpleCqrs.NServiceBus.Eventing; - -namespace SimpleCqrs.NServiceBus -{ - public class ConfigSimpleCqrs : Configure - { - private readonly ISimpleCqrsRuntime runtime; - - public ConfigSimpleCqrs(ISimpleCqrsRuntime runtime) - { - this.runtime = runtime; - } - - public IServiceLocator ServiceLocator { get; private set; } - - public void Configure(Configure config) - { - Configurer = config.Configurer; - Builder = config.Builder; - - runtime.Start(); - - ServiceLocator = runtime.ServiceLocator; - ServiceLocator.Register(() => Builder.Build()); - Configurer.RegisterSingleton(runtime); - } - - public ConfigSimpleCqrs UseLocalCommandBus() - { - var commandBus = ServiceLocator.Resolve(); - ServiceLocator.Register(commandBus); - Configurer.RegisterSingleton(commandBus); - - return this; - } - - public ConfigSimpleCqrs SubscribeForDomainEvents() - { - var typeCatalog = ServiceLocator.Resolve(); - var domainEventHandlerFactory = ServiceLocator.Resolve(); - var domainEventTypes = typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleDomainEvents<>)); - - var eventBus = new NsbLocalEventBus(domainEventTypes, domainEventHandlerFactory); - Configurer.RegisterSingleton(eventBus); - - var configEventBus = new ConfigEventBus(); - configEventBus.Configure(this, runtime); - - return this; - } - - public ConfigSimpleCqrs UseNsbCommandBus() - { - var config = new ConfigCommandBus(runtime); - var commandBus = config.Configure(this); - - ServiceLocator.Register(commandBus); - Configurer.RegisterSingleton(commandBus); - - return this; - } - - public ConfigSimpleCqrs UseNsbEventBus() - { - var eventBus = new NsbEventBus(); - - ServiceLocator.Register(eventBus); - Configurer.RegisterSingleton(eventBus); - - return this; - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/ConfigureSimpleCqrs.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/ConfigureSimpleCqrs.cs deleted file mode 100644 index b26ead4..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/ConfigureSimpleCqrs.cs +++ /dev/null @@ -1,14 +0,0 @@ -using NServiceBus; - -namespace SimpleCqrs.NServiceBus -{ - public static class ConfigureSimpleCqrs - { - public static ConfigSimpleCqrs SimpleCqrs(this Configure configure, ISimpleCqrsRuntime runtime) - { - var configSimpleCqrs = new ConfigSimpleCqrs(runtime); - configSimpleCqrs.Configure(configure); - return configSimpleCqrs; - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/Config/DomainEventBusConfig.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/Config/DomainEventBusConfig.cs deleted file mode 100644 index 65fd011..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/Config/DomainEventBusConfig.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Configuration; - -namespace SimpleCqrs.NServiceBus.Eventing.Config -{ - public class DomainEventBusConfig : ConfigurationSection - { - private const string DomainEventEndpointMappingsElementName = "DomainEventEndpointMappings"; - - [ConfigurationProperty(DomainEventEndpointMappingsElementName, IsRequired = false)] - public DomainEventEndpointMappingCollection DomainEventEndpointMappings - { - get { return (base[DomainEventEndpointMappingsElementName] as DomainEventEndpointMappingCollection); } - set { base[DomainEventEndpointMappingsElementName] = value; } - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/Config/DomainEventEndpointMapping.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/Config/DomainEventEndpointMapping.cs deleted file mode 100644 index 6307a55..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/Config/DomainEventEndpointMapping.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Configuration; - -namespace SimpleCqrs.NServiceBus.Eventing.Config -{ - public class DomainEventEndpointMapping : ConfigurationElement - { - private const string DomainEventsPropertyName = "DomainEvents"; - private const string EndpointPropertyName = "Endpoint"; - - [ConfigurationProperty(EndpointPropertyName, IsRequired = true, IsKey = true)] - public string Endpoint - { - get { return (string)base[EndpointPropertyName]; } - set { base[EndpointPropertyName] = value; } - } - - [ConfigurationProperty(DomainEventsPropertyName, IsRequired = true, IsKey = true)] - public string DomainEvents - { - get { return (string)base[DomainEventsPropertyName]; } - set { base[DomainEventsPropertyName] = value; } - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/Config/DomainEventEndpointMappingCollection.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/Config/DomainEventEndpointMappingCollection.cs deleted file mode 100644 index c444fd6..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/Config/DomainEventEndpointMappingCollection.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System.Configuration; - -namespace SimpleCqrs.NServiceBus.Eventing.Config -{ - public class DomainEventEndpointMappingCollection : ConfigurationElementCollection - { - public void Add(DomainEventEndpointMapping mapping) - { - BaseAdd(mapping); - } - - protected override void BaseAdd(ConfigurationElement element) - { - BaseAdd(element, true); - } - - public void Clear() - { - BaseClear(); - } - - protected override ConfigurationElement CreateNewElement() - { - return new DomainEventEndpointMapping(); - } - - protected override ConfigurationElement CreateNewElement(string elementName) - { - return new DomainEventEndpointMapping {DomainEvents = elementName}; - } - - protected override object GetElementKey(ConfigurationElement element) - { - var domainEventEndpointMapping = ((DomainEventEndpointMapping)element); - return domainEventEndpointMapping.DomainEvents; - } - - public int IndexOf(DomainEventEndpointMapping mapping) - { - return BaseIndexOf(mapping); - } - - public void Remove(DomainEventEndpointMapping mapping) - { - if(BaseIndexOf(mapping) >= 0) - { - BaseRemove(mapping.DomainEvents); - } - } - - public void Remove(string name) - { - BaseRemove(name); - } - - public void RemoveAt(int index) - { - BaseRemoveAt(index); - } - - public override ConfigurationElementCollectionType CollectionType - { - get { return ConfigurationElementCollectionType.AddRemoveClearMap; } - } - - public DomainEventEndpointMapping this[int index] - { - get { return (DomainEventEndpointMapping)BaseGet(index); } - set - { - if(BaseGet(index) != null) - { - BaseRemoveAt(index); - } - BaseAdd(index, value); - } - } - - public new DomainEventEndpointMapping this[string name] - { - get { return (DomainEventEndpointMapping)BaseGet(name); } - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/ConfigEventBus.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/ConfigEventBus.cs deleted file mode 100644 index 593886c..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/ConfigEventBus.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.Collections.Generic; -using NServiceBus; -using NServiceBus.Unicast; -using SimpleCqrs.Eventing; -using SimpleCqrs.NServiceBus.Eventing.Config; - -namespace SimpleCqrs.NServiceBus.Eventing -{ - public class ConfigEventBus : Configure - { - public void Configure(ConfigSimpleCqrs config, ISimpleCqrsRuntime runtime) - { - Configurer = config.Configurer; - Builder = config.Builder; - - var serviceLocator = runtime.ServiceLocator; - var typeCatalog = serviceLocator.Resolve(); - - var domainEventBusConfig = GetConfigSection(); - var domainEventTypes = typeCatalog.GetDerivedTypes(typeof(DomainEvent)); - var domainEventMessageTypes = new List(); - var bus = (UnicastBus)config - .MsmqTransport() - .UnicastBus() - .LoadMessageHandlers(new First()) - .CreateBus(); - - RegisterAssemblyDomainEventSubscriptionMappings(domainEventBusConfig, domainEventTypes, domainEventMessageTypes, bus); - RegisterDomainEventSubscriptionMappings(domainEventBusConfig, domainEventTypes, domainEventMessageTypes, bus); - - bus.Started += (s, e) => domainEventMessageTypes.ForEach(bus.Subscribe); - } - - private static void RegisterDomainEventSubscriptionMappings(DomainEventBusConfig domainEventBusConfig, IEnumerable domainEventTypes, ICollection domainEventMessageTypes, UnicastBus bus) - { - var domainEventMessageType = typeof(DomainEventMessage<>); - foreach (DomainEventEndpointMapping mapping in domainEventBusConfig.DomainEventEndpointMappings) - { - foreach (var domainEventType in domainEventTypes) - { - if (DomainEventsIsDomainEvent(domainEventType, mapping.DomainEvents)) - { - var messageType = domainEventMessageType.MakeGenericType(domainEventType); - domainEventMessageTypes.Add(messageType); - bus.RegisterMessageType(messageType, mapping.Endpoint, false); - } - } - } - } - - private static void RegisterAssemblyDomainEventSubscriptionMappings(DomainEventBusConfig domainEventBusConfig, IEnumerable domainEventTypes, ICollection domainEventMessageTypes, UnicastBus bus) - { - var domainEventMessageType = typeof(DomainEventMessage<>); - foreach(DomainEventEndpointMapping mapping in domainEventBusConfig.DomainEventEndpointMappings) - { - foreach(var domainEventType in domainEventTypes) - { - if (DomainEventsIsAssembly(domainEventType, mapping.DomainEvents)) - { - var messageType = domainEventMessageType.MakeGenericType(domainEventType); - domainEventMessageTypes.Add(messageType); - bus.RegisterMessageType(messageType, mapping.Endpoint, false); - } - } - } - } - - private static bool DomainEventsIsDomainEvent(Type domainEventType, string domainEvents) - { - return domainEventType.FullName.ToLower() == domainEvents.ToLower() - || domainEventType.AssemblyQualifiedName.ToLower() == domainEvents.ToLower(); - } - - private static bool DomainEventsIsAssembly(Type domainEventType, string domainEvents) - { - return domainEventType.Assembly.GetName().Name.ToLower() == domainEvents.ToLower(); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/DomainEventMessage.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/DomainEventMessage.cs deleted file mode 100644 index e0535d0..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/DomainEventMessage.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.NServiceBus.Eventing -{ - [Serializable] - public class DomainEventMessage : IDomainEventMessage - where TDomainEvent : DomainEvent - { - public TDomainEvent DomainEvent { get; set; } - - public string Header { get; set; } - - DomainEvent IDomainEventMessage.DomainEvent - { - get { return DomainEvent; } - set { DomainEvent = (TDomainEvent)value; } - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/DomainEventMessageHandler.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/DomainEventMessageHandler.cs deleted file mode 100644 index 29f4552..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/DomainEventMessageHandler.cs +++ /dev/null @@ -1,21 +0,0 @@ -using NServiceBus; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.NServiceBus.Eventing -{ - public class DomainEventMessageHandler : IHandleMessages - { - private readonly IEventBus eventBus; - - public DomainEventMessageHandler(IEventBus eventBus) - { - this.eventBus = eventBus; - } - - public void Handle(IDomainEventMessage message) - { - var domainEvent = message.DomainEvent; - eventBus.PublishEvent(domainEvent); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/IDomainEventMessage.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/IDomainEventMessage.cs deleted file mode 100644 index bd8b46c..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/IDomainEventMessage.cs +++ /dev/null @@ -1,11 +0,0 @@ -using NServiceBus; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.NServiceBus.Eventing -{ - public interface IDomainEventMessage : IMessage - { - DomainEvent DomainEvent { get; set; } - string Header { get; set; } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/NsbEventBus.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/NsbEventBus.cs deleted file mode 100644 index e6f0465..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/NsbEventBus.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using NServiceBus; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.NServiceBus.Eventing -{ - internal class NsbEventBus : IEventBus - { - private IBus bus; - - public void PublishEvent(DomainEvent domainEvent) - { - Bus.Publish(message => message.DomainEvent = domainEvent); - } - - public void PublishEvents(IEnumerable domainEvents) - { - var domainEventMessages = domainEvents.Select(CreateDomainEventMessage).ToList(); - domainEventMessages.ForEach(message => Bus.Publish(message)); - } - - private IBus Bus - { - get { return bus ?? (bus = Configure.Instance.Builder.Build()); } - } - - private static IDomainEventMessage CreateDomainEventMessage(DomainEvent domainEvent) - { - var domainEventMessageType = typeof(DomainEventMessage<>).MakeGenericType(domainEvent.GetType()); - var message = (IDomainEventMessage)Activator.CreateInstance(domainEventMessageType); - message.DomainEvent = domainEvent; - return message; - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/NsbLocalEventBus.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/NsbLocalEventBus.cs deleted file mode 100644 index 069e7bd..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/Eventing/NsbLocalEventBus.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using log4net; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.NServiceBus.Eventing -{ - internal class NsbLocalEventBus : IEventBus - { - private readonly IDomainEventHandlerFactory eventHandlerBuilder; - private IDictionary eventHandlerInvokers; - - public NsbLocalEventBus(IEnumerable eventHandlerTypes, IDomainEventHandlerFactory eventHandlerBuilder) - { - this.eventHandlerBuilder = eventHandlerBuilder; - BuildEventInvokers(eventHandlerTypes); - } - - public void PublishEvent(DomainEvent domainEvent) - { - if(!eventHandlerInvokers.ContainsKey(domainEvent.GetType())) return; - - var eventHandlerInvoker = eventHandlerInvokers[domainEvent.GetType()]; - eventHandlerInvoker.Publish(domainEvent); - } - - public void PublishEvents(IEnumerable domainEvents) - { - foreach(var domainEvent in domainEvents) - PublishEvent(domainEvent); - } - - private void BuildEventInvokers(IEnumerable eventHandlerTypes) - { - eventHandlerInvokers = new Dictionary(); - foreach(var eventHandlerType in eventHandlerTypes) - { - foreach(var domainEventType in GetDomainEventTypes(eventHandlerType)) - { - EventHandlerInvoker eventInvoker; - if(!eventHandlerInvokers.TryGetValue(domainEventType, out eventInvoker)) - eventInvoker = new EventHandlerInvoker(eventHandlerBuilder, domainEventType); - - eventInvoker.AddEventHandlerType(eventHandlerType); - eventHandlerInvokers[domainEventType] = eventInvoker; - } - } - } - - private static IEnumerable GetDomainEventTypes(Type eventHandlerType) - { - return from interfaceType in eventHandlerType.GetInterfaces() - where interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IHandleDomainEvents<>) - select interfaceType.GetGenericArguments()[0]; - } - - private class EventHandlerInvoker - { - private readonly IDomainEventHandlerFactory eventHandlerFactory; - private readonly Type domainEventType; - private readonly List eventHandlerTypes; - private readonly ILog logger = LogManager.GetLogger(typeof(NsbLocalEventBus)); - - public EventHandlerInvoker(IDomainEventHandlerFactory eventHandlerFactory, Type domainEventType) - { - this.eventHandlerFactory = eventHandlerFactory; - this.domainEventType = domainEventType; - eventHandlerTypes = new List(); - } - - public void AddEventHandlerType(Type eventHandlerType) - { - eventHandlerTypes.Add(eventHandlerType); - } - - public void Publish(DomainEvent domainEvent) - { - var exceptionList = new List(); - - var handleMethod = typeof(IHandleDomainEvents<>).MakeGenericType(domainEventType).GetMethod("Handle"); - foreach(var eventHandlerType in eventHandlerTypes) - { - try - { - var eventHandler = eventHandlerFactory.Create(eventHandlerType); - handleMethod.Invoke(eventHandler, new object[] {domainEvent}); - } - catch(Exception exception) - { - logger.Error(string.Format("An exception occured while handling event of type '{0}'\nMessage: {1}", domainEvent.GetType(), exception.Message), exception); - exceptionList.Add(exception); - } - } - - if(exceptionList.Count > 0) - throw new AggregateException(exceptionList); - } - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.NServiceBus.Core/Properties/AssemblyInfo.cs b/src/Extensions/SimpleCqrs.NServiceBus.Core/Properties/AssemblyInfo.cs deleted file mode 100644 index 659c076..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/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("SimpleCqrs.NServiceBus")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SimpleCqrs.NServiceBus")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] -[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("3da51379-ebe4-4e6a-bcb6-7cabf432d76d")] - -// 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/src/Extensions/SimpleCqrs.NServiceBus.Core/SimpleCqrs.NServiceBus.csproj b/src/Extensions/SimpleCqrs.NServiceBus.Core/SimpleCqrs.NServiceBus.csproj deleted file mode 100644 index 1ae2a56..0000000 --- a/src/Extensions/SimpleCqrs.NServiceBus.Core/SimpleCqrs.NServiceBus.csproj +++ /dev/null @@ -1,88 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {07C2BF77-9646-4C39-BDB2-852B76AA6C75} - Library - Properties - SimpleCqrs.NServiceBus - SimpleCqrs.NServiceBus - v4.0 - 512 - - - true - full - false - ..\..\..\binaries\extension\nservicebus\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\lib\log4net.dll - - - ..\..\..\lib\NServiceBus.dll - - - ..\..\..\lib\NServiceBus.Core.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {E04C12B5-A6D3-4D64-9F38-896BEE68162E} - SimpleCqrs - - - - - \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/DomainEventConsumer.cs b/src/Extensions/SimpleCqrs.Rhino.ServiceBus/DomainEventConsumer.cs deleted file mode 100644 index 657e991..0000000 --- a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/DomainEventConsumer.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Rhino.ServiceBus; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.Rhino.ServiceBus -{ - public class DomainEventConsumer : ConsumerOf - { - private readonly IEventBus eventBus; - - public DomainEventConsumer(IEventBus eventBus) - { - this.eventBus = eventBus; - } - - public void Consume(DomainEvent domainEvent) - { - eventBus.PublishEvent(domainEvent); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/Properties/AssemblyInfo.cs b/src/Extensions/SimpleCqrs.Rhino.ServiceBus/Properties/AssemblyInfo.cs deleted file mode 100644 index 4cdcd95..0000000 --- a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/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("SimpleCqrs.Rhino.ServiceBus")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SimpleCqrs.Rhino.ServiceBus")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[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("b87d4af7-1f84-4d57-9402-2a4c333ca6fd")] - -// 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/src/Extensions/SimpleCqrs.Rhino.ServiceBus/Reply.cs b/src/Extensions/SimpleCqrs.Rhino.ServiceBus/Reply.cs deleted file mode 100644 index f3e61bb..0000000 --- a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/Reply.cs +++ /dev/null @@ -1,14 +0,0 @@ -using SimpleCqrs.Commanding; - -namespace SimpleCqrs.Rhino.ServiceBus -{ - public class Reply : IReply where TCommand : ICommand - { - public int ValidationResult { get; set; } - } - - public interface IReply - { - int ValidationResult { get; set; } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/ReplyConsumer.cs b/src/Extensions/SimpleCqrs.Rhino.ServiceBus/ReplyConsumer.cs deleted file mode 100644 index a99fcfe..0000000 --- a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/ReplyConsumer.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Threading; -using Rhino.ServiceBus; -using SimpleCqrs.Commanding; - -namespace SimpleCqrs.Rhino.ServiceBus -{ - public class ReplyConsumer : OccasionalConsumerOf> where TCommand : ICommand - { - public ReplyConsumer() - { - Event = new ManualResetEvent(false); - } - - public ManualResetEvent Event { get; set; } - public int ValidationResult { get; set; } - - public void Consume(Reply replay) - { - ValidationResult = replay.ValidationResult; - Event.Set(); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/Request.cs b/src/Extensions/SimpleCqrs.Rhino.ServiceBus/Request.cs deleted file mode 100644 index a84e856..0000000 --- a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/Request.cs +++ /dev/null @@ -1,20 +0,0 @@ -using SimpleCqrs.Commanding; - -namespace SimpleCqrs.Rhino.ServiceBus -{ - public class Request : IRequest where TCommand : ICommand - { - public TCommand Command { get; set; } - - ICommand IRequest.Command - { - get { return Command; } - set { Command = (TCommand)value; } - } - } - - public interface IRequest - { - ICommand Command { get; set; } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/RequestReplyMessageOwnersSelector.cs b/src/Extensions/SimpleCqrs.Rhino.ServiceBus/RequestReplyMessageOwnersSelector.cs deleted file mode 100644 index 75a7f5f..0000000 --- a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/RequestReplyMessageOwnersSelector.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Rhino.ServiceBus; -using Rhino.ServiceBus.Exceptions; -using Rhino.ServiceBus.Impl; -using Rhino.ServiceBus.Internal; - -namespace SimpleCqrs.Rhino.ServiceBus -{ - public class RequestReplyMessageOwnersSelector : MessageOwnersSelector, IMessageOwnersSelector - { - private readonly MessageOwner[] messageOwners; - private readonly IEndpointRouter endpointRouter; - - public RequestReplyMessageOwnersSelector(MessageOwner[] messageOwners, IEndpointRouter endpointRouter) - : base(messageOwners, endpointRouter) - { - this.messageOwners = messageOwners; - this.endpointRouter = endpointRouter; - } - - Endpoint IMessageOwnersSelector.GetEndpointForMessageBatch(object[] messages) - { - if(messages == null) - throw new ArgumentNullException("messages"); - - if(messages.Length == 0) - throw new MessagePublicationException("Cannot send empty message batch"); - - var messageType = messages[0].GetType(); - if(messageType.IsGenericType && (messageType.GetGenericTypeDefinition() == typeof(Reply<>) || messageType.GetGenericTypeDefinition() == typeof(Request<>))) - { - var messageOwner = messageOwners - .Where(x => x.IsOwner(messageType.GetGenericArguments()[0])) - .FirstOrDefault(); - - var endpoint = endpointRouter.GetRoutedEndpoint(messageOwner.Endpoint); - endpoint.Transactional = messageOwner.Transactional; - return endpoint; - } - - return GetEndpointForMessageBatch(messages); - } - - IEnumerable IMessageOwnersSelector.Of(Type type) - { - if(type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Request<>) || type.GetGenericTypeDefinition() == typeof(Reply<>))) - return Of(type.GetGenericArguments()[0]); - - return Of(type); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/RsbCommandBus.cs b/src/Extensions/SimpleCqrs.Rhino.ServiceBus/RsbCommandBus.cs deleted file mode 100644 index 1ea61ae..0000000 --- a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/RsbCommandBus.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Rhino.ServiceBus; -using SimpleCqrs.Commanding; - -namespace SimpleCqrs.Rhino.ServiceBus -{ - public class RsbCommandBus : ICommandBus - { - private readonly IServiceBus serviceBus; - - public RsbCommandBus(IServiceBus serviceBus) - { - this.serviceBus = serviceBus; - } - - public int Execute(TCommand command) where TCommand : ICommand - { - var replyConsumer = new ReplyConsumer(); - using(serviceBus.AddInstanceSubscription(replyConsumer)) - { - serviceBus.Send(new Request{Command = command }); - if (!replyConsumer.Event.WaitOne(50000)) - throw new ExecuteTimeoutException(); - - return replyConsumer.ValidationResult; - } - } - - public void Send(TCommand command) where TCommand : ICommand - { - serviceBus.Send(command); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/RsbCommandConsumer.cs b/src/Extensions/SimpleCqrs.Rhino.ServiceBus/RsbCommandConsumer.cs deleted file mode 100644 index ae1a925..0000000 --- a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/RsbCommandConsumer.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using Rhino.ServiceBus; -using SimpleCqrs.Commanding; - -namespace SimpleCqrs.Rhino.ServiceBus -{ - public class RsbCommandConsumer : ConsumerOf, ConsumerOf - { - private readonly ICommandBus commandBus; - private readonly IServiceBus serviceBus; - - public RsbCommandConsumer(ICommandBus commandBus, IServiceBus serviceBus) - { - this.commandBus = commandBus; - this.serviceBus = serviceBus; - } - - public void Consume(ICommand command) - { - commandBus.Send(command); - } - - public void Consume(IRequest request) - { - var validationResult = commandBus.Execute(request.Command); - var reply = (IReply)Activator.CreateInstance(typeof(Reply<>).MakeGenericType(request.Command.GetType())); - reply.ValidationResult = validationResult; - serviceBus.Reply(reply); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/RsbEventBus.cs b/src/Extensions/SimpleCqrs.Rhino.ServiceBus/RsbEventBus.cs deleted file mode 100644 index b044dec..0000000 --- a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/RsbEventBus.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Rhino.ServiceBus; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.Rhino.ServiceBus -{ - public class RsbEventBus : IEventBus - { - private readonly IServiceBus serviceBus; - - public RsbEventBus(IServiceBus serviceBus) - { - this.serviceBus = serviceBus; - } - - public void PublishEvent(DomainEvent domainEvent) - { - serviceBus.Notify(domainEvent); - } - - public void PublishEvents(IEnumerable domainEvents) - { - serviceBus.Notify(domainEvents.ToArray()); - } - } -} \ No newline at end of file diff --git a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/SimpleCqrs.Rhino.ServiceBus.csproj b/src/Extensions/SimpleCqrs.Rhino.ServiceBus/SimpleCqrs.Rhino.ServiceBus.csproj deleted file mode 100644 index b406d02..0000000 --- a/src/Extensions/SimpleCqrs.Rhino.ServiceBus/SimpleCqrs.Rhino.ServiceBus.csproj +++ /dev/null @@ -1,67 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {EE1B7085-F7BC-48BD-B058-C33DF4CD0F74} - Library - Properties - SimpleCqrs.Rhino.ServiceBus - SimpleCqrs.Rhino.ServiceBus - v4.0 - 512 - - - true - full - false - ..\..\..\binaries\extension\rhino.servicebus\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - False - ..\..\..\lib\Rhino.ServiceBus.dll - - - - - - - - - - - - - - - - - - - {E04C12B5-A6D3-4D64-9F38-896BEE68162E} - SimpleCqrs - - - - - \ No newline at end of file diff --git a/src/Packages/repositories.config b/src/Packages/repositories.config deleted file mode 100644 index e39cf99..0000000 --- a/src/Packages/repositories.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/src/Packages/structuremap.2.6.3/lib/StructureMap.XML b/src/Packages/structuremap.2.6.3/lib/StructureMap.XML deleted file mode 100644 index cd80940..0000000 --- a/src/Packages/structuremap.2.6.3/lib/StructureMap.XML +++ /dev/null @@ -1,3880 +0,0 @@ - - - - StructureMap - - - - - The "BuildUp" method takes in an already constructed object - and uses Setter Injection to push in configured dependencies - of that object - - - - - - Get the object of type T that is valid for this build session. - - - - - - - Get the object of type T that is valid for this build session by name. - - - - - - - Register a default object for the given PluginType that will - be used throughout the rest of the current object request - - - - - - - Same as GetInstance, but can gracefully return null if - the Type does not already exist - - - - - - - Same as GetInstance(name), but can gracefully return null if - the Type and name does not already exist - - - - - - - - Gets all objects in the current object graph that can be cast - to T that have already been created - - - - - - - Creates/Resolves every configured instance of PlutinType T - - - - - - - Gets a reference to the BuildStack for this build session - - - - - The concrete type of the immediate parent object in the object graph - - - - - Gets the root "frame" of the object request - - - - - The requested instance name of the object graph - - - - - Expression Builder that has grammars for defining policies at the - PluginType level. This expression is used for registering - open generic types - - - - - Convenience method that sets the default concrete type of the PluginType. The "concreteType" - can only accept types that do not have any primitive constructor arguments. - StructureMap has to know how to construct all of the constructor argument types. - - - - - - - Use this configured Instance as is - - - - - - Shorter way to call TheDefaultIsConcreteType - - - - - - - Shortcut to add a value by type - - - - - - - Shortcut method to add an additional Instance to this Plugin Type - as just a Concrete Type. This will only work if the Concrete Type - has no primitive constructor or mandatory Setter arguments. - - - - - - - Shortcut method to add an additional Instance to this Plugin Type - as just a Concrete Type. This will only work if the Concrete Type - has no primitive constructor or mandatory Setter arguments. - - - - - - - Configure this type as the supplied value - - - - - - Sets the object creation of the instances of the PluginType. For example: PerRequest, - Singleton, ThreadLocal, HttpContext, or Hybrid - - - - - - - Register an Action to run against any object of this PluginType immediately after - it is created, but before the new object is passed back to the caller - - - - - - - Register a Func to run against any object of this PluginType immediately after it is created, - but before the new object is passed back to the caller. Unlike OnCreation(), - EnrichWith() gives the the ability to return a different object. Use this method for runtime AOP - scenarios or to return a decorator. - - - - - - - Register a Func to run against any object of this PluginType immediately after it is created, - but before the new object is passed back to the caller. Unlike OnCreation(), - EnrichWith() gives the the ability to return a different object. Use this method for runtime AOP - scenarios or to return a decorator. - - - - - - - Registers an IBuildInterceptor for this Plugin Type that executes before - any object of this PluginType is created. IBuildInterceptor's can be - used to create a custom scope - - - - - - - Convenience method to mark a PluginFamily as a Singleton - - - - - - Convenience method to mark a PluginFamily as a Hybrid lifecycle - - - - - - Convenience method to mark a PluginFamily as HttpContext scoped - - - - - - - - - - - - - Shortcut method to add an additional Instance to this Plugin Type - as just a Concrete Type. You can also chain other declarations after - this method to add constructor and setter arguments - - - - - - - Shortcut method to add an additional Instance to this Plugin Type - as just a Concrete Type by a specified name. You can also chain other declarations after - this method to add constructor and setter arguments - - - - - - - - Specify the value of this explicit argument - - - - - - - Pass in additional arguments by type T - - - - - - - - Pass in additional arguments by type - - - - - - - - Pass in additional arguments by name - - - - - - - Gets the default instance of type T using the explicitly configured arguments from the "args" - - - - - - - Gets a named instance of type T using the explicitly configured arguments from teh "args" - - - - - - - - Gets the default instance of the pluginType using the explicitly configured arguments from the "args" - - - - - - Gets all configured instances of type T using explicitly configured arguments - - - - - - - Returns the System.Reflection.ConstructorInfo for the PluggedType. Uses either - the "greediest" constructor with the most arguments or the constructor function - marked with the [DefaultConstructor] - - - - - - The InstanceKey of the default instance of the PluginFamily - - - - - The CLR Type that defines the "Plugin" interface for the PluginFamily - - - - - Add an Assembly to the scanning operation - - - - - - Add an Assembly by name to the scanning operation - - - - - - Add the currently executing Assembly to the scanning operation - - - - - Add the Assembly that contains type T to the scanning operation - - - - - - Add the Assembly that contains type to the scanning operation - - - - - - Sweep the designated path and add any Assembly's found in this folder to the - scanning operation - - - - - - Sweep the designated path and add any Assembly's found in this folder to the - scanning operation. The assemblyFilter can be used to filter or limit the - Assembly's that are picked up. - - - - - - - Sweep the application base directory of current app domain and add any Assembly's - found to the scanning operation. - - - - - Sweep the application base directory of current app domain and add any Assembly's - found to the scanning operation. The assemblyFilter can be used to filter or limit the - Assembly's that are picked up. - - - - - Adds an ITypeScanner object to the scanning operation - - - - - - Creates and adds a new ITypeScanner of type T to this scanning operation - - - - - - Directs the scanning operation to automatically detect and include any Registry - classes found in the Assembly's being scanned - - - - - Add all concrete types of the Plugin Type as Instances of Plugin Type - - - - - - Add all concrete types of the Plugin Type as Instances of Plugin Type - - - - - - Makes this scanning operation ignore all [PluginFamily] and [Pluggable] attributes - - - - - Exclude types that match the Predicate from being scanned - - - - - - Exclude all types in this nameSpace or its children from the scanning operation - - - - - - Exclude all types in this nameSpace or its children from the scanning operation - - - - - - Only include types matching the Predicate in the scanning operation. You can - use multiple Include() calls in a single scanning operation - - - - - - Only include types from this nameSpace or its children in the scanning operation. You can - use multiple Include() calls in a single scanning operation - - - - - - Only include types from this nameSpace or its children in the scanning operation. You can - use multiple Include() calls in a single scanning operation - - - - - - Exclude this specific type from the scanning operation - - - - - - Adds a registration convention to be applied to all the types in this - logical "scan" operation - - - - - - Adds a registration convention to be applied to all the types in this - logical "scan" operation - - - - - Adds the DefaultConventionScanner to the scanning operations. I.e., a concrete - class named "Something" that implements "ISomething" will be automatically - added to PluginType "ISomething" - - - - - Scans for PluginType's and Concrete Types that close the given open generic type - - - - - - - - - Automatically registers all concrete types without primitive arguments - against its first interface, if any - - - - - Directs the scanning to automatically register any type that is the single - implementation of an interface against that interface. - The filters apply - - - - - Adds the DefaultConventionScanner to the scanning operations. I.e., a concrete - class named "Something" that implements "ISomething" will be automatically - added to PluginType "ISomething" - - - - - Scans for PluginType's and Concrete Types that close the given open generic type - - - - - - - - - Automatically registers all concrete types without primitive arguments - against its first interface, if any - - - - - Directs the scanning to automatically register any type that is the single - implementation of an interface against that interface. - The filters apply - - - - - A TypeInterceptor that is only applied if the MatchesType() - method is true for a given Type - - - - - An InstanceInterceptor can be registered on a per-Instance basis - to act on, or even replace, the object that is created before - it is passed back to the caller. This is primarily a hook - for runtime AOP scenarios. - - - - - Does this TypeInterceptor apply to the given type? - - - - - - - Specify how objects matching the Type predicate - will be intercepted - - - - - - Specify how objects matching the Type predicate - will be intercepted - - - - - - An Instance class that builds objects by calling a constructor function on a concrete type - and filling setter properties. ConfiguredInstance should only be used for open generic types. - Favor SmartInstance{T} for all other usages. - - - - - Register an Action to perform on the object created by this Instance - before it is returned to the caller - - - - - - - - Register an Action to perform on the object created by this Instance - before it is returned to the caller - - - - - - - - Register a Func to potentially enrich or substitute for the object - created by this Instance before it is returned to the caller - - - - - - - Register a Func to potentially enrich or substitute for the object - created by this Instance before it is returned to the caller - - - - - - - Inline definition of a dependency array like IService[] or IHandler[] - - - - - - - - Inline definition of a dependency array like IService[] or IHandler[] - - - - - - - Inline definition of a dependency array like IService[] or IHandler[] - - - - - - - Start the definition of a child instance for type CONSTRUCTORARGUMENTTYPE - - - - - - - Start the definition of a child instance for type CONSTRUCTORARGUMENTTYPE - - - - - - - Inline definition of a constructor or a setter property dependency - - - - - - - Starts the definition of a child instance specifying the argument name - in the case of a constructor function that consumes more than one argument - of type T - - - - - - - - Inline definition of a constructor dependency - - - - - - - - Inline definition of a setter dependency - - - - - - - - Start the definition of a primitive argument to a constructor argument - - - - - - - Configure a primitive constructor argument - - - - - - - Configures an array of Instance's for the array dependency - - - - - - - Part of the Fluent Interface, represents a nonprimitive argument to a - constructure function - - - - - Use a previously configured and named instance for the child - - - - - - - Start the definition of a child instance by defining the concrete type - - - - - - - Start the definition of a child instance by defining the concrete type - - - - - - - Registers a configured instance to use as the argument to the parent's - constructor - - - - - - - Directs StructureMap to fill this dependency with the Default Instance of the - constructor or property type - - - - - - Base class for many of the Instance subclasses to support - method chaining in the Registry DSL for common options - - - - - - Set the name of this Instance - - - - - - - Register an Action to perform on the object created by this Instance - before it is returned to the caller - - - - - - - - Register a Func to potentially enrich or substitute for the object - created by this Instance before it is returned to the caller - - - - - - - - Register a Func to potentially enrich or substitute for the object - created by this Instance before it is returned to the caller - - - - - - - - Register an InstanceInterceptor with this Instance - - - - - - - Used to override the constructor of a class to be used by StructureMap to create - a Pluggable object - - - - - Examines a System.Type object and determines the ConstructorInfo to use in creating - instances of the Type - - - - - - - Used to implicitly mark a class as a Plugin candidate for StructureMap - - - - - Determines whether a Type object is marked as Pluggable - - - - - - - The ConcreteKey alias of the Type - - - - - Declares a class, abstract class, or interface to be the target of a PluginFamily in the container - - - - - Determines if a Type object is marked as a PluginFamily - - - - - - - If set, determines the shared "scope" of the instance -- PerRequest, Singleton, ThreadLocal, - HttpContext, etc. - - - - - InstanceKey of the default instance. Used to implicitly define the default without - declaring the instance in StructureMap.config - - - - - Declares the target to be built by StructureMap as a Singleton. One object instance will - be created for each named instance - - - - - Marks a Property in a Pluggable class as filled by setter injection - - - - - Marks a method with no parameters as a method that validates an instance. StructureMap - uses this method to validate the configuration file. If the method does not throw an - exception, the object is assumed to be valid. - - - - - Returns an array of any MethodInfo's on a Type that are marked as ValidationMethod - - CLR Type to search for validation methods - - - - - Constants for the names of Xml nodes and attributes in the StructureMap.config - file - - - - - The name of the default configuration file. The value is always StructurMap.config - - - - - Returns the absolute path to the StructureMap.config file - - - - - - Expression Builder that has grammars for defining policies at the - PluginType level - - - - - Add multiple Instance's to this PluginType - - - - - - - Conditional binding of instances - - - - - - - Access to all of the uncommon Instance types - - - - - - - Access to all of the uncommon Instance types - - - - - - - Convenience method that sets the default concrete type of the PluginType. Type T - can only accept types that do not have any primitive constructor arguments. - StructureMap has to know how to construct all of the constructor argument types. - - - - - - - - Shorthand to say TheDefault.Is.ConstructedBy(func) - - - - - - - Shorthand to say TheDefault.Is.ConstructedBy(func) - - - - - - - Shorthand to say TheDefault.IsThis(@object) - - - - - - - Sets the object creation of the instances of the PluginType. For example: PerRequest, - Singleton, ThreadLocal, HttpContext, or Hybrid - - - - - - - Convenience method to mark a PluginFamily as a Singleton - - - - - - Convenience method to mark a PluginFamily as a Transient - - - - - - Convenience method to mark a PluginFamily as a Hybrid lifecycle - - - - - - Convenience method to mark a PluginFamily as HttpContext scoped - - - - - - Register an Action to run against any object of this PluginType immediately after - it is created, but before the new object is passed back to the caller - - - - - - - Register an Action to run against any object of this PluginType immediately after - it is created, but before the new object is passed back to the caller - - - - - - - Adds an Interceptor to only this PluginType - - - - - - - Register an Action to run against any object of this PluginType immediately after - it is created, but before the new object is passed back to the caller - - - - - - - Register an Action to run against any object of this PluginType immediately after - it is created, but before the new object is passed back to the caller - - - - - - - Register a Func to run against any object of this PluginType immediately after it is created, - but before the new object is passed back to the caller. Unlike OnCreation(), - EnrichWith() gives the the ability to return a different object. Use this method for runtime AOP - scenarios or to return a decorator. - - - - - - - Register a Func to run against any object of this PluginType immediately after it is created, - but before the new object is passed back to the caller. Unlike OnCreation(), - EnrichWith() gives the the ability to return a different object. Use this method for runtime AOP - scenarios or to return a decorator. - - - - - - - Register a Func to run against any object of this PluginType immediately after it is created, - but before the new object is passed back to the caller. Unlike OnCreation(), - EnrichWith() gives the the ability to return a different object. Use this method for runtime AOP - scenarios or to return a decorator. - - - - - - - Register a Func to run against any object of this PluginType immediately after it is created, - but before the new object is passed back to the caller. Unlike OnCreation(), - EnrichWith() gives the the ability to return a different object. Use this method for runtime AOP - scenarios or to return a decorator. - - - - - - - Shortcut method to add an additional Instance to this Plugin Type - as just a Concrete Type. This will only work if the Concrete Type - has no primitive constructor or mandatory Setter arguments. - - - - - - - Registers an ILifecycle for this Plugin Type that executes before - any object of this PluginType is created. ILifecycle's can be - used to create a custom scope - - - - - - - Largely deprecated and unnecessary with the ability to add Xml configuration files - - - - - - - Forces StructureMap to always use a unique instance to - stop the "BuildSession" caching - - - - - - Adds the object to to the PLUGINTYPE - - - - - - - Add an Instance to this type created by a Lambda - - - - - - - Define the Default Instance for this PluginType - - - - - Expression class to help define a runtime Profile - - - - - Starts the definition of the default instance for the containing Profile. This is - still valid, but Type() is recommended - - - - - - - Designate or define the Instance for a type within - this Profile - - - - - - - Use statement to define the Profile defaults for a Generic type - - - - - - - Expression Builder inside of a Profile creation for - open generic types - - - - - Use this concreteType for the Instance of this Profile for the PluginType - - - - - - - Use this concreteType for the Instance of this Profile for the PluginType - - - - - - - Use this Instance for the Profile Instance of this Plugin Type - - - - - - - Use the named Instance as the Profile Instance for this PluginType - - - - - - - Use the named Instance as the Profile Instance for this PluginType - - - - - - - For this type and profile, build the object with this Lambda - - - - - - - Expression Builder within defining a Profile - - - - - - Use a named, preconfigured instance as the default instance for this profile - - - - - - - Use a named, preconfigured instance as the default instance for this profile - - - - - - - Define the default instance of the PluginType for the containing Profile - - - - - - - For this Profile, use an Instance with this Func - - - - - - - For this Profile, use an Instance with this Func - - - - - - - For this Profile, use this object - - - - - - - Access to the uncommon types of Instance - - - - - - For this Profile, use the Concrete Type - - - - - - - For this profile, use this concrete type - - - - - - - A Registry class provides methods and grammars for configuring a Container or ObjectFactory. - Using a Registry subclass is the recommended way of configuring a StructureMap Container. - - - public class MyRegistry : Registry - { - public MyRegistry() - { - ForRequestedType(typeof(IService)).TheDefaultIsConcreteType(typeof(Service)); - } - } - - - - - Adds the concreteType as an Instance of the pluginType - - - - - - - Adds the concreteType as an Instance of the pluginType with a name - - - - - - - - Add the pluggedType as an instance to any configured pluginType where pluggedType - could be assigned to the pluginType - - - - - - Imports the configuration from another registry into this registry. - - - - - - Imports the configuration from another registry into this registry. - - - - - - Expression Builder used to define policies for a PluginType including - Scoping, the Default Instance, and interception. BuildInstancesOf() - and ForRequestedType() are synonyms - - - - - - - Expression Builder used to define policies for a PluginType including - Scoping, the Default Instance, and interception. This method is specifically - meant for registering open generic types - - - - - - This method is a shortcut for specifying the default constructor and - setter arguments for a ConcreteType. ForConcreteType is shorthand for: - ForRequestedType[T]().Use[T].************** - when the PluginType and ConcreteType are the same Type - - - - - - - Expression Builder used to define policies for a PluginType including - Scoping, the Default Instance, and interception. BuildInstancesOf() - and ForRequestedType() are synonyms - - - - - - - Convenience method. Equivalent of ForRequestedType[PluginType]().AsSingletons() - - - - - - - Uses the configuration expressions of this Registry to create a PluginGraph - object that could be used to initialize a Container. This method is - mostly for internal usage, but might be helpful for diagnostics - - - - - - Adds an additional, non-Default Instance to the PluginType T. - - - - - - - Adds an additional, non-Default Instance to the designated pluginType - This method is mostly meant for open generic types - - - - - - - Expression Builder to define the defaults for a named Profile. Each call - to CreateProfile is additive. - - - - - - - An alternative way to use CreateProfile that uses ProfileExpression - as a Nested Closure. This usage will result in cleaner code for - multiple declarations - - - - - - - Registers a new TypeInterceptor object with the Container - - - - - - Allows you to define a TypeInterceptor inline with Lambdas or anonymous delegates - - - - - IfTypeMatches( ... ).InterceptWith( o => new ObjectWrapper(o) ); - - - - - Designates a policy for scanning assemblies to auto - register types - - - - - - Directs StructureMap to always inject dependencies into any and all public Setter properties - of the type PLUGINTYPE. - - - - - - - Creates automatic "policies" for which public setters are considered mandatory - properties by StructureMap that will be "setter injected" as part of the - construction process. - - - - - - Use to programmatically select the constructor function of a concrete - class. Applies globally to all Containers in a single AppDomain. - - - - - - - All requests For the "TO" types will be filled by fetching the "FROM" - type and casting it to "TO" - GetInstance(typeof(TO)) basically becomes (TO)GetInstance(typeof(FROM)) - - - - - - - Syntactic Sugar for saying ForRequestedType().TheDefault.IsThis( @object ) - - - - - - - Syntactic Sugar for saying ForRequestedType().TheDefault.IsThis( instance ) - - - - - - - - Shorthand for ForRequestedType(pluginType) - - - - - - - - Advanced Usage Only! Skips the Registry and goes right to the inner - Semantic Model of StructureMap. Use with care - - - - - - Adds the concreteType as an Instance of the pluginType. Mostly useful - for conventions - - - - - - - Adds the concreteType as an Instance of the pluginType with a name. Mostly - useful for conventions - - - - - - - - Add the pluggedType as an instance to any configured pluginType where pluggedType. - Mostly useful for conventions - - - - - - Imports the configuration from another registry into this registry. - - - - - - Imports the configuration from another registry into this registry. - - - - - - Expression Builder used to define policies for a PluginType including - Scoping, the Default Instance, and interception. BuildInstancesOf() - and ForRequestedType() are synonyms - - - - - - - Expression Builder used to define policies for a PluginType including - Scoping, the Default Instance, and interception. This method is specifically - meant for registering open generic types - - - - - - This method is a shortcut for specifying the default constructor and - setter arguments for a ConcreteType. ForConcreteType is shorthand for: - For[T]().Use[T].************** - when the PluginType and ConcreteType are the same Type - - - - - - - Expression Builder used to define policies for a PluginType including - Scoping, the Default Instance, and interception. BuildInstancesOf() - and ForRequestedType() are synonyms - - - - - - - Convenience method. Equivalent of ForRequestedType[PluginType]().Singletons() - - - - - - - Uses the configuration expressions of this Registry to create a PluginGraph - object that could be used to initialize a Container. This method is - mostly for internal usage, but might be helpful for diagnostics - - - - - - Adds an additional, non-Default Instance to the PluginType T. - - - - - - - Adds an additional, non-Default Instance to the designated pluginType - This method is mostly meant for open generic types - - - - - - - Expression Builder to define the defaults for a named Profile. Each call - to CreateProfile is additive. - - - - - - - An alternative way to use CreateProfile that uses ProfileExpression - as a Nested Closure. This usage will result in cleaner code for - multiple declarations - - - - - - - Registers a new TypeInterceptor object with the Container - - - - - - Allows you to define a TypeInterceptor inline with Lambdas or anonymous delegates - - - - - IfTypeMatches( ... ).InterceptWith( o => new ObjectWrapper(o) ); - - - - - Designates a policy for scanning assemblies to auto - register types - - - - - - Directs StructureMap to always inject dependencies into any and all public Setter properties - of the type PLUGINTYPE. - - - - - - - Creates automatic "policies" for which public setters are considered mandatory - properties by StructureMap that will be "setter injected" as part of the - construction process. - - - - - - Use to programmatically select the constructor function of a concrete - class. Applies globally to all Containers in a single AppDomain. - - - - - - - All requests For the "TO" types will be filled by fetching the "FROM" - type and casting it to "TO" - GetInstance(typeof(TO)) basically becomes (TO)GetInstance(typeof(FROM)) - - - - - - - Syntactic Sugar for saying ForRequestedType().TheDefault.IsThis( @object ) - - - - - - - Syntactic Sugar for saying ForRequestedType().TheDefault.IsThis( instance ) - - - - - - - Expression Builder used to define policies for a PluginType including - Scoping, the Default Instance, and interception. BuildInstancesOf() - and ForRequestedType() are synonyms - - - - - - - Expression Builder used to define policies for a PluginType including - Scoping, the Default Instance, and interception. This method is specifically - meant for registering open generic types - - - - - - - Advanced Usage Only! Skips the Registry and goes right to the inner - Semantic Model of StructureMap. Use with care - - - - - - Define the constructor and setter arguments for the default T - - - - - - Thrown by IProperty classes when an invalid value is applied to - a property of an InstanceGraph - - - - - Main exception for StructureMap. Use the ErrorCode to aid in troubleshooting - StructureMap problems - - - - - Represents a concrete class that can be built by StructureMap as an instance of the parent - PluginFamily’s PluginType. The properties of a Plugin are the CLR Type of the concrete class, - and the human-friendly concrete key that StructureMap will use to identify the Type. - - - - - The ConcreteKey that identifies the Plugin within a PluginFamily - - - - - The concrete CLR Type represented by the Plugin - - - - - Property's that will be filled by setter injection - - - - - Conceptually speaking, a PluginFamily object represents a point of abstraction or variability in - the system. A PluginFamily defines a CLR Type that StructureMap can build, and all of the possible - Plugin’s implementing the CLR Type. - - - - - The CLR Type that defines the "Plugin" interface for the PluginFamily - - - - - The InstanceKey of the default instance of the PluginFamily - - - - - Custom collection class for PluginFamily's - - - - - Adds the concreteType as an Instance of the pluginType - - - - - - - Adds the concreteType as an Instance of the pluginType with a name - - - - - - - - Add the pluggedType as an instance to any configured pluginType where pluggedType - could be assigned to the pluginType - - - - - - Models the runtime configuration of a StructureMap Container - - - - - Closes the PluginGraph for adding or removing members. Runs all the AssemblyScanner's - and attempts to attach concrete types to the proper plugin types. Calculates the Profile defaults. - - - - - Adds the concreteType as an Instance of the pluginType - - - - - - - Adds the concreteType as an Instance of the pluginType with a name - - - - - - - - Add the pluggedType as an instance to any configured pluginType where pluggedType - could be assigned to the pluginType - - - - - - Adds an AssemblyScanner to the PluginGraph. Used for Testing. - - - - - - Add configuration to a PluginGraph with the Registry DSL - - - - - - Designates whether a PluginGraph has been "Sealed." - - - - - Represents a PropertyInfo of a Plugin.PluggedType that is filled by Setter Injection - - - - - Custom collection class for SetterProperty objects - - - - - Designates a CLR type that is loaded by name. - - - - - Interface for a "Factory" pattern class that creates object instances of the PluginType - - - - - The main "container" object that implements the Service Locator pattern - - - - - Creates or finds the named instance of the pluginType - - - - - - - - Creates or finds the default instance of the pluginType - - - - - - - Creates a new instance of the requested type using the supplied Instance. Mostly used internally - - - - - - - - Creates or finds the named instance of T - - - - - - - - Creates or finds the default instance of type T - - - - - - - Creates a new instance of the requested type T using the supplied Instance. Mostly used internally - - - - - - - Creates or resolves all registered instances of type T - - - - - - - Creates or resolves all registered instances of the pluginType - - - - - - - Creates or finds the named instance of the pluginType. Returns null if the named instance is not known to the container. - - - - - - - - Creates or finds the default instance of the pluginType. Returns null if the pluginType is not known to the container. - - - - - - - Creates or finds the default instance of type T. Returns the default value of T if it is not known to the container. - - - - - - - Creates or finds the named instance of type T. Returns the default value of T if the named instance is not known to the container. - - - - - - - Used to add additional configuration to a Container *after* the initialization. - - - - - - Injects the given object into a Container as the default for the designated - PLUGINTYPE. Mostly used for temporarily setting up return values of the Container - to introduce mocks or stubs during automated testing scenarios - - - - - - - Injects the given object into a Container as the default for the designated - pluginType. Mostly used for temporarily setting up return values of the Container - to introduce mocks or stubs during automated testing scenarios - - - - - - - Sets the default instance for all PluginType's to the designated Profile. - - - - - - Returns a report detailing the complete configuration of all PluginTypes and Instances - - - - - - Use with caution! Does a full environment test of the configuration of this container. Will try to create every configured - instance and afterward calls any methods marked with the [ValidationMethod] attribute - - - - - Gets all configured instances of type T using explicitly configured arguments from the "args" - - - - - - - - Gets the default instance of type T using the explicitly configured arguments from the "args" - - - - - - - - Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency - of type T should be "arg" - - - - - - - - Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency or primitive argument - with the designated name should be the next value. - - - - - - - Gets the default instance of the pluginType using the explicitly configured arguments from the "args" - - - - - - - - Removes all configured instances of type T from the Container. Use with caution! - - - - - - The "BuildUp" method takes in an already constructed object - and uses Setter Injection to push in configured dependencies - of that object - - - - - - Convenience method to request an object using an Open Generic - Type and its parameter Types - - - - - IFlattener flattener1 = container.ForGenericType(typeof (IFlattener<>)) - .WithParameters(typeof (Address)).GetInstanceAs<IFlattener>(); - - - - - Gets the named instance of the pluginType using the explicitly configured arguments from the "args" - - - - - - - - - Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency - of type T should be "arg" - - - - - - - - - Starts a "Nested" Container for atomic, isolated access - - - - - - Starts a new "Nested" Container for atomic, isolated service location. Opens - - - - - - - Provides queryable access to the configured PluginType's and Instances of this Container - - - - - Default implementation of IInstanceFactory - - - - - Constructor to use when troubleshooting possible configuration issues. - - - - - - Constructor to create an Container - - PluginGraph containing the instance and type definitions - for the Container - - - - Creates or finds the named instance of T - - - - - - - - Creates a new instance of the requested type T using the supplied Instance. Mostly used internally - - - - - - - Gets the default instance of the pluginType using the explicitly configured arguments from the "args" - - - - - - - Gets the default instance of the pluginType using the explicitly configured arguments from the "args" - - - - - - - - Gets all configured instances of type T using explicitly configured arguments from the "args" - - - - - - - - Creates or finds the default instance of type T - - - - - - - Creates or resolves all registered instances of type T - - - - - - - Sets the default instance for all PluginType's to the designated Profile. - - - - - - Creates or finds the named instance of the pluginType - - - - - - - - Creates or finds the named instance of the pluginType. Returns null if the named instance is not known to the container. - - - - - - - - Creates or finds the default instance of the pluginType. Returns null if the pluginType is not known to the container. - - - - - - - Creates or finds the default instance of type T. Returns the default value of T if it is not known to the container. - - - - - - - The "BuildUp" method takes in an already constructed object - and uses Setter Injection to push in configured dependencies - of that object - - - - - - Creates or finds the named instance of type T. Returns the default value of T if the named instance is not known to the container. - - - - - - - Creates or finds the default instance of the pluginType - - - - - - - Creates a new instance of the requested type using the supplied Instance. Mostly used internally - - - - - - - - Creates or resolves all registered instances of the pluginType - - - - - - - Used to add additional configuration to a Container *after* the initialization. - - - - - - Returns a report detailing the complete configuration of all PluginTypes and Instances - - - - - - Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency - of type T should be "arg" - - - - - - - - Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency - of type T should be "arg" - - - - - - - - Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency or primitive argument - with the designated name should be the next value. - - - - - - - Use with caution! Does a full environment test of the configuration of this container. Will try to create every configured - instance and afterward calls any methods marked with the [ValidationMethod] attribute - - - - - Removes all configured instances of type T from the Container. Use with caution! - - - - - - Convenience method to request an object using an Open Generic - Type and its parameter Types - - - - - IFlattener flattener1 = container.ForGenericType(typeof (IFlattener<>)) - .WithParameters(typeof (Address)).GetInstanceAs<IFlattener>(); - - - - - - Starts a "Nested" Container for atomic, isolated access - - - - - - Starts a new "Nested" Container for atomic, isolated service location. Opens - - - - - - - Injects the given object into a Container as the default for the designated - PLUGINTYPE. Mostly used for temporarily setting up return values of the Container - to introduce mocks or stubs during automated testing scenarios - - - - - - - Injects the given object into a Container as the default for the designated - pluginType. Mostly used for temporarily setting up return values of the Container - to introduce mocks or stubs during automated testing scenarios - - - - - - - Sets the default instance for the PluginType - - - - - - - Provides queryable access to the configured PluginType's and Instances of this Container - - - - - GoF Memento representing an Object Instance - - - - - Retrieves the named property value as a string - - - - - - - Template method for implementation specific retrieval of the named property - - - - - - - Returns the named child InstanceMemento - - - - - - - Template method for implementation specific retrieval of the named property - - - - - - - This method is made public for testing. It is not necessary for normal usage. - - - - - - Used to create a templated InstanceMemento - - - - - - - The named type of the object instance represented by the InstanceMemento. Translates to a concrete - type - - - - - The named key of the object instance represented by the InstanceMemento - - - - - Gets the referred template name - - - - - - Template pattern property specifying whether the InstanceMemento is simply a reference - to another named instance. Useful for child objects. - - - - - Template pattern property specifying the instance key that the InstanceMemento refers to - - - - - Is the InstanceMemento a reference to the default instance of the plugin type? - - - - - A TypeInterceptor that always applies to all Instances of a given Plugin Type - - - - - Abstract class that is the supertype of all storage and retrieval mechanisms of - InstanceMemento instances - - - - - Retrieves the named InstanceMemento - - The instanceKey of the requested InstanceMemento - - - - - Retrieves an array of all InstanceMemento's stored by this MementoSource - - - - - - Template pattern method. Determines if the MementoSource contains a definition for the - requested instanceKey. - - - - - - - Template pattern method. Retrieves an InstanceMemento for the instanceKey - - - - - - - The type of MementoSource - - - - - String description of the MementoSource. Used in the StructureMap-Client UI. - - - - - An in-memory implementation of InstanceMemento. - - - - - Creates an instance of MemoryInstanceMemento that represents a reference to another - instance. - - The referenced instance key to another instance - - - - - Creates a MemoryInstanceMemento that represents a reference to the default instance - of a plugin type. - - - - - - Constructs a MemoryInstanceMemento without properties - - The concrete key of the plugin type - The identifying instance key - - - - Constructs a MemoryInstanceMemento with properties - - The concrete key of the plugin type - The identifying instance key - NameValueCollection of instance properties - - - - Sets the value of the named property - - - - - - - Deletes a named property from the DefaultInstanceMemento - - - - - - Links a child InstanceMemento as a named property - - - - - - - Links an array of InstanceMemento's to a named array property - - - - - - - See InstanceMemento - - - - - See InstanceMemento - - - - - See InstanceMemento - - - - - See InstanceMemento - - - - - See InstanceMemento - - - - - The main static Facade for the StructureMap container - - - - - Restarts ObjectFactory and blows away all Singleton's and cached instances. Use with caution. - - - - - Remove and dispose all objects scoped by HttpContext. Call this method at the *end* of an Http request to clean up resources - - - - - Injects the given object into a Container as the default for the designated - pluginType. Mostly used for temporarily setting up return values of the Container - to introduce mocks or stubs during automated testing scenarios - - - - - - - Injects the given object into a Container as the default for the designated - PLUGINTYPE. Mostly used for temporarily setting up return values of the Container - to introduce mocks or stubs during automated testing scenarios - - - - - - - Returns a report detailing the complete configuration of all PluginTypes and Instances - - - - - - Use with caution! Does a full environment test of the configuration of this container. Will try to create every configured - instance and afterward calls any methods marked with the [ValidationMethod] attribute - - - - - Creates or finds the default instance of the pluginType - - - - - - - Creates or finds the default instance of type T - - - - - - - Creates a new instance of the requested type using the supplied Instance. Mostly used internally - - - - - - - - Creates a new instance of the requested type T using the supplied Instance. Mostly used internally - - - - - - - Creates or finds the named instance of the pluginType - - - - - - - - Creates or finds the named instance of T - - - - - - - - Creates or resolves all registered instances of the pluginType - - - - - - - Creates or resolves all registered instances of type T - - - - - - - Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency - of type T should be "arg" - - - - - - - - Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency or primitive argument - with the designated name should be the next value. - - - - - - - Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency - of type T should be "arg" - - - - - - - - Removes all configured instances of type T from the Container. Use with caution! - - - - - - Creates or finds the named instance of the pluginType. Returns null if the named instance is not known to the container. - - - - - - - - Creates or finds the default instance of the pluginType. Returns null if the pluginType is not known to the container. - - - - - - - Creates or finds the default instance of type T. Returns the default value of T if it is not known to the container. - - - - - - - Creates or finds the named instance of type T. Returns the default value of T if the named instance is not known to the container. - - - - - - - - The "BuildUp" method takes in an already constructed object - and uses Setter Injection to push in configured dependencies - of that object - - - - - - Convenience method to request an object using an Open Generic - Type and its parameter Types - - - - - IFlattener flattener1 = container.ForGenericType(typeof (IFlattener<>)) - .WithParameters(typeof (Address)).GetInstanceAs<IFlattener>(); - - - - - - Used to add additional configuration to a Container *after* the initialization. - - - - - - Provides queryable access to the configured PluginType's and Instances of the inner Container - - - - - Sets the default instance for all PluginType's to the designated Profile. - - - - - Reads configuration XML documents and builds the structures necessary to initialize - the Container/IInstanceFactory/InstanceBuilder/ObjectInstanceActivator objects - - - - - Reads the configuration information and returns the PluginGraph definition of - plugin families and plugin's - - - - - - Generic implementation of an XmlMementoSource - - - - - Base class for all MementoSource classes that store InstanceMemento's as - node-normalized Xml - - - - - Implementation of MementoSource that stores and retrieves an XmlInstanceMemento per file in a named directory. - DirectoryXmlMementoSource is meant to simplify complicated object graph configurations by isolating each instance to a separate - editable file. - - - - - Stores an Xml InstanceMemento per file in a directory - - A ";" delimited list of directories to look for mementos. DirectoryXmlMementoSource - will use the FIRST directory it finds - The file extension of the InstanceMemento files without a dot. Typically "xml" - NodeNormalized or AttributeNormalized - - - - Implementation of MementoSource that stores and retrieves an XmlInstanceMemento per Embedded Resource file - in a named namespace. EmbeddedFolderXmlMementoSource is meant to simplify complicated object graph configurations - by isolating each instance to a separate - editable file. - - NodeNormalized or AttributeNormalized - The name of the Assembly with the embedded resources - The root namespace of all of the mementos. - The file extension of the memento files - "xml" - - - - An in-memory MementoSource - - - - - Retrieves Xml InstanceMemento's from an xml file stored as an embedded resource in an assembly. - - Designates the nodes that are memento nodes - NodeNormalized or AttributeNormalized - The name of the Assembly the file is embedded into - The path to the embedded resource within the file - - - - Default Constructor - - MementoSource that contains the Memento Templates - MementoSource that contains instances consisting of Template valuee - - - - Stores Attribute-normalized InstanceMemento's in an external file - - - - - Implementation of XmlMementoSource that reads InstanceMemento's from an external file. - Useful to break the StructureMap.config file into smaller pieces. - - - - - Default constructor - - Path to the xml file that contains the instance configuration - XPath expression to the parent node that contains the InstanceMemento nodes. - If empty, it defaults to the top node - The name of the nodes that are InstanceMemento nodes. Useful to store - different types of instances in the same file - - - - An implementation of InstanceMemento that stores properties as Xml attributes - Limited functionality - - - - - Implementation of InstanceMemento that stores information in a node-normalized - Xml format. - - - - - specify what type you'd like the service returned as - - - - - - - Specify the open generic type that should have a single generic parameter - - - - - - - Used as the argument in the Container.Configure() method to describe - configuration directives and specify the sources of configuration for - a Container - - - - - Creates and adds a Registry object of type T. - - The Registry Type - - - - Imports all the configuration from a Registry object - - - - - - Imports configuration from an Xml file. The fileName - must point to an Xml file with valid StructureMap - configuration - - - - - - Imports configuration directly from an XmlNode. This - method was intended for scenarios like Xml being embedded - into an assembly. The node must be a 'StructureMap' node - - - - - - If true, directs StructureMap to look for configuration in the App.config. - The default value is false. - - - - - Expression Builder to define an Instance - - - - - - Register a previously built Instance. This provides a "catch all" - method to attach custom Instance objects. Synonym for Instance() - - - - - - Inject this object directly. Synonym to Object() - - - - - - - Gives you full access to all the different ways to specify an "Instance" - - - - - An Expression Builder to define Instances of a PluginType. - This is mostly used for configuring open generic types - - - - - Shortcut to register a Concrete Type as an instance. This method supports - method chaining to allow you to add constructor and setter arguments for - the concrete type - - - - - - - Shortcut to simply use the Instance with the given name - - - - - - - An Expression Builder that is used throughout the Registry DSL to - add and define Instances - - - - - - Register a previously built Instance. This provides a "catch all" - method to attach custom Instance objects. Synonym for IsThis() - - - - - - Inject this object directly. Synonym to IsThis() - - - - - - - Build the Instance with the constructor function and setter arguments. Starts - the definition of a SmartInstance - - - - - - - Build the Instance with the constructor function and setter arguments. Starts - the definition of a SmartInstance - - - - - - - Build the Instance with the constructor function and setter arguments. Use this - method for open generic types, and favor the generic version of OfConcreteType - for all other types - - - - - - - Build the Instance with the constructor function and setter arguments. Use this - method for open generic types, and favor the generic version of OfConcreteType - for all other types - - - - - - - Create an Instance that builds an object by calling a Lambda or - an anonymous delegate with no arguments - - - - - - - Create an Instance that builds an object by calling a Lambda or - an anonymous delegate with the IContext representing - the current object graph. - - - - - - - Use the Instance of this PluginType with the specified name. This is - generally only used while configuring child dependencies within a deep - object graph - - - - - - - Use the default Instance of this PluginType. This is - generally only used while configuring child dependencies within a deep - object graph - - - - - - Creates an Instance that stores this object of type T, - and returns a cloned copy of the template. - - - - - - - Caches template as a serialized byte stream. Uses deserialization - to create copies when the Instance is built. - - - - - - - Creates an Instance that will load an ASCX user control from the url - - - - - - - Creates an Instance according to conditional rules - - - - - - - Used as an expression builder to specify setter injection policies - - - - - Directs StructureMap to treat all public setters of type T as - mandatory properties - - - - - - Directs StructureMap to tread all public setters with - a PropertyType that matches the predicate as a - mandatory setter - - - - - - Directs StructureMap to treat all public setters that match the - rule as mandatory properties - - - - - - Directs StructureMap to treat all public setters with a property - type in the specified namespace as mandatory properties - - - - - - Directs StructureMap to treat all public setters with a property - type in the specified namespace as mandatory properties - - - - - - Directs StructureMap to treat all public setters where to property name - matches the specified rule as a mandatory property - - - - - - Base class for creating an object instance from an InstanceMemento. SubClasses are - emitted for each concrete Plugin with constructor parameters. - - - - - Allows built-in registration conventions to be configurable through the assembly scanning DSL - - - Intended for StructureMap internal use only. - Custom registration convention instances can be directly configured - before being passed to IAssemblyScanner.With(IRegistrationConvention). - - - - - Simply query to see if there are any implementations registered - - - - - - Ejects any instances of this instance from the current container - and permanently removes the instance from the container configuration - - - - - - Eject all instances of this PluginType from the current container, - but leaves the lifecycle behavior - - - - - The "instance" that will be used when Container.GetInstance(PluginType) is called. - See InstanceRef for more information - - - - - The build "policy" for this PluginType. Used by the WhatDoIHave() diagnostics methods - - - - - All of the InstanceRef's registered - for this PluginType - - - - - Simply query to see if there are any implementations registered - - - - - - The "instance" that will be used when Container.GetInstance(PluginType) is called. - See InstanceRef for more information - - - - - The build "policy" for this PluginType. Used by the WhatDoIHave() diagnostics methods - - - - - All of the InstanceRef's registered - for this PluginType - - - - - Simply query to see if there are any implementations registered - - - - - - The "instance" that will be used when Container.GetInstance(PluginType) is called. - See InstanceRef for more information - - - - - The build "policy" for this PluginType. Used by the WhatDoIHave() diagnostics methods - - - - - All of the InstanceRef's registered - for this PluginType - - - - - Models the state of a Container or ObjectFactory. Can be used to query for the - existence of types registered with StructureMap - - - - - Can StructureMap fulfill a request to ObjectFactory.GetInstance(pluginType) from the - current configuration. This does not include concrete classes that could be auto-configured - upon demand - - - - - - - Can StructureMap fulfill a request to ObjectFactory.GetInstance<T>() from the - current configuration. This does not include concrete classes that could be auto-configured - upon demand - - - - - - - Queryable access to all of the InstanceRef for a given PluginType - - - - - - - Queryable access to all of the InstanceRef for a given PluginType - - - - - - Does the current container have existing configuration for the "pluginType" - - - - - - - Does the current container have existing configuration for the type T - - - - - - Find the concrete type for the default Instance of T. - In other words, when I call Container.GetInstance(Type), - what do I get? May be indeterminate - - - - - - - Find the concrete type for the default Instance of pluginType. - In other words, when I call Container.GetInstance(Type), - what do I get? May be indeterminate - - - - - - Retrieves the configuration for the given type - - - - - - - Retrieves the configuration for the given type - - - - - - - Eject all objects, configuration, and Plugin Types matching this filter - - - - - - Eject all objects and configuration for any Plugin Type that matches this filter - - - - - - Eject all objects and Instance configuration for this PluginType - - - - - - Get each and every configured instance that could possibly - be cast to T - - - - - - - Access to all the Plugin Type registrations - - - - - Makes sure that every request for this object returns a unique object - - - - - Simply query to see if there are any implementations registered - - - - - - The "instance" that will be used when Container.GetInstance(PluginType) is called. - See InstanceRef for more information - - - - - The build "policy" for this PluginType. Used by the WhatDoIHave() diagnostics methods - - - - - All of the InstanceRef's registered - for this PluginType - - - - - The actual concrete type of this Instance. Not every type of IInstance - can determine the ConcreteType - - - - - Ejects and removes all objects and the configuration for the named instance from the - container - - - - - - - Ejects and removes all objects and configuration for the instances that match the filter - - - - - - - Determines if the pluggedType can be upcast to the pluginType - - - - - - - - Determines if the PluggedType is a valid Plugin into the - PluginType - - - - - - - - Imports configuration from an Xml file. The fileName - must point to an Xml file with valid StructureMap - configuration - - - - - - Imports configuration directly from an XmlNode. This - method was intended for scenarios like Xml being embedded - into an assembly. The node must be a 'StructureMap' node - - - - - - Creates and adds a Registry object of type T. - - The Registry Type - - - - Imports all the configuration from a Registry object - - - - - - If true, makes the existence of the StructureMap.config mandatory. - The default is false. - - - - - If true, the StructureMap.config file will be ignored even if it exists. - The default is false. - - - - - If true, directs StructureMap to look for configuration in the App.config. - The default value is false. - - - - - Designate the Default Profile. This will be applied as soon as the - Container is initialized. - - - - - Retrieves the configuration for the given type - - - - - - - Retrieves the configuration for the given type - - - - - - - Eject all objects, configuration, and Plugin Types matching this filter - - - - - - Eject all objects and configuration for any Plugin Type that matches this filter - - - - - - Eject all objects and Instance configuration for this PluginType - - - - - - Get each and every configured instance that could possibly - be cast to T - - - - - - - The requested PluginType of the Instance being create - - - - - The Name of the Instance being created - - - - - The actual ConcreteType being created. This will not always - be available - - - - - Models the current place in an object graph during the construction of - an instance. Provides contextual information that can be used - to alter the desired construction of child objects - - - - - The requested PluginType of the Instance being create - - - - - The Name of the Instance being created - - - - - The actual ConcreteType being created. This will not always - be available - - - - - Provides metadata about the object graph being constructed. More or less a stack trace of the GetInstance() pipeline - that can be used for "contextual" object construction - - - - - The top level of the object graph. Describes the original requested instance - - - - - The current BuildFrame - - - - - The immediate parent BuildFrame - - - - - Defines the value of a primitive argument to a constructur argument - - - - - Sets the value of the constructor argument - - - - - - - Sets the value of the constructor argument to the key/value in the - AppSettings - - The key in appSettings for the value to use. - - - - - Sets the value of the constructor argument to the key/value in the - AppSettings when it exists. Otherwise uses the provided default value. - - The key in appSettings for the value to use. - The value to use if an entry for does not exist in the appSettings section. - - - - - Instance that builds objects with by calling constructor functions and using setter properties - - The concrete type constructed by SmartInstance - - - - Sets the name of this Instance - - - - - - - Sets the name of this Instance - - - - - - - Register an Action to perform on the object created by this Instance - before it is returned to the caller - - - - - - - Register an Action to perform on the object created by this Instance - before it is returned to the caller - - - - - - - Register a Func to potentially enrich or substitute for the object - created by this Instance before it is returned to the caller - - - - - - - Register a Func to potentially enrich or substitute for the object - created by this Instance before it is returned to the caller - - - - - - - Register a Func to potentially enrich or substitute for the object - created by this Instance before it is returned to the caller - - - - - - - Register a Func to potentially enrich or substitute for the object - created by this Instance before it is returned to the caller - - - - - - - Register an InstanceInterceptor with this Instance - - - - - - - Define a primitive constructor argument - - - - - - - Set simple setter properties - - - - - - - Define a primitive setter property by specifying the property name with - an expression - - - - - - - Define a primitive setter property by specifying the property name - - - - - - - Inline definition of a constructor dependency. Select the constructor argument by type. Do not - use this method if there is more than one constructor arguments of the same type - - - - - - - Inline definition of a constructor dependency. Select the constructor argument by type. Do not - use this method if there is more than one constructor arguments of the same type - - - - - - - Inline definition of a constructor dependency. Select the constructor argument by type and constructor name. - Use this method if there is more than one constructor arguments of the same type - - - - - - - - Inline definition of a constructor dependency. Select the constructor argument by type and constructor name. - Use this method if there is more than one constructor arguments of the same type - - - - - - - - Inline definition of a setter dependency. The property name is specified with an Expression - - - - - - - - Inline definition of a setter dependency. The property name is specified with an Expression - - - - - - - - Inline definition of a setter dependency. Only use this method if there - is only a single property of the SETTERTYPE - - - - - - - Inline definition of a setter dependency. Only use this method if there - is only a single property of the SETTERTYPE - - - - - - - Inline definition of a dependency on an Array of the CHILD type. I.e. CHILD[]. - This method can be used for either constructor arguments or setter properties - - - - - - - Inline definition of a dependency on an Array of the CHILD type and the specified setter property or constructor argument name. I.e. CHILD[]. - This method can be used for either constructor arguments or setter properties - - - - - - - - Inline definition of a dependency on an Array of the CHILD type. I.e. CHILD[]. - This method can be used for either constructor arguments or setter properties - - - - - - - Inline definition of a dependency on an Array of the CHILD type and the specified setter property or constructor argument name. I.e. CHILD[]. - This method can be used for either constructor arguments or setter properties - - - - - - - - Expression Builder to help define multiple Instances for an Array dependency - - - - - - Nested Closure that allows you to add an unlimited number of child Instances - - - - - - - Specify an array of Instance objects directly for an Array dependency - - - - - - - Expression Builder that helps to define child dependencies inline - - - - - - Sets the value of the constructor argument to the key/value in the - AppSettings - - The key in appSettings for the value to use. - - - - - Sets the value of the constructor argument to the key/value in the - AppSettings when it exists. Otherwise uses the provided default value. - - The key in appSettings for the value to use. - The value to use if an entry for does not exist in the appSettings section. - - - - - Nested Closure to define a child dependency inline - - - - - - - Shortcut to set an inline dependency to an Instance - - - - - - - Shortcut to set an inline dependency to a designated object - - - - - - - Shortcut to set an inline dependency to a designated object - - - - - - - Set an Inline dependency to the Default Instance of the Property type - Used mostly to force an optional Setter property to be filled by - StructureMap - - - - - - Shortcut method to define a child dependency inline - - - - - - - Shortcut method to define a child dependency inline and configure - the child dependency - - - - - - - Provides virtual methods that can be used by subclasses to parse an expression tree. - - - This class actually already exists in the System.Core assembly...as an internal class. - I can only speculate as to why it is internal, but it is obviously much too dangerous - for anyone outside of Microsoft to be using... - - - - diff --git a/src/Packages/structuremap.2.6.3/lib/StructureMap.dll b/src/Packages/structuremap.2.6.3/lib/StructureMap.dll deleted file mode 100644 index e2ca021..0000000 Binary files a/src/Packages/structuremap.2.6.3/lib/StructureMap.dll and /dev/null differ diff --git a/src/Packages/structuremap.2.6.3/structuremap.2.6.3.nupkg b/src/Packages/structuremap.2.6.3/structuremap.2.6.3.nupkg deleted file mode 100644 index 31aa336..0000000 Binary files a/src/Packages/structuremap.2.6.3/structuremap.2.6.3.nupkg and /dev/null differ diff --git a/src/ServiceLocators/SimpleCqrs.StructureMap/Properties/AssemblyInfo.cs b/src/ServiceLocators/SimpleCqrs.StructureMap/Properties/AssemblyInfo.cs deleted file mode 100644 index f01b7a3..0000000 --- a/src/ServiceLocators/SimpleCqrs.StructureMap/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("SimpleCqrs.StructureMap")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("SimpleCqrs.StructureMap")] -[assembly: AssemblyCopyright("Copyright © 2011")] -[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("45b7d4d4-3fac-49df-9cc3-45a59b1b59a0")] - -// 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/src/ServiceLocators/SimpleCqrs.StructureMap/SimpleCqrs.StructureMap.csproj b/src/ServiceLocators/SimpleCqrs.StructureMap/SimpleCqrs.StructureMap.csproj deleted file mode 100644 index 72f26e4..0000000 --- a/src/ServiceLocators/SimpleCqrs.StructureMap/SimpleCqrs.StructureMap.csproj +++ /dev/null @@ -1,62 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {9C1063E4-1A0B-4402-8D78-A3F8E23D3D98} - Library - Properties - SimpleCqrs.StructureMap - SimpleCqrs.StructureMap - v4.0 - 512 - - - true - full - false - ..\..\..\binaries\servicelocators\structuremap\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - ..\..\..\binaries\servicelocators\structuremap\ - TRACE - prompt - 4 - - - - ..\..\packages\structuremap.2.6.3\lib\StructureMap.dll - - - - - - - - - - - - - - - {E04C12B5-A6D3-4D64-9F38-896BEE68162E} - SimpleCqrs - - - - - \ No newline at end of file diff --git a/src/ServiceLocators/SimpleCqrs.StructureMap/StructureMapServiceLocator.cs b/src/ServiceLocators/SimpleCqrs.StructureMap/StructureMapServiceLocator.cs deleted file mode 100644 index 78e77f7..0000000 --- a/src/ServiceLocators/SimpleCqrs.StructureMap/StructureMapServiceLocator.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; -using System.Collections.Generic; -using StructureMap; - -namespace SimpleCqrs.StructureMap -{ - public class StructureMapServiceLocator : IServiceLocator - { - private static bool _isDisposing; - - public StructureMapServiceLocator() : this(ObjectFactory.Container) {} - - public StructureMapServiceLocator(IContainer container) - { - Container = container; - } - - public IContainer Container { private set; get; } - - public T Resolve() where T : class - { - try - { - return Container.GetInstance(); - } - catch (Exception ex) - { - throw new ServiceResolutionException(typeof(T), ex); - } - } - - public T Resolve(string key) where T : class - { - try - { - return Container.GetInstance(key); - } - catch (Exception ex) - { - throw new ServiceResolutionException(typeof(T), ex); - } - } - - public object Resolve(Type type) - { - try - { - return Container.GetInstance(type); - } - catch (Exception ex) - { - throw new ServiceResolutionException(type, ex); - } - } - - public IList ResolveServices() where T : class - { - return Container.GetAllInstances(); - } - - public void Register(Type implType) where TInterface : class - { - var key = string.Format("{0}-{1}", typeof(TInterface).Name, implType.FullName); - Container.Configure(x => x.For(implType).Use(implType).Named(key)); - - // Work-around, also register this implementation to service mapping - // without the generated key above. - Container.Configure(x => x.For(implType).Use(implType)); - } - - public void Register() where TImplementation : class, TInterface - { - Container.Configure(x => x.For().Use()); - } - - public void Register(string key) where TImplementation : class, TInterface - { - Container.Configure(x => x.For().Use().Named(key)); - } - - public void Register(string key, Type type) - { - Container.Configure(x => x.For(type).Use(type).Named(key)); - } - - public void Register(Type serviceType, Type implType) - { - Container.Configure(x => x.For(serviceType).Use(implType)); - } - - public void Register(TInterface instance) where TInterface : class - { - Container.Configure(x => x.For().Use(instance)); - } - - public void Register(Func factoryMethod) where TInterface : class - { - Container.Configure(x => x.For().Use(factoryMethod)); - } - - public void Release(object instance) - { - //Not needed for StructureMap it doesn't keep references beyond the life cycle that was configured. - } - - public void Reset() - { - throw new NotSupportedException("StructureMap does not support reset"); - } - - public TService Inject(TService instance) where TService : class - { - if (instance == null) - return null; - - Container.BuildUp(instance); - - return instance; - } - - public void TearDown(TService instance) where TService : class - { - //Not needed for StructureMap it doesn't keep references beyond the life cycle that was configured. - } - - public void Dispose() - { - if (_isDisposing) return; - if (Container == null) return; - - _isDisposing = true; - Container.Dispose(); - Container = null; - } - } -} \ No newline at end of file diff --git a/src/ServiceLocators/SimpleCqrs.StructureMap/packages.config b/src/ServiceLocators/SimpleCqrs.StructureMap/packages.config deleted file mode 100644 index a4bbf56..0000000 --- a/src/ServiceLocators/SimpleCqrs.StructureMap/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/src/ServiceLocators/SimpleCqrs.Unity/Properties/AssemblyInfo.cs b/src/ServiceLocators/SimpleCqrs.Unity/Properties/AssemblyInfo.cs deleted file mode 100644 index bef6567..0000000 --- a/src/ServiceLocators/SimpleCqrs.Unity/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("SimpleCqrs.Unity")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("DEG")] -[assembly: AssemblyProduct("SimpleCqrs.Unity")] -[assembly: AssemblyCopyright("Copyright © DEG 2010")] -[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("e6884286-6931-4449-bbc1-87961a27e5ec")] - -// 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/src/ServiceLocators/SimpleCqrs.Unity/SimpleCqrs.Unity.csproj b/src/ServiceLocators/SimpleCqrs.Unity/SimpleCqrs.Unity.csproj deleted file mode 100644 index 1fc983d..0000000 --- a/src/ServiceLocators/SimpleCqrs.Unity/SimpleCqrs.Unity.csproj +++ /dev/null @@ -1,62 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {00634E6C-A282-404A-B08B-338FD4CA41A9} - Library - Properties - SimpleCqrs.Unity - SimpleCqrs.Unity - v4.0 - 512 - - - true - full - false - ..\..\..\binaries\servicelocators\unity\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - False - ..\..\..\lib\Microsoft.Practices.Unity.dll - True - - - - - - - - - - - - {E04C12B5-A6D3-4D64-9F38-896BEE68162E} - SimpleCqrs - False - - - - - \ No newline at end of file diff --git a/src/ServiceLocators/SimpleCqrs.Unity/UnityServiceLocator.cs b/src/ServiceLocators/SimpleCqrs.Unity/UnityServiceLocator.cs deleted file mode 100644 index 06959b3..0000000 --- a/src/ServiceLocators/SimpleCqrs.Unity/UnityServiceLocator.cs +++ /dev/null @@ -1,171 +0,0 @@ -using System; -using System.Collections.Generic; -using Microsoft.Practices.Unity; - -#region License - -// -// Author: Javier Lozano -// Copyright (c) 2009-2010, lozanotek, inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#endregion - -namespace SimpleCqrs.Unity -{ - public class UnityServiceLocator : IServiceLocator - { - public UnityServiceLocator() - : this(new UnityContainer()) - { - } - - public UnityServiceLocator(IUnityContainer container) - { - if(container == null) - throw new ArgumentNullException("container", "The specified Unity container cannot be null."); - - Container = container; - } - - public IUnityContainer Container { private set; get; } - - public T Resolve() where T : class - { - try - { - return Container.Resolve(); - } - catch (Exception ex) - { - throw new ServiceResolutionException(typeof(T), ex); - } - } - - public T Resolve(string key) where T : class - { - try - { - return Container.Resolve(key); - } - catch (Exception ex) - { - throw new ServiceResolutionException(typeof(T), ex); - } - } - - public T Resolve(Type type) where T : class - { - try - { - return Container.Resolve(type) as T; - } - catch (Exception ex) - { - throw new ServiceResolutionException(type, ex); - } - } - - public object Resolve(Type type) - { - try - { - return Container.Resolve(type); - } - catch (Exception ex) - { - throw new ServiceResolutionException(type, ex); - } - } - - public IList ResolveServices() where T : class - { - var services = Container.ResolveAll(); - return new List(services); - } - - public void Register(Type implType) where TInterface : class - { - var key = string.Format("{0}-{1}", typeof(TInterface).Name, implType.FullName); - Container.RegisterType(typeof(TInterface), implType, key); - - // Work-around, also register this implementation to service mapping - // without the generated key above. - Container.RegisterType(typeof(TInterface), implType); - } - - public void Register() - where TImplementation : class, TInterface - { - Container.RegisterType(); - } - - public void Register(string key) - where TImplementation : class, TInterface - { - Container.RegisterType(key); - } - - public void Register(string key, Type type) - { - Container.RegisterType(type, key); - } - - public void Register(Type serviceType, Type implType) - { - Container.RegisterType(serviceType, implType); - } - - public void Register(TInterface instance) where TInterface : class - { - Container.RegisterInstance(instance); - } - - public void Register(Func factoryMethod) where Interface : class - { - var container = Container; - Func factoryFunc = c => factoryMethod.Invoke(); - container.RegisterType(new InjectionFactory(factoryFunc)); - } - - public void Release(object instance) - { - if (instance == null) return; - - Container.Teardown(instance); - } - - public void Reset() - { - Dispose(); - } - - public TService Inject(TService instance) where TService : class - { - return instance == null ? instance : (TService)Container.BuildUp(instance.GetType(), instance); - } - - public void TearDown(TService instance) where TService : class - { - if (instance == null) return; - Container.Teardown(instance); - } - - public void Dispose() - { - Container.Dispose(); - } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs.Utilites/DomainEventReplayer.cs b/src/SimpleCqrs.Utilites/DomainEventReplayer.cs deleted file mode 100644 index 0b34c2d..0000000 --- a/src/SimpleCqrs.Utilites/DomainEventReplayer.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.Utilites -{ - public class DomainEventReplayer - { - private readonly ISimpleCqrsRuntime runtime; - - public DomainEventReplayer(ISimpleCqrsRuntime runtime) - { - this.runtime = runtime; - } - - public void ReplayEventsForHandlerType(Type handlerType) - { - ReplayEventsForHandlerType(handlerType, DateTime.MinValue, DateTime.MaxValue); - } - - public void ReplayEventsForHandlerType(Type handlerType, Guid aggregateRootId) - { - runtime.Start(); - - var serviceLocator = runtime.ServiceLocator; - var eventStore = serviceLocator.Resolve(); - var domainEventTypes = GetDomainEventTypesHandledByHandler(handlerType); - - var domainEvents = eventStore.GetEventsByEventTypes(domainEventTypes, aggregateRootId); - var eventBus = new LocalEventBus(new[] { handlerType }, new DomainEventHandlerFactory(serviceLocator)); - - eventBus.PublishEvents(domainEvents); - } - - public void ReplayEventsForHandlerType(Type handlerType, DateTime startDate, DateTime endDate) - { - runtime.Start(); - - var serviceLocator = runtime.ServiceLocator; - var eventStore = serviceLocator.Resolve(); - var domainEventTypes = GetDomainEventTypesHandledByHandler(handlerType); - - var domainEvents = eventStore.GetEventsByEventTypes(domainEventTypes, startDate, endDate); - var eventBus = new LocalEventBus(new[] {handlerType}, new DomainEventHandlerFactory(serviceLocator)); - - eventBus.PublishEvents(domainEvents); - } - - private static IEnumerable GetDomainEventTypesHandledByHandler(Type handlerType) - { - return (from i in handlerType.GetInterfaces() - where i.IsGenericType - where i.GetGenericTypeDefinition() == typeof(IHandleDomainEvents<>) - select i.GetGenericArguments()[0]).ToList(); - } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs.Utilites/Properties/AssemblyInfo.cs b/src/SimpleCqrs.Utilites/Properties/AssemblyInfo.cs deleted file mode 100644 index 6975d03..0000000 --- a/src/SimpleCqrs.Utilites/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("SimpleCqrs.EventReplay")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SimpleCqrs.EventReplay")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] -[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("a16fb8bc-375d-45c1-a757-169fd70fad65")] - -// 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/src/SimpleCqrs.Utilites/SimpleCqrs.Utilites.csproj b/src/SimpleCqrs.Utilites/SimpleCqrs.Utilites.csproj deleted file mode 100644 index dc2de81..0000000 --- a/src/SimpleCqrs.Utilites/SimpleCqrs.Utilites.csproj +++ /dev/null @@ -1,66 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {266DAB4E-3EAD-46A5-88D5-0D9B6EC73A86} - Library - Properties - SimpleCqrs.Utilites - SimpleCqrs.Utilites - v4.0 - 512 - - - true - full - false - ..\..\binaries\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\lib\MongoDB.dll - - - - - - - - - - - - - - - {201A4DF5-2217-4202-80E8-E784737366BC} - SimpleCqrs.EventStore.MongoDb - - - {E04C12B5-A6D3-4D64-9F38-896BEE68162E} - SimpleCqrs - - - - - \ No newline at end of file diff --git a/src/SimpleCqrs/AssemblyTypeCatalog.cs b/src/SimpleCqrs/AssemblyTypeCatalog.cs deleted file mode 100644 index 49f125f..0000000 --- a/src/SimpleCqrs/AssemblyTypeCatalog.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Reflection; - -namespace SimpleCqrs -{ - public class AssemblyTypeCatalog : ITypeCatalog - { - private readonly IEnumerable loadedTypes; - - public AssemblyTypeCatalog(IEnumerable assemblies) - { - loadedTypes = LoadTypes(assemblies); - } - - public Type[] LoadedTypes - { - get { return loadedTypes.ToArray(); } - } - - public Type[] GetDerivedTypes(Type type) - { - return ( - from derivedType in loadedTypes - where type != derivedType - where type.IsAssignableFrom(derivedType) - select derivedType).ToArray(); - } - - public Type[] GetDerivedTypes() - { - return GetDerivedTypes(typeof(T)); - } - - public Type[] GetGenericInterfaceImplementations(Type type) - { - return (from derivedType in loadedTypes - from interfaceType in derivedType.GetInterfaces() - where interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == type - select derivedType).Distinct().ToArray(); - } - - public Type[] GetInterfaceImplementations(Type type) - { - return (from derivedType in loadedTypes - where !derivedType.IsInterface - from interfaceType in derivedType.GetInterfaces() - where interfaceType == type - select derivedType).Distinct().ToArray(); - } - - public Type[] GetInterfaceImplementations() - { - return GetInterfaceImplementations(typeof(T)); - } - - private static IEnumerable LoadTypes(IEnumerable assemblies) - { - var loadedTypes = new List(); - foreach(var assembly in assemblies) - { - try - { - var types = assembly.GetTypes(); - loadedTypes.AddRange(types); - } - catch(ReflectionTypeLoadException exception) - { - exception.LoaderExceptions - .Select(e => e.Message) - .Distinct().ToList() - .ForEach(message => Debug.WriteLine(message)); - } - } - - return loadedTypes; - } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Domain/AggregateRootNotFoundException.cs b/src/SimpleCqrs/Domain/AggregateRootNotFoundException.cs deleted file mode 100644 index 39e1ce6..0000000 --- a/src/SimpleCqrs/Domain/AggregateRootNotFoundException.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace SimpleCqrs.Domain -{ - public class AggregateRootNotFoundException : Exception - { - public Guid AggregateRootId { get; private set; } - public Type Type { get; private set; } - - public AggregateRootNotFoundException(Guid aggregateRootId, Type type) - { - AggregateRootId = aggregateRootId; - Type = type; - } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Domain/DomainRepository.cs b/src/SimpleCqrs/Domain/DomainRepository.cs deleted file mode 100644 index 9f43103..0000000 --- a/src/SimpleCqrs/Domain/DomainRepository.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Linq; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.Domain -{ - public class DomainRepository : IDomainRepository - { - private readonly IEventBus eventBus; - private readonly IEventStore eventStore; - private readonly ISnapshotStore snapshotStore; - - public DomainRepository(IEventStore eventStore, ISnapshotStore snapshotStore, IEventBus eventBus) - { - this.eventStore = eventStore; - this.snapshotStore = snapshotStore; - this.eventBus = eventBus; - } - - public virtual TAggregateRoot GetById(Guid aggregateRootId) where TAggregateRoot : AggregateRoot, new() - { - var aggregateRoot = new TAggregateRoot(); - var snapshot = GetSnapshotFromSnapshotStore(aggregateRootId); - var lastEventSequence = snapshot == null || !(aggregateRoot is ISnapshotOriginator) ? 0 : snapshot.LastEventSequence; - var domainEvents = eventStore.GetEvents(aggregateRootId, lastEventSequence).ToArray(); - - if (lastEventSequence == 0 && domainEvents.Length == 0) - return null; - - LoadSnapshot(aggregateRoot, snapshot); - aggregateRoot.LoadFromHistoricalEvents(domainEvents); - - return aggregateRoot; - } - - public virtual TAggregateRoot GetExistingById(Guid aggregateRootId) where TAggregateRoot : AggregateRoot, new() - { - var aggregateRoot = GetById(aggregateRootId); - - if(aggregateRoot == null) - throw new AggregateRootNotFoundException(aggregateRootId, typeof(TAggregateRoot)); - - return aggregateRoot; - } - - public virtual void Save(AggregateRoot aggregateRoot) - { - var domainEvents = aggregateRoot.UncommittedEvents; - - eventStore.Insert(domainEvents); - eventBus.PublishEvents(domainEvents); - - aggregateRoot.CommitEvents(); - - SaveSnapshot(aggregateRoot); - } - - private void SaveSnapshot(AggregateRoot aggregateRoot) - { - var snapshotOriginator = aggregateRoot as ISnapshotOriginator; - - if(snapshotOriginator == null) - return; - - var previousSnapshot = snapshotStore.GetSnapshot(aggregateRoot.Id); - - if (!snapshotOriginator.ShouldTakeSnapshot(previousSnapshot)) return; - - var snapshot = snapshotOriginator.GetSnapshot(); - snapshot.AggregateRootId = aggregateRoot.Id; - snapshot.LastEventSequence = aggregateRoot.LastEventSequence; - - snapshotStore.SaveSnapshot(snapshot); - } - - private static void LoadSnapshot(AggregateRoot aggregateRoot, Snapshot snapshot) - { - var snapshotOriginator = aggregateRoot as ISnapshotOriginator; - if(snapshot != null && snapshotOriginator != null) - { - snapshotOriginator.LoadSnapshot(snapshot); - aggregateRoot.Id = snapshot.AggregateRootId; - aggregateRoot.LastEventSequence = snapshot.LastEventSequence; - } - } - - private Snapshot GetSnapshotFromSnapshotStore(Guid aggregateRootId) - { - return snapshotStore.GetSnapshot(aggregateRootId); - } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Domain/IDomainRepository.cs b/src/SimpleCqrs/Domain/IDomainRepository.cs deleted file mode 100644 index a7c7f26..0000000 --- a/src/SimpleCqrs/Domain/IDomainRepository.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace SimpleCqrs.Domain -{ - public interface IDomainRepository - { - TAggregateRoot GetById(Guid aggregateRootId) where TAggregateRoot : AggregateRoot, new(); - TAggregateRoot GetExistingById(Guid aggregateRootId) where TAggregateRoot : AggregateRoot, new(); - void Save(AggregateRoot aggregateRoot); - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Domain/IGenerateEventSequences.cs b/src/SimpleCqrs/Domain/IGenerateEventSequences.cs deleted file mode 100644 index 80be268..0000000 --- a/src/SimpleCqrs/Domain/IGenerateEventSequences.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace SimpleCqrs.Domain -{ - public interface IGenerateEventSequences - { - int GetNextSequence(); - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Domain/IRegisterEntities.cs b/src/SimpleCqrs/Domain/IRegisterEntities.cs deleted file mode 100644 index 4add0e1..0000000 --- a/src/SimpleCqrs/Domain/IRegisterEntities.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace SimpleCqrs.Domain -{ - public interface IRegisterEntities - { - void RegisterEntity(Entity entity); - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Domain/ISnapshotOriginator.cs b/src/SimpleCqrs/Domain/ISnapshotOriginator.cs deleted file mode 100644 index e5ade0f..0000000 --- a/src/SimpleCqrs/Domain/ISnapshotOriginator.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace SimpleCqrs.Domain -{ - public interface ISnapshotOriginator - { - Snapshot GetSnapshot(); - void LoadSnapshot(Snapshot snapshot); - bool ShouldTakeSnapshot(Snapshot previousSnapshot); - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Eventing/DomainEvent.cs b/src/SimpleCqrs/Eventing/DomainEvent.cs deleted file mode 100644 index 15100a1..0000000 --- a/src/SimpleCqrs/Eventing/DomainEvent.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace SimpleCqrs.Eventing -{ - [Serializable] - public class DomainEvent - { - public Guid AggregateRootId { get; set; } - public int Sequence { get; set; } - public DateTime EventDate { get; set; } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Eventing/DomainEventHandlerFactory.cs b/src/SimpleCqrs/Eventing/DomainEventHandlerFactory.cs deleted file mode 100644 index c815120..0000000 --- a/src/SimpleCqrs/Eventing/DomainEventHandlerFactory.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -namespace SimpleCqrs.Eventing -{ - public class DomainEventHandlerFactory : IDomainEventHandlerFactory - { - private readonly IServiceLocator serviceLocator; - - public DomainEventHandlerFactory(IServiceLocator serviceLocator) - { - this.serviceLocator = serviceLocator; - } - - public object Create(Type domainEventHandlerType) - { - return serviceLocator.Resolve(domainEventHandlerType); - } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Eventing/IEventBus.cs b/src/SimpleCqrs/Eventing/IEventBus.cs deleted file mode 100644 index 13888f6..0000000 --- a/src/SimpleCqrs/Eventing/IEventBus.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; - -namespace SimpleCqrs.Eventing -{ - public interface IEventBus - { - void PublishEvent(DomainEvent domainEvent); - void PublishEvents(IEnumerable domainEvents); - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Eventing/IEventStore.cs b/src/SimpleCqrs/Eventing/IEventStore.cs deleted file mode 100644 index abc7d3a..0000000 --- a/src/SimpleCqrs/Eventing/IEventStore.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace SimpleCqrs.Eventing -{ - public interface IEventStore - { - IEnumerable GetEvents(Guid aggregateRootId, int startSequence); - void Insert(IEnumerable domainEvents); - IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes); - IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes, Guid aggregateRootId); - IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes, DateTime startDate, DateTime endDate); - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Eventing/ISnapshotStore.cs b/src/SimpleCqrs/Eventing/ISnapshotStore.cs deleted file mode 100644 index 677c229..0000000 --- a/src/SimpleCqrs/Eventing/ISnapshotStore.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using SimpleCqrs.Domain; - -namespace SimpleCqrs.Eventing -{ - public interface ISnapshotStore - { - Snapshot GetSnapshot(Guid aggregateRootId); - void SaveSnapshot(TSnapshot snapshot) where TSnapshot : Snapshot; - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Eventing/LocalEventBus.cs b/src/SimpleCqrs/Eventing/LocalEventBus.cs deleted file mode 100644 index 569089d..0000000 --- a/src/SimpleCqrs/Eventing/LocalEventBus.cs +++ /dev/null @@ -1,88 +0,0 @@ - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace SimpleCqrs.Eventing -{ - public class LocalEventBus : IEventBus - { - private readonly IDomainEventHandlerFactory eventHandlerBuilder; - private IDictionary eventHandlerInvokers; - - public LocalEventBus(IEnumerable eventHandlerTypes, IDomainEventHandlerFactory eventHandlerBuilder) - { - this.eventHandlerBuilder = eventHandlerBuilder; - BuildEventInvokers(eventHandlerTypes); - } - - public void PublishEvent(DomainEvent domainEvent) - { - var domainEventType = domainEvent.GetType(); - var invokers = (from entry in eventHandlerInvokers - where entry.Key.IsAssignableFrom(domainEventType) - select entry.Value).ToList(); - - invokers.ForEach(i => i.Publish(domainEvent)); - } - - public void PublishEvents(IEnumerable domainEvents) - { - foreach(var domainEvent in domainEvents) - PublishEvent(domainEvent); - } - - private void BuildEventInvokers(IEnumerable eventHandlerTypes) - { - eventHandlerInvokers = new Dictionary(); - foreach(var eventHandlerType in eventHandlerTypes) - { - foreach(var domainEventType in GetDomainEventTypes(eventHandlerType)) - { - EventHandlerInvoker eventInvoker; - if(!eventHandlerInvokers.TryGetValue(domainEventType, out eventInvoker)) - eventInvoker = new EventHandlerInvoker(eventHandlerBuilder, domainEventType); - - eventInvoker.AddEventHandlerType(eventHandlerType); - eventHandlerInvokers[domainEventType] = eventInvoker; - } - } - } - - private static IEnumerable GetDomainEventTypes(Type eventHandlerType) - { - return from interfaceType in eventHandlerType.GetInterfaces() - where interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IHandleDomainEvents<>) - select interfaceType.GetGenericArguments()[0]; - } - - private class EventHandlerInvoker - { - private readonly IDomainEventHandlerFactory eventHandlerFactory; - private readonly Type domainEventType; - private readonly List eventHandlerTypes; - - public EventHandlerInvoker(IDomainEventHandlerFactory eventHandlerFactory, Type domainEventType) - { - this.eventHandlerFactory = eventHandlerFactory; - this.domainEventType = domainEventType; - eventHandlerTypes = new List(); - } - - public void AddEventHandlerType(Type eventHandlerType) - { - eventHandlerTypes.Add(eventHandlerType); - } - - public void Publish(DomainEvent domainEvent) - { - var handleMethod = typeof(IHandleDomainEvents<>).MakeGenericType(domainEventType).GetMethod("Handle"); - foreach(var eventHandlerType in eventHandlerTypes) - { - var eventHandler = eventHandlerFactory.Create(eventHandlerType); - handleMethod.Invoke(eventHandler, new object[] {domainEvent}); - } - } - } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Eventing/MemoryEventStore.cs b/src/SimpleCqrs/Eventing/MemoryEventStore.cs deleted file mode 100644 index bc7f506..0000000 --- a/src/SimpleCqrs/Eventing/MemoryEventStore.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace SimpleCqrs.Eventing -{ - public class MemoryEventStore : IEventStore - { - private readonly List storedDomainEvents = new List(); - - public IEnumerable GetEvents(Guid aggregateRootId, int startSequence) - { - return (from domainEvent in storedDomainEvents - where domainEvent.AggregateRootId == aggregateRootId - where domainEvent.Sequence > startSequence - select domainEvent).ToList(); - } - - public void Insert(IEnumerable domainEvents) - { - storedDomainEvents.AddRange(domainEvents); - } - - public IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes) - { - return (from domainEvent in storedDomainEvents - where domainEventTypes.Contains(domainEvent.GetType()) - select domainEvent); - } - - public IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes, Guid aggregateRootId) - { - return (from domainEvent in storedDomainEvents - where domainEvent.AggregateRootId == aggregateRootId - where domainEventTypes.Contains(domainEvent.GetType()) - select domainEvent); - } - - public IEnumerable GetEventsByEventTypes(IEnumerable domainEventTypes, DateTime startDate, DateTime endDate) - { - return (from domainEvent in storedDomainEvents - where domainEvent.EventDate >= startDate - where domainEvent.EventDate <= endDate - where domainEventTypes.Contains(domainEvent.GetType()) - select domainEvent); - } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Eventing/NullSnapshotStore.cs b/src/SimpleCqrs/Eventing/NullSnapshotStore.cs deleted file mode 100644 index ff90129..0000000 --- a/src/SimpleCqrs/Eventing/NullSnapshotStore.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using SimpleCqrs.Domain; - -namespace SimpleCqrs.Eventing -{ - public class NullSnapshotStore : ISnapshotStore - { - public Snapshot GetSnapshot(Guid aggregateRootId) - { - return null; - } - - public void SaveSnapshot(TSnapshot snapshot) where TSnapshot : Snapshot - { - } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/IHaveATestMode.cs b/src/SimpleCqrs/IHaveATestMode.cs deleted file mode 100644 index 7c8d247..0000000 --- a/src/SimpleCqrs/IHaveATestMode.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace SimpleCqrs -{ - public interface IHaveATestMode - { - bool IsInTestMode { get; set; } - } - - namespace Testing - { - public static class TestModeExtensionMethods - { - public static void TurnTestModeOn(this IHaveATestMode value) - { - value.IsInTestMode = true; - } - - public static void TurnTestModeOff(this IHaveATestMode value) - { - value.IsInTestMode = false; - } - } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/IRegisterComponents.cs b/src/SimpleCqrs/IRegisterComponents.cs deleted file mode 100644 index 7965469..0000000 --- a/src/SimpleCqrs/IRegisterComponents.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace SimpleCqrs -{ - public interface IRegisterComponents - { - void Register(IServiceLocator serviceLocator); - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/IServiceLocator.cs b/src/SimpleCqrs/IServiceLocator.cs deleted file mode 100644 index 833aa59..0000000 --- a/src/SimpleCqrs/IServiceLocator.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.Collections.Generic; - -#region License - -// -// Author: Javier Lozano -// Copyright (c) 2009-2010, lozanotek, inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#endregion - -namespace SimpleCqrs -{ - public interface IServiceLocator : IDisposable - { - T Resolve() where T : class; - T Resolve(string key) where T : class; - object Resolve(Type type); - IList ResolveServices() where T : class; - void Register(Type implType) where TInterface : class; - void Register() where TImplementation : class, TInterface; - void Register(string key) where TImplementation : class, TInterface; - void Register(string key, Type type); - void Register(Type serviceType, Type implType); - void Register(TInterface instance) where TInterface : class; - void Release(object instance); - void Reset(); - TService Inject(TService instance) where TService : class; - void TearDown(TService instance) where TService : class; - void Register(Func factoryMethod) where TInterface : class; - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/ISimpleCqrsRuntime.cs b/src/SimpleCqrs/ISimpleCqrsRuntime.cs deleted file mode 100644 index 87373a3..0000000 --- a/src/SimpleCqrs/ISimpleCqrsRuntime.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace SimpleCqrs -{ - /// - /// Defines a runtime environment for a SimpleCqrs applications. - /// - public interface ISimpleCqrsRuntime : IDisposable - { - /// - /// Gets the service locator associated with the runtime. - /// - IServiceLocator ServiceLocator { get; } - - /// - /// Starts the runtime environment. - /// - void Start(); - - /// - /// Shutdowns the runtime environment and release all the resouces held by the runtime environment. - /// - void Shutdown(); - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/ITypeCatalog.cs b/src/SimpleCqrs/ITypeCatalog.cs deleted file mode 100644 index 86d2e57..0000000 --- a/src/SimpleCqrs/ITypeCatalog.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace SimpleCqrs -{ - public interface ITypeCatalog - { - Type[] LoadedTypes { get; } - Type[] GetDerivedTypes(Type type); - Type[] GetDerivedTypes(); - Type[] GetGenericInterfaceImplementations(Type type); - Type[] GetInterfaceImplementations(Type type); - Type[] GetInterfaceImplementations(); - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/Properties/AssemblyInfo.cs b/src/SimpleCqrs/Properties/AssemblyInfo.cs deleted file mode 100644 index f4e3253..0000000 --- a/src/SimpleCqrs/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("SimpleCqrs")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SimpleCqrs")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] -[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("6c3705f8-5d9f-4217-b049-40c1252a20c1")] - -// 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/src/SimpleCqrs/ServiceLocator.cs b/src/SimpleCqrs/ServiceLocator.cs deleted file mode 100644 index 6f5062e..0000000 --- a/src/SimpleCqrs/ServiceLocator.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace SimpleCqrs -{ - public static class ServiceLocator - { - public static IServiceLocator Current { get; private set; } - - public static void SetCurrent(IServiceLocator serviceLocator) - { - Current = serviceLocator; - } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/ServiceResolutionException.cs b/src/SimpleCqrs/ServiceResolutionException.cs deleted file mode 100644 index fc26821..0000000 --- a/src/SimpleCqrs/ServiceResolutionException.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Runtime.Serialization; - -#region License - -// -// Author: Javier Lozano -// Copyright (c) 2009-2010, lozanotek, inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#endregion - -namespace SimpleCqrs -{ - [Serializable] - public class ServiceResolutionException : Exception - { - public ServiceResolutionException(Type service) : - base(string.Format("Could not resolve serviceType '{0}'", service)) - { - ServiceType = service; - } - - public ServiceResolutionException(Type service, Exception innerException) - : base(string.Format("Could not resolve serviceType '{0}'", service), innerException) - { - ServiceType = service; - } - - public ServiceResolutionException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - - public Type ServiceType { get; set; } - } -} \ No newline at end of file diff --git a/src/SimpleCqrs/SimpleCqrs.csproj b/src/SimpleCqrs/SimpleCqrs.csproj deleted file mode 100644 index 5561ec6..0000000 --- a/src/SimpleCqrs/SimpleCqrs.csproj +++ /dev/null @@ -1,107 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {E04C12B5-A6D3-4D64-9F38-896BEE68162E} - Library - Properties - SimpleCqrs - SimpleCqrs - v4.0 - 512 - - - - true - full - false - ..\..\binaries\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - Code - - - Code - - - - - - - Code - - - Code - - - Code - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/SimpleCqrs/SimpleCqrsRuntime.cs b/src/SimpleCqrs/SimpleCqrsRuntime.cs deleted file mode 100644 index 214d293..0000000 --- a/src/SimpleCqrs/SimpleCqrsRuntime.cs +++ /dev/null @@ -1,187 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using SimpleCqrs.Commanding; -using SimpleCqrs.Domain; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs -{ - /// - /// Represents the runtime environment for a SimpleCqrs applications. - /// - /// The type of the service locator. - public class SimpleCqrsRuntime : ISimpleCqrsRuntime - where TServiceLocator : class, IServiceLocator - { - /// - /// Gets the service locator associated with the runtime. - /// - public TServiceLocator ServiceLocator - { - get { return (TServiceLocator)SimpleCqrs.ServiceLocator.Current; } - } - - /// - /// Gets the service locator associated with the runtime. - /// - IServiceLocator ISimpleCqrsRuntime.ServiceLocator - { - get { return ServiceLocator; } - } - - /// - /// Starts the runtime environment. - /// - public void Start() - { - var serviceLocator = GetServiceLocator(); - - serviceLocator.Register(() => serviceLocator); - serviceLocator.Register(GetTypeCatalog(serviceLocator)); - serviceLocator.Register(GetCommandBus(serviceLocator)); - serviceLocator.Register(GetEventBus(serviceLocator)); - serviceLocator.Register(GetSnapshotStore(serviceLocator)); - serviceLocator.Register(GetEventStore(serviceLocator)); - serviceLocator.Register(); - RegisterComponents(serviceLocator); - - SimpleCqrs.ServiceLocator.SetCurrent(serviceLocator); - - OnStarted(serviceLocator); - } - - /// - /// Called after the runtime has be started. - /// - /// The current . - protected virtual void OnStarted(TServiceLocator serviceLocator) - { - } - - /// - /// Called when the runtime is to shutdown. - /// - /// The current . - protected virtual void OnShutdown(TServiceLocator serviceLocator) - { - } - - /// - /// Shutdowns the runtime environment and release all the resouces held by the runtime environment. - /// - public void Shutdown() - { - OnShutdown(ServiceLocator); - ServiceLocator.Dispose(); - } - - /// - /// When overriden this method returns the that will be used by the runtime. - /// The default implementation returns an instance of . - /// - /// The current . - /// An instance of . - protected virtual ICommandBus GetCommandBus(IServiceLocator serviceLocator) - { - return new LocalCommandBus(serviceLocator.Resolve(), serviceLocator); - } - - /// - /// When overriden this method returns the that will be used by the runtime. - /// The default implementation returns an instance of . - /// - /// The current . - /// An instance of . - protected virtual IEventBus GetEventBus(IServiceLocator serviceLocator) - { - var typeCatalog = serviceLocator.Resolve(); - var domainEventHandlerFactory = serviceLocator.Resolve(); - var domainEventTypes = typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleDomainEvents<>)); - - return new LocalEventBus(domainEventTypes, domainEventHandlerFactory); - } - - /// - /// When overriden this method returns the assemblies that will be scanned for types used by the runtime. - /// The default implementation returns the assemblies returned from . - /// - /// The current . - /// An containing the assemblies to scan. - protected virtual IEnumerable GetAssembliesToScan(IServiceLocator serviceLocator) - { - return AppDomain.CurrentDomain.GetAssemblies(); - } - - /// - /// When overriden this method returns the that will be used by the runtime. - /// The default implementation returns an instance of . - /// - /// The current . - /// An instance of . - protected virtual ITypeCatalog GetTypeCatalog(IServiceLocator serviceLocator) - { - return new AssemblyTypeCatalog(GetAssembliesToScan(serviceLocator)); - } - - /// - /// When overriden this method returns the that will be used by the runtime. - /// The default implementation returns an instance of . - /// - /// The current . - /// An instance of . - protected virtual ISnapshotStore GetSnapshotStore(IServiceLocator serviceLocator) - { - return new NullSnapshotStore(); - } - - /// - /// When overriden this method returns the that will be used by the runtime. - /// The default implementation returns an instance of . - /// - /// The current . - /// An instance of . - protected virtual IEventStore GetEventStore(IServiceLocator serviceLocator) - { - return new MemoryEventStore(); - } - - /// - /// When overriden this method returns the that will be used by the runtime. - /// The default implementation returns an instance of . - /// - /// An instance of . - protected virtual TServiceLocator GetServiceLocator() - { - return Activator.CreateInstance(); - } - - protected virtual IEnumerable GetComponentRegistrars(Type componentRegistarType, IServiceLocator serviceLocator) - { - var typeCatalog = serviceLocator.Resolve(); - var componentRegistrarTypes = componentRegistarType.IsInterface ? - typeCatalog.GetInterfaceImplementations(componentRegistarType) : - typeCatalog.GetDerivedTypes(componentRegistarType); - - return componentRegistrarTypes - .Select(serviceLocator.Resolve) - .Cast(); - } - - protected virtual void RegisterComponents(IServiceLocator serviceLocator) - { - var componentRegistrars = GetComponentRegistrars(typeof(IRegisterComponents), serviceLocator).ToList(); - componentRegistrars.ForEach(componentRegistrar => componentRegistrar.Register(serviceLocator)); - } - - /// - /// Shutdowns the runtime and disposes of the resources in the service locator. - /// - /// This calls Shutdown. - public void Dispose() - { - Shutdown(); - } - } -} \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/CreateEventStore.feature b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/CreateEventStore.feature deleted file mode 100644 index 7267a8b..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/CreateEventStore.feature +++ /dev/null @@ -1,38 +0,0 @@ -Feature: Create event store - In order to insert and retrieve events from the event store - As a Simple CQRS developer - I want the event store to be created if it does not exist - -Background: - Given the connection string to my database is - """ - Data Source=.\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;MultipleActiveResultSets=True; - """ - -Scenario: The event store does not exist before inserting - Given the EventStore table does not exist - And I have a SomethingHappenedEvent to be added to the store with the following values - | Field | Value | - | EventDate | 3/20/2010 3:01:04 AM | - | AggregateRootId | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | - | Sequence | 2 | - | ThisHappened | something | - And that event will serialize to 'Serialized Object' - When I add the domain events to the store - Then I should have the following events in the database - | EventDate | - | 3/20/2010 3:01:04 AM | - -Scenario: The event store does not exist before retrieving events by aggregate root - Given the EventStore table does not exist - When I retrieve the domain events for '8312E92C-DF1C-4970-A9D5-6414120C3CF7' - Then I should get back the following DomainEvents - | Sequence | - -Scenario: The event store does not exist before retrieving events by event type - Given the EventStore table does not exist - When I retrieve the domain events for the following types - | Type | - | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null | - Then I should get back the following DomainEvents - | Sequence | \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/CreateEventStore.feature.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/CreateEventStore.feature.cs deleted file mode 100644 index 6caf76f..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/CreateEventStore.feature.cs +++ /dev/null @@ -1,157 +0,0 @@ -// ------------------------------------------------------------------------------ -// -// This code was generated by SpecFlow (http://www.specflow.org/). -// SpecFlow Version:1.5.0.0 -// Runtime Version:4.0.30319.1 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -// ------------------------------------------------------------------------------ -#region Designer generated code -namespace SimpleCqrs.EventStore.SqlServer.Tests.Features -{ - using TechTalk.SpecFlow; - - - [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.5.0.0")] - [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [NUnit.Framework.TestFixtureAttribute()] - [NUnit.Framework.DescriptionAttribute("Create event store")] - public partial class CreateEventStoreFeature - { - - private static TechTalk.SpecFlow.ITestRunner testRunner; - -#line 1 "CreateEventStore.feature" -#line hidden - - [NUnit.Framework.TestFixtureSetUpAttribute()] - public virtual void FeatureSetup() - { - testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); - TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Create event store", "In order to insert and retrieve events from the event store\nAs a Simple CQRS deve" + - "loper\nI want the event store to be created if it does not exist", GenerationTargetLanguage.CSharp, ((string[])(null))); - testRunner.OnFeatureStart(featureInfo); - } - - [NUnit.Framework.TestFixtureTearDownAttribute()] - public virtual void FeatureTearDown() - { - testRunner.OnFeatureEnd(); - testRunner = null; - } - - public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) - { - testRunner.OnScenarioStart(scenarioInfo); - this.FeatureBackground(); - } - - [NUnit.Framework.TearDownAttribute()] - public virtual void ScenarioTearDown() - { - testRunner.OnScenarioEnd(); - } - - public virtual void FeatureBackground() - { -#line 6 -#line hidden -#line 7 - testRunner.Given("the connection string to my database is", "Data Source=.\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;MultipleAc" + - "tiveResultSets=True;", ((TechTalk.SpecFlow.Table)(null))); -#line hidden - } - - [NUnit.Framework.TestAttribute()] - [NUnit.Framework.DescriptionAttribute("The event store does not exist before inserting")] - public virtual void TheEventStoreDoesNotExistBeforeInserting() - { - TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("The event store does not exist before inserting", ((string[])(null))); -#line 12 -this.ScenarioSetup(scenarioInfo); -#line 13 - testRunner.Given("the EventStore table does not exist"); -#line hidden - TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table1.AddRow(new string[] { - "EventDate", - "3/20/2010 3:01:04 AM"}); - table1.AddRow(new string[] { - "AggregateRootId", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7"}); - table1.AddRow(new string[] { - "Sequence", - "2"}); - table1.AddRow(new string[] { - "ThisHappened", - "something"}); -#line 14 - testRunner.And("I have a SomethingHappenedEvent to be added to the store with the following value" + - "s", ((string)(null)), table1); -#line 20 - testRunner.And("that event will serialize to \'Serialized Object\'"); -#line 21 - testRunner.When("I add the domain events to the store"); -#line hidden - TechTalk.SpecFlow.Table table2 = new TechTalk.SpecFlow.Table(new string[] { - "EventDate"}); - table2.AddRow(new string[] { - "3/20/2010 3:01:04 AM"}); -#line 22 - testRunner.Then("I should have the following events in the database", ((string)(null)), table2); -#line hidden - testRunner.CollectScenarioErrors(); - } - - [NUnit.Framework.TestAttribute()] - [NUnit.Framework.DescriptionAttribute("The event store does not exist before retrieving events by aggregate root")] - public virtual void TheEventStoreDoesNotExistBeforeRetrievingEventsByAggregateRoot() - { - TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("The event store does not exist before retrieving events by aggregate root", ((string[])(null))); -#line 26 -this.ScenarioSetup(scenarioInfo); -#line 27 - testRunner.Given("the EventStore table does not exist"); -#line 28 - testRunner.When("I retrieve the domain events for \'8312E92C-DF1C-4970-A9D5-6414120C3CF7\'"); -#line hidden - TechTalk.SpecFlow.Table table3 = new TechTalk.SpecFlow.Table(new string[] { - "Sequence"}); -#line 29 - testRunner.Then("I should get back the following DomainEvents", ((string)(null)), table3); -#line hidden - testRunner.CollectScenarioErrors(); - } - - [NUnit.Framework.TestAttribute()] - [NUnit.Framework.DescriptionAttribute("The event store does not exist before retrieving events by event type")] - public virtual void TheEventStoreDoesNotExistBeforeRetrievingEventsByEventType() - { - TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("The event store does not exist before retrieving events by event type", ((string[])(null))); -#line 32 -this.ScenarioSetup(scenarioInfo); -#line 33 - testRunner.Given("the EventStore table does not exist"); -#line hidden - TechTalk.SpecFlow.Table table4 = new TechTalk.SpecFlow.Table(new string[] { - "Type"}); - table4.AddRow(new string[] { - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"}); -#line 34 - testRunner.When("I retrieve the domain events for the following types", ((string)(null)), table4); -#line hidden - TechTalk.SpecFlow.Table table5 = new TechTalk.SpecFlow.Table(new string[] { - "Sequence"}); -#line 37 - testRunner.Then("I should get back the following DomainEvents", ((string)(null)), table5); -#line hidden - testRunner.CollectScenarioErrors(); - } - } -} -#endregion diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/GetEvents.feature b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/GetEvents.feature deleted file mode 100644 index 666fd45..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/GetEvents.feature +++ /dev/null @@ -1,93 +0,0 @@ -Feature: Get Events - In order to retrieve events from my SQL Server event store - As a Simple CQRS developer - I want to pass a request to retrieve events and get the appropriate events back - -Background: - Given the connection string to my database is - """ - Data Source=.\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;MultipleActiveResultSets=True; - """ - -Scenario: Get Events by aggregate root id - Given I have the following events in the database - | EventDate | Data | Sequence | AggregateRootId | EventType | - | 3/20/2010 3:01:04 AM | Serialized Object | 1 | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - | 3/20/2010 4:01:04 AM | Serialized Objecta | 2 | D50E4D4F-0893-45B2-92F8-897514812A91 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - | 3/20/2010 5:01:04 AM | Serialized Object2 | 3 | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - And deserializing 'Serialized Object' will return a SomethingHappenedEvent with the following data - | Field | Value | - | Sequence | 97 | - And deserializing 'Serialized Object2' will return a SomethingElseHappenedEvent with the following data - | Field | Value | - | Sequence | 98 | - When I retrieve the domain events for '8312E92C-DF1C-4970-A9D5-6414120C3CF7' - Then I should get back the following DomainEvents - | Sequence | - | 97 | - | 98 | - -Scenario: Get Events by sequence - Given I have the following events in the database - | EventDate | Data | Sequence | AggregateRootId | EventType | - | 3/20/2010 3:01:04 AM | Serialized Object | 1 | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - | 3/20/2010 4:01:04 AM | Serialized Objecta | 2 | D50E4D4F-0893-45B2-92F8-897514812A91 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - | 3/20/2010 5:01:04 AM | Serialized Object2 | 3 | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - And deserializing 'Serialized Object' will return a SomethingHappenedEvent with the following data - | Field | Value | - | Sequence | 97 | - And deserializing 'Serialized Object2' will return a SomethingElseHappenedEvent with the following data - | Field | Value | - | Sequence | 98 | - When I retrieve the domain events for '8312E92C-DF1C-4970-A9D5-6414120C3CF7' and sequence 2 - Then I should get back the following DomainEvents - | Sequence | - | 98 | - -Scenario: Get events with one event type - Given I have the following events in the database - | EventDate | Data | Sequence | AggregateRootId | EventType | - | 3/20/2010 3:01:04 AM | Serialized Object | 1 | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - | 3/20/2010 4:01:04 AM | Serialized Object2 | 2 | D50E4D4F-0893-45B2-92F8-897514812A91 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - | 3/20/2010 5:01:04 AM | Serialized Object3 | 3 | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - And deserializing 'Serialized Object' will return a SomethingHappenedEvent with the following data - | Field | Value | - | Sequence | 97 | - And deserializing 'Serialized Object2' will return a SomethingHappenedEvent with the following data - | Field | Value | - | Sequence | 98 | - And deserializing 'Serialized Object3' will return a SomethingElseHappenedEvent with the following data - | Field | Value | - | Sequence | 99 | - When I retrieve the domain events for the following types - | Type | - | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - Then I should get back the following DomainEvents - | Sequence | - | 97 | - | 98 | - -Scenario: Get events with two event types - Given I have the following events in the database - | EventDate | Data | Sequence | AggregateRootId | EventType | - | 3/20/2010 3:01:04 AM | Serialized Object | 1 | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - | 3/20/2010 4:01:04 AM | Serialized Object2 | 2 | D50E4D4F-0893-45B2-92F8-897514812A91 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - | 3/20/2010 5:01:04 AM | Serialized Object3 | 3 | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - And deserializing 'Serialized Object' will return a SomethingHappenedEvent with the following data - | Field | Value | - | Sequence | 97 | - And deserializing 'Serialized Object2' will return a SomethingHappenedEvent with the following data - | Field | Value | - | Sequence | 98 | - And deserializing 'Serialized Object3' will return a SomethingElseHappenedEvent with the following data - | Field | Value | - | Sequence | 99 | - When I retrieve the domain events for the following types - | Type | - | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - | SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - Then I should get back the following DomainEvents - | Sequence | - | 97 | - | 98 | - | 99 | \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/GetEvents.feature.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/GetEvents.feature.cs deleted file mode 100644 index 49cdf02..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/GetEvents.feature.cs +++ /dev/null @@ -1,393 +0,0 @@ -// ------------------------------------------------------------------------------ -// -// This code was generated by SpecFlow (http://www.specflow.org/). -// SpecFlow Version:1.5.0.0 -// Runtime Version:4.0.30319.1 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -// ------------------------------------------------------------------------------ -#region Designer generated code -namespace SimpleCqrs.EventStore.SqlServer.Tests.Features -{ - using TechTalk.SpecFlow; - - - [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.5.0.0")] - [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [NUnit.Framework.TestFixtureAttribute()] - [NUnit.Framework.DescriptionAttribute("Get Events")] - public partial class GetEventsFeature - { - - private static TechTalk.SpecFlow.ITestRunner testRunner; - -#line 1 "GetEvents.feature" -#line hidden - - [NUnit.Framework.TestFixtureSetUpAttribute()] - public virtual void FeatureSetup() - { - testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); - TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Get Events", "In order to retrieve events from my SQL Server event store\nAs a Simple CQRS devel" + - "oper\nI want to pass a request to retrieve events and get the appropriate events " + - "back", GenerationTargetLanguage.CSharp, ((string[])(null))); - testRunner.OnFeatureStart(featureInfo); - } - - [NUnit.Framework.TestFixtureTearDownAttribute()] - public virtual void FeatureTearDown() - { - testRunner.OnFeatureEnd(); - testRunner = null; - } - - public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) - { - testRunner.OnScenarioStart(scenarioInfo); - this.FeatureBackground(); - } - - [NUnit.Framework.TearDownAttribute()] - public virtual void ScenarioTearDown() - { - testRunner.OnScenarioEnd(); - } - - public virtual void FeatureBackground() - { -#line 6 -#line hidden -#line 7 - testRunner.Given("the connection string to my database is", "Data Source=.\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;MultipleAc" + - "tiveResultSets=True;", ((TechTalk.SpecFlow.Table)(null))); -#line hidden - } - - [NUnit.Framework.TestAttribute()] - [NUnit.Framework.DescriptionAttribute("Get Events by aggregate root id")] - public virtual void GetEventsByAggregateRootId() - { - TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Get Events by aggregate root id", ((string[])(null))); -#line 12 -this.ScenarioSetup(scenarioInfo); -#line hidden - TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] { - "EventDate", - "Data", - "Sequence", - "AggregateRootId", - "EventType"}); - table1.AddRow(new string[] { - "3/20/2010 3:01:04 AM", - "Serialized Object", - "1", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests"}); - table1.AddRow(new string[] { - "3/20/2010 4:01:04 AM", - "Serialized Objecta", - "2", - "D50E4D4F-0893-45B2-92F8-897514812A91", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests"}); - table1.AddRow(new string[] { - "3/20/2010 5:01:04 AM", - "Serialized Object2", - "3", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.Even" + - "tStore.SqlServer.Tests"}); -#line 13 - testRunner.Given("I have the following events in the database", ((string)(null)), table1); -#line hidden - TechTalk.SpecFlow.Table table2 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table2.AddRow(new string[] { - "Sequence", - "97"}); -#line 18 - testRunner.And("deserializing \'Serialized Object\' will return a SomethingHappenedEvent with the f" + - "ollowing data", ((string)(null)), table2); -#line hidden - TechTalk.SpecFlow.Table table3 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table3.AddRow(new string[] { - "Sequence", - "98"}); -#line 21 - testRunner.And("deserializing \'Serialized Object2\' will return a SomethingElseHappenedEvent with " + - "the following data", ((string)(null)), table3); -#line 24 - testRunner.When("I retrieve the domain events for \'8312E92C-DF1C-4970-A9D5-6414120C3CF7\'"); -#line hidden - TechTalk.SpecFlow.Table table4 = new TechTalk.SpecFlow.Table(new string[] { - "Sequence"}); - table4.AddRow(new string[] { - "97"}); - table4.AddRow(new string[] { - "98"}); -#line 25 - testRunner.Then("I should get back the following DomainEvents", ((string)(null)), table4); -#line hidden - testRunner.CollectScenarioErrors(); - } - - [NUnit.Framework.TestAttribute()] - [NUnit.Framework.DescriptionAttribute("Get Events by sequence")] - public virtual void GetEventsBySequence() - { - TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Get Events by sequence", ((string[])(null))); -#line 30 -this.ScenarioSetup(scenarioInfo); -#line hidden - TechTalk.SpecFlow.Table table5 = new TechTalk.SpecFlow.Table(new string[] { - "EventDate", - "Data", - "Sequence", - "AggregateRootId", - "EventType"}); - table5.AddRow(new string[] { - "3/20/2010 3:01:04 AM", - "Serialized Object", - "1", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests"}); - table5.AddRow(new string[] { - "3/20/2010 4:01:04 AM", - "Serialized Objecta", - "2", - "D50E4D4F-0893-45B2-92F8-897514812A91", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests"}); - table5.AddRow(new string[] { - "3/20/2010 5:01:04 AM", - "Serialized Object2", - "3", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.Even" + - "tStore.SqlServer.Tests"}); -#line 31 - testRunner.Given("I have the following events in the database", ((string)(null)), table5); -#line hidden - TechTalk.SpecFlow.Table table6 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table6.AddRow(new string[] { - "Sequence", - "97"}); -#line 36 - testRunner.And("deserializing \'Serialized Object\' will return a SomethingHappenedEvent with the f" + - "ollowing data", ((string)(null)), table6); -#line hidden - TechTalk.SpecFlow.Table table7 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table7.AddRow(new string[] { - "Sequence", - "98"}); -#line 39 - testRunner.And("deserializing \'Serialized Object2\' will return a SomethingElseHappenedEvent with " + - "the following data", ((string)(null)), table7); -#line 42 - testRunner.When("I retrieve the domain events for \'8312E92C-DF1C-4970-A9D5-6414120C3CF7\' and seque" + - "nce 2"); -#line hidden - TechTalk.SpecFlow.Table table8 = new TechTalk.SpecFlow.Table(new string[] { - "Sequence"}); - table8.AddRow(new string[] { - "98"}); -#line 43 - testRunner.Then("I should get back the following DomainEvents", ((string)(null)), table8); -#line hidden - testRunner.CollectScenarioErrors(); - } - - [NUnit.Framework.TestAttribute()] - [NUnit.Framework.DescriptionAttribute("Get events with one event type")] - public virtual void GetEventsWithOneEventType() - { - TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Get events with one event type", ((string[])(null))); -#line 47 -this.ScenarioSetup(scenarioInfo); -#line hidden - TechTalk.SpecFlow.Table table9 = new TechTalk.SpecFlow.Table(new string[] { - "EventDate", - "Data", - "Sequence", - "AggregateRootId", - "EventType"}); - table9.AddRow(new string[] { - "3/20/2010 3:01:04 AM", - "Serialized Object", - "1", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests"}); - table9.AddRow(new string[] { - "3/20/2010 4:01:04 AM", - "Serialized Object2", - "2", - "D50E4D4F-0893-45B2-92F8-897514812A91", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests"}); - table9.AddRow(new string[] { - "3/20/2010 5:01:04 AM", - "Serialized Object3", - "3", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.Even" + - "tStore.SqlServer.Tests"}); -#line 48 - testRunner.Given("I have the following events in the database", ((string)(null)), table9); -#line hidden - TechTalk.SpecFlow.Table table10 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table10.AddRow(new string[] { - "Sequence", - "97"}); -#line 53 - testRunner.And("deserializing \'Serialized Object\' will return a SomethingHappenedEvent with the f" + - "ollowing data", ((string)(null)), table10); -#line hidden - TechTalk.SpecFlow.Table table11 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table11.AddRow(new string[] { - "Sequence", - "98"}); -#line 56 - testRunner.And("deserializing \'Serialized Object2\' will return a SomethingHappenedEvent with the " + - "following data", ((string)(null)), table11); -#line hidden - TechTalk.SpecFlow.Table table12 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table12.AddRow(new string[] { - "Sequence", - "99"}); -#line 59 - testRunner.And("deserializing \'Serialized Object3\' will return a SomethingElseHappenedEvent with " + - "the following data", ((string)(null)), table12); -#line hidden - TechTalk.SpecFlow.Table table13 = new TechTalk.SpecFlow.Table(new string[] { - "Type"}); - table13.AddRow(new string[] { - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests"}); -#line 62 - testRunner.When("I retrieve the domain events for the following types", ((string)(null)), table13); -#line hidden - TechTalk.SpecFlow.Table table14 = new TechTalk.SpecFlow.Table(new string[] { - "Sequence"}); - table14.AddRow(new string[] { - "97"}); - table14.AddRow(new string[] { - "98"}); -#line 65 - testRunner.Then("I should get back the following DomainEvents", ((string)(null)), table14); -#line hidden - testRunner.CollectScenarioErrors(); - } - - [NUnit.Framework.TestAttribute()] - [NUnit.Framework.DescriptionAttribute("Get events with two event types")] - public virtual void GetEventsWithTwoEventTypes() - { - TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Get events with two event types", ((string[])(null))); -#line 70 -this.ScenarioSetup(scenarioInfo); -#line hidden - TechTalk.SpecFlow.Table table15 = new TechTalk.SpecFlow.Table(new string[] { - "EventDate", - "Data", - "Sequence", - "AggregateRootId", - "EventType"}); - table15.AddRow(new string[] { - "3/20/2010 3:01:04 AM", - "Serialized Object", - "1", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests"}); - table15.AddRow(new string[] { - "3/20/2010 4:01:04 AM", - "Serialized Object2", - "2", - "D50E4D4F-0893-45B2-92F8-897514812A91", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests"}); - table15.AddRow(new string[] { - "3/20/2010 5:01:04 AM", - "Serialized Object3", - "3", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.Even" + - "tStore.SqlServer.Tests"}); -#line 71 - testRunner.Given("I have the following events in the database", ((string)(null)), table15); -#line hidden - TechTalk.SpecFlow.Table table16 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table16.AddRow(new string[] { - "Sequence", - "97"}); -#line 76 - testRunner.And("deserializing \'Serialized Object\' will return a SomethingHappenedEvent with the f" + - "ollowing data", ((string)(null)), table16); -#line hidden - TechTalk.SpecFlow.Table table17 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table17.AddRow(new string[] { - "Sequence", - "98"}); -#line 79 - testRunner.And("deserializing \'Serialized Object2\' will return a SomethingHappenedEvent with the " + - "following data", ((string)(null)), table17); -#line hidden - TechTalk.SpecFlow.Table table18 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table18.AddRow(new string[] { - "Sequence", - "99"}); -#line 82 - testRunner.And("deserializing \'Serialized Object3\' will return a SomethingElseHappenedEvent with " + - "the following data", ((string)(null)), table18); -#line hidden - TechTalk.SpecFlow.Table table19 = new TechTalk.SpecFlow.Table(new string[] { - "Type"}); - table19.AddRow(new string[] { - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests"}); - table19.AddRow(new string[] { - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.Even" + - "tStore.SqlServer.Tests"}); -#line 85 - testRunner.When("I retrieve the domain events for the following types", ((string)(null)), table19); -#line hidden - TechTalk.SpecFlow.Table table20 = new TechTalk.SpecFlow.Table(new string[] { - "Sequence"}); - table20.AddRow(new string[] { - "97"}); - table20.AddRow(new string[] { - "98"}); - table20.AddRow(new string[] { - "99"}); -#line 89 - testRunner.Then("I should get back the following DomainEvents", ((string)(null)), table20); -#line hidden - testRunner.CollectScenarioErrors(); - } - } -} -#endregion diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/InsertEvents.feature b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/InsertEvents.feature deleted file mode 100644 index 75a5f6e..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/InsertEvents.feature +++ /dev/null @@ -1,57 +0,0 @@ -Feature: Insert events - In order to add events to my SQL Server event store - As a Simple CQRS developer - I want to pass an array of events and have them added to the appropriate table - -Background: - Given the connection string to my database is - """ - Data Source=.\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;MultipleActiveResultSets=True; - """ - -Scenario: Insert one domain event - Given I have a SomethingHappenedEvent to be added to the store with the following values - | Field | Value | - | EventDate | 3/20/2010 3:01:04 AM | - | AggregateRootId | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | - | Sequence | 2 | - | ThisHappened | something | - And that event will serialize to 'Serialized Object' - When I add the domain events to the store - Then I should have the following events in the database - | EventDate | Data | Sequence | AggregateRootId | EventType | - | 3/20/2010 3:01:04 AM | Serialized Object | 2 | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - -Scenario: Insert two domain events - Given I have a SomethingHappenedEvent to be added to the store with the following values - | Field | Value | - | EventDate | 3/20/2010 3:01:04 AM | - | AggregateRootId | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | - | Sequence | 2 | - | ThisHappened | something | - And that event will serialize to 'The First Record' - And I have a SomethingElseHappenedEvent to be added to the store with the following values - | Field | Value | - | EventDate | 4/24/2010 3:01:04 AM | - | AggregateRootId | C3579C12-C29B-4F65-8D83-B79AC5C85718 | - | Sequence | 4 | - | SomeDataToStore | Testing | - And that event will serialize to 'The Second Record' - When I add the domain events to the store - Then I should have the following events in the database - | EventDate | Data | Sequence | AggregateRootId | EventType | - | 3/20/2010 3:01:04 AM | The First Record | 2 | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - | 4/24/2010 3:01:04 AM | The Second Record | 4 | C3579C12-C29B-4F65-8D83-B79AC5C85718 | SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.EventStore.SqlServer.Tests | - -Scenario: Inserting and retrieving an event - Given I have a SomethingHappenedEvent to be added to the store with the following values - | Field | Value | - | EventDate | 3/20/2010 3:01:04 AM | - | AggregateRootId | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | - | Sequence | 2 | - | ThisHappened | something | - And I am choosing to use the Json Serializer - When I add the domain events to the store - Then I should get back the following SomethingHappenedEvents - | EventDate | AggregateRootId | Sequence | ThisHappened | - | 3/20/2010 3:01:04 AM | 8312E92C-DF1C-4970-A9D5-6414120C3CF7 | 2 | something | diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/InsertEvents.feature.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/InsertEvents.feature.cs deleted file mode 100644 index acd5126..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/InsertEvents.feature.cs +++ /dev/null @@ -1,244 +0,0 @@ -// ------------------------------------------------------------------------------ -// -// This code was generated by SpecFlow (http://www.specflow.org/). -// SpecFlow Version:1.6.0.0 -// SpecFlow Generator Version:1.6.0.0 -// Runtime Version:4.0.30319.1 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -// ------------------------------------------------------------------------------ -#region Designer generated code -namespace SimpleCqrs.EventStore.SqlServer.Tests.Features -{ - using TechTalk.SpecFlow; - - - [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.6.0.0")] - [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [NUnit.Framework.TestFixtureAttribute()] - [NUnit.Framework.DescriptionAttribute("Insert events")] - public partial class InsertEventsFeature - { - - private static TechTalk.SpecFlow.ITestRunner testRunner; - -#line 1 "InsertEvents.feature" -#line hidden - - [NUnit.Framework.TestFixtureSetUpAttribute()] - public virtual void FeatureSetup() - { - testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); - TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Insert events", "In order to add events to my SQL Server event store\nAs a Simple CQRS developer\nI " + - "want to pass an array of events and have them added to the appropriate table", GenerationTargetLanguage.CSharp, ((string[])(null))); - testRunner.OnFeatureStart(featureInfo); - } - - [NUnit.Framework.TestFixtureTearDownAttribute()] - public virtual void FeatureTearDown() - { - testRunner.OnFeatureEnd(); - testRunner = null; - } - - public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) - { - testRunner.OnScenarioStart(scenarioInfo); - this.FeatureBackground(); - } - - [NUnit.Framework.TearDownAttribute()] - public virtual void ScenarioTearDown() - { - testRunner.OnScenarioEnd(); - } - - public virtual void FeatureBackground() - { -#line 6 -#line hidden -#line 7 - testRunner.Given("the connection string to my database is", "Data Source=.\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;MultipleAc" + - "tiveResultSets=True;", ((TechTalk.SpecFlow.Table)(null))); -#line hidden - } - - [NUnit.Framework.TestAttribute()] - [NUnit.Framework.DescriptionAttribute("Insert one domain event")] - public virtual void InsertOneDomainEvent() - { - TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Insert one domain event", ((string[])(null))); -#line 12 -this.ScenarioSetup(scenarioInfo); -#line hidden - TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table1.AddRow(new string[] { - "EventDate", - "3/20/2010 3:01:04 AM"}); - table1.AddRow(new string[] { - "AggregateRootId", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7"}); - table1.AddRow(new string[] { - "Sequence", - "2"}); - table1.AddRow(new string[] { - "ThisHappened", - "something"}); -#line 13 - testRunner.Given("I have a SomethingHappenedEvent to be added to the store with the following value" + - "s", ((string)(null)), table1); -#line 19 - testRunner.And("that event will serialize to \'Serialized Object\'"); -#line 20 - testRunner.When("I add the domain events to the store"); -#line hidden - TechTalk.SpecFlow.Table table2 = new TechTalk.SpecFlow.Table(new string[] { - "EventDate", - "Data", - "Sequence", - "AggregateRootId", - "EventType"}); - table2.AddRow(new string[] { - "3/20/2010 3:01:04 AM", - "Serialized Object", - "2", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests"}); -#line 21 - testRunner.Then("I should have the following events in the database", ((string)(null)), table2); -#line hidden - testRunner.CollectScenarioErrors(); - } - - [NUnit.Framework.TestAttribute()] - [NUnit.Framework.DescriptionAttribute("Insert two domain events")] - public virtual void InsertTwoDomainEvents() - { - TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Insert two domain events", ((string[])(null))); -#line 25 -this.ScenarioSetup(scenarioInfo); -#line hidden - TechTalk.SpecFlow.Table table3 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table3.AddRow(new string[] { - "EventDate", - "3/20/2010 3:01:04 AM"}); - table3.AddRow(new string[] { - "AggregateRootId", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7"}); - table3.AddRow(new string[] { - "Sequence", - "2"}); - table3.AddRow(new string[] { - "ThisHappened", - "something"}); -#line 26 - testRunner.Given("I have a SomethingHappenedEvent to be added to the store with the following value" + - "s", ((string)(null)), table3); -#line 32 - testRunner.And("that event will serialize to \'The First Record\'"); -#line hidden - TechTalk.SpecFlow.Table table4 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table4.AddRow(new string[] { - "EventDate", - "4/24/2010 3:01:04 AM"}); - table4.AddRow(new string[] { - "AggregateRootId", - "C3579C12-C29B-4F65-8D83-B79AC5C85718"}); - table4.AddRow(new string[] { - "Sequence", - "4"}); - table4.AddRow(new string[] { - "SomeDataToStore", - "Testing"}); -#line 33 - testRunner.And("I have a SomethingElseHappenedEvent to be added to the store with the following v" + - "alues", ((string)(null)), table4); -#line 39 - testRunner.And("that event will serialize to \'The Second Record\'"); -#line 40 - testRunner.When("I add the domain events to the store"); -#line hidden - TechTalk.SpecFlow.Table table5 = new TechTalk.SpecFlow.Table(new string[] { - "EventDate", - "Data", - "Sequence", - "AggregateRootId", - "EventType"}); - table5.AddRow(new string[] { - "3/20/2010 3:01:04 AM", - "The First Record", - "2", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" + - "re.SqlServer.Tests"}); - table5.AddRow(new string[] { - "4/24/2010 3:01:04 AM", - "The Second Record", - "4", - "C3579C12-C29B-4F65-8D83-B79AC5C85718", - "SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.Even" + - "tStore.SqlServer.Tests"}); -#line 41 - testRunner.Then("I should have the following events in the database", ((string)(null)), table5); -#line hidden - testRunner.CollectScenarioErrors(); - } - - [NUnit.Framework.TestAttribute()] - [NUnit.Framework.DescriptionAttribute("Inserting and retrieving an event")] - public virtual void InsertingAndRetrievingAnEvent() - { - TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Inserting and retrieving an event", ((string[])(null))); -#line 46 -this.ScenarioSetup(scenarioInfo); -#line hidden - TechTalk.SpecFlow.Table table6 = new TechTalk.SpecFlow.Table(new string[] { - "Field", - "Value"}); - table6.AddRow(new string[] { - "EventDate", - "3/20/2010 3:01:04 AM"}); - table6.AddRow(new string[] { - "AggregateRootId", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7"}); - table6.AddRow(new string[] { - "Sequence", - "2"}); - table6.AddRow(new string[] { - "ThisHappened", - "something"}); -#line 47 - testRunner.Given("I have a SomethingHappenedEvent to be added to the store with the following value" + - "s", ((string)(null)), table6); -#line 53 - testRunner.And("I am choosing to use the Json Serializer"); -#line 54 - testRunner.When("I add the domain events to the store"); -#line hidden - TechTalk.SpecFlow.Table table7 = new TechTalk.SpecFlow.Table(new string[] { - "EventDate", - "AggregateRootId", - "Sequence", - "ThisHappened"}); - table7.AddRow(new string[] { - "3/20/2010 3:01:04 AM", - "8312E92C-DF1C-4970-A9D5-6414120C3CF7", - "2", - "something"}); -#line 55 - testRunner.Then("I should get back the following SomethingHappenedEvents", ((string)(null)), table7); -#line hidden - testRunner.CollectScenarioErrors(); - } - } -} -#endregion diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Properties/AssemblyInfo.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index 3c97660..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.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("SimpleCqrs.EventStore.SqlServer.Tests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SimpleCqrs.EventStore.SqlServer.Tests")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[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("69cc4772-d7c5-4894-80ed-c80a0e69b329")] - -// 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/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/SimpleCqrs.EventStore.SqlServer.Tests.csproj b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/SimpleCqrs.EventStore.SqlServer.Tests.csproj deleted file mode 100644 index 0cc98eb..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/SimpleCqrs.EventStore.SqlServer.Tests.csproj +++ /dev/null @@ -1,144 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {77A06BB6-0B60-4B10-B1BB-BDEDDC8EC743} - Library - Properties - SimpleCqrs.EventStore.SqlServer.Tests - SimpleCqrs.EventStore.SqlServer.Tests - v4.0 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\..\lib\AutoMoq.dll - - - ..\..\..\..\lib\Machine.Specifications.dll - - - - False - ..\..\..\..\lib\nunit.framework.dll - - - ..\..\..\..\lib\Should.dll - - - False - ..\..\..\..\lib\Simple.Data.dll - - - False - ..\..\..\..\lib\Simple.Data.Ado.dll - - - False - ..\..\..\..\lib\Simple.Data.SqlServer.dll - - - - - ..\..\..\..\..\Simple.Data\Simple.Data.SqlServer\bin\Debug\System.CoreEx.dll - - - ..\..\..\..\..\Simple.Data\Simple.Data.SqlServer\bin\Debug\System.Reactive.dll - - - - - - - - ..\..\..\..\lib\TechTalk.SpecFlow.dll - - - - - CreateEventStore.feature - True - True - - - True - True - GetEvents.feature - - - True - True - InsertEvents.feature - - - - - - - - - - - - - - - - - - {BEEBFC8E-91EC-4E24-8223-395C2302C1B3} - SimpleCqrs.EventStore.SqlServer - - - {00634E6C-A282-404A-B08B-338FD4CA41A9} - SimpleCqrs.Unity - - - {E04C12B5-A6D3-4D64-9F38-896BEE68162E} - SimpleCqrs - - - - - SpecFlowSingleFileGenerator - CreateEventStore.feature.cs - - - SpecFlowSingleFileGenerator - GetEvents.feature.cs - - - SpecFlowSingleFileGenerator - InsertEvents.feature.cs - - - - - - \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/SomethingElseHappenedEvent.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/SomethingElseHappenedEvent.cs deleted file mode 100644 index 4b4c5dc..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/SomethingElseHappenedEvent.cs +++ /dev/null @@ -1,9 +0,0 @@ -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.EventStore.SqlServer.Tests -{ - public class SomethingElseHappenedEvent : DomainEvent - { - public string SomeDataToStore { get; set; } - } -} \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/SomethingHappenedEvent.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/SomethingHappenedEvent.cs deleted file mode 100644 index 001a846..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/SomethingHappenedEvent.cs +++ /dev/null @@ -1,9 +0,0 @@ -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.EventStore.SqlServer.Tests -{ - public class SomethingHappenedEvent : DomainEvent - { - public string ThisHappened { get; set; } - } -} \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Specs/JsonDomainEventSerializerTests.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Specs/JsonDomainEventSerializerTests.cs deleted file mode 100644 index 360daff..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Specs/JsonDomainEventSerializerTests.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Machine.Specifications; -using SimpleCqrs.Eventing; -using SimpleCqrs.EventStore.SqlServer.Serializers; - -namespace SimpleCqrs.EventStore.SqlServer.Tests.Specs -{ - [Subject(typeof (JsonDomainEventSerializer))] - public class when_serializing_a_SomethingHappenedEvent : with_automoqer - { - private Because of = - () => - { - var serializer = new JsonDomainEventSerializer(); - result = serializer.Serialize(new SomethingHappenedEvent - { - AggregateRootId = new Guid("14802395-BAC1-4F4B-AF6D-855DADC9E824"), - EventDate = new DateTime(2015, 3, 31), - Sequence = 4, - ThisHappened = "Testing values." - }); - }; - - private It should_equal_a_json_representation_of_the_object = - () => result.ShouldEqual(@"{""ThisHappened"":""Testing values."",""AggregateRootId"":""14802395bac14f4baf6d855dadc9e824"",""Sequence"":4,""EventDate"":""\/Date(1427778000000+0000)\/""}"); - - private static string result; - } -} diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/DatabaseSteps.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/DatabaseSteps.cs deleted file mode 100644 index a7a2290..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/DatabaseSteps.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data.SqlClient; -using System.Linq; -using Simple.Data; -using TechTalk.SpecFlow; -using TechTalk.SpecFlow.Assist; - -namespace SimpleCqrs.EventStore.SqlServer.Tests.Steps -{ - [Binding] - public class DatabaseSteps - { - public static void ClearTheEventStore() - { - dynamic db = GetTheDatabase(); - try - { - var events = GetTheDomainEvents(); - foreach (var @event in events) - { - var eventId = @event.EventId; - db.EventStore.DeleteByEventId(eventId); - } - } catch - { - } - - db = null; - } - - [Given(@"the EventStore table does not exist")] - public void GivenTheEventStoreTableDoesNotExist() - { - var sqlConfiguration = ScenarioContext.Current.Get(); - - var createSql = - @" -IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[{1}]') AND type in (N'U')) -begin -Drop table [{1}]; -end"; - using (var connection = new SqlConnection(sqlConfiguration.ConnectionString)) - { - connection.Open(); - var sql = string.Format(createSql, "", "EventStore"); - using (var command = new SqlCommand(sql, connection)) - { - command.ExecuteNonQuery(); - } - connection.Close(); - } - } - - - [Given(@"I have the following events in the database")] - public void GivenIHaveTheFollowingEventsInTheDatabase(Table table) - { - dynamic db = GetTheDatabase(); - - var eventStoreRecords = table.CreateSet(); - - foreach (var record in eventStoreRecords) - { - dynamic recordToAdd = new SimpleRecord(); - recordToAdd.Data = record.Data; - recordToAdd.Sequence = record.Sequence; - recordToAdd.EventDate = record.EventDate; - recordToAdd.AggregateRootId = record.AggregateRootId; - recordToAdd.EventType = record.EventType; - db.EventStore.Insert(recordToAdd); - } - } - - [Then(@"I should have the following events in the database")] - public void x(Table table) - { - var events = GetTheDomainEvents(); - - table.CompareToSet(events); - } - - private static IEnumerable GetTheDomainEvents() - { - dynamic db = GetTheDatabase(); - - IEnumerable databaseRecords = db.EventStore.FindAll(db.EventStore.EventType != "x").ToList() - ?? new dynamic[] {}; - - return databaseRecords.Select(x => new EventStore - { - AggregateRootId = x.AggregateRootId, - Data = x.Data, - EventDate = x.EventDate, - EventId = x.EventId, - EventType = x.EventType, - Sequence = x.Sequence - }).ToList(); - } - - private static object GetTheDatabase() - { - var sqlServerConfiguration = ScenarioContext.Current.Get(); - - return Database.OpenConnection(sqlServerConfiguration.ConnectionString); - } - } - - public class EventStore - { - public int EventId { get; set; } - public string EventType { get; set; } - public Guid AggregateRootId { get; set; } - public DateTime EventDate { get; set; } - public int Sequence { get; set; } - public string Data { get; set; } - } -} \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/DomainEventSteps.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/DomainEventSteps.cs deleted file mode 100644 index 5ea16ec..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/DomainEventSteps.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Moq; -using SimpleCqrs.Eventing; -using TechTalk.SpecFlow; -using TechTalk.SpecFlow.Assist; - -namespace SimpleCqrs.EventStore.SqlServer.Tests.Specs -{ - [Binding] - public class DomainEventSteps - { - private IList eventsToAdd; - private Mock domainEventSerializer; - - [BeforeScenario] - public void Setup() - { - domainEventSerializer = new Mock(); - eventsToAdd = new List(); - - ScenarioContext.Current.Set>(() => eventsToAdd); - ScenarioContext.Current.Set(domainEventSerializer.Object); - } - - [Given(@"I have a SomethingHappenedEvent to be added to the store with the following values")] - public void x(Table table) - { - var somethingHappenedEvent = table.CreateInstance(); - eventsToAdd.Add(somethingHappenedEvent); - } - - [Given(@"I have a SomethingElseHappenedEvent to be added to the store with the following values")] - public void y(Table table) - { - var somethingHappenedEvent = table.CreateInstance(); - eventsToAdd.Add(somethingHappenedEvent); - } - - [Given(@"that event will serialize to '(.*)'")] - public void x(string result) - { - var domainEvent = eventsToAdd.ToList().Last(); - domainEventSerializer.Setup(x => x.Serialize(domainEvent)) - .Returns(result); - } - - [Given(@"deserializing '(.*)' will return a SomethingHappenedEvent with the following data")] - public void z(string data, Table table) - { - domainEventSerializer.Setup(x => x.Deserialize(typeof (SomethingHappenedEvent), data)) - .Returns(table.CreateInstance()); - } - - [Given(@"deserializing '(.*)' will return a SomethingElseHappenedEvent with the following data")] - public void a(string data, Table table) - { - domainEventSerializer.Setup(x => x.Deserialize(typeof (SomethingElseHappenedEvent), data)) - .Returns(table.CreateInstance()); - } - - [Then(@"I should get back the following DomainEvents")] - public void b(Table table) - { - var domainEvents = ScenarioContext.Current.Get>(); - table.CompareToSet(domainEvents); - } - - [Then(@"I should get back the following SomethingHappenedEvents")] - public void g(Table table) - { - var somethingHappenedEvents = ScenarioContext.Current.Get>().OfType(); - table.CompareToSet(somethingHappenedEvents); - } - } -} \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/JsonSerializerSteps.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/JsonSerializerSteps.cs deleted file mode 100644 index cb6191d..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/JsonSerializerSteps.cs +++ /dev/null @@ -1,15 +0,0 @@ -using SimpleCqrs.EventStore.SqlServer.Serializers; -using TechTalk.SpecFlow; - -namespace SimpleCqrs.EventStore.SqlServer.Tests.Steps -{ - [Binding] - public class JsonSerializerSteps - { - [Given(@"I am choosing to use the Json Serializer")] - public void GivenIAmChoosingToUseTheJsonSerializer() - { - ScenarioContext.Current.Set(new JsonDomainEventSerializer()); - } - } -} \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/RuntimeSteps.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/RuntimeSteps.cs deleted file mode 100644 index 162d727..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/RuntimeSteps.cs +++ /dev/null @@ -1,34 +0,0 @@ -using TechTalk.SpecFlow; - -namespace SimpleCqrs.EventStore.SqlServer.Tests.Specs -{ - [Binding] - public class RuntimeSteps - { - public static TestingRuntime Runtime; - - [BeforeTestRun] - public static void TestRun() - { - Runtime = new TestingRuntime(); - Runtime.Start(); - } - - [AfterTestRun] - public static void Cleanup() - { - Runtime.Shutdown(); - } - - [BeforeScenario] - public void Setup() - { - ScenarioContext.Current.Set(Runtime.ServiceLocator); - } - - [AfterScenario] - public void Teardown() - { - } - } -} \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/SomethingHappenedEventSteps.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/SomethingHappenedEventSteps.cs deleted file mode 100644 index 27547fd..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/SomethingHappenedEventSteps.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using TechTalk.SpecFlow; - -namespace SimpleCqrs.EventStore.SqlServer.Tests.Steps -{ - [Binding] - public class SomethingHappenedEventSteps - { - - - } -} diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/SqlServerConfigurationSteps.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/SqlServerConfigurationSteps.cs deleted file mode 100644 index e9a8ebc..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/SqlServerConfigurationSteps.cs +++ /dev/null @@ -1,17 +0,0 @@ -using TechTalk.SpecFlow; - -namespace SimpleCqrs.EventStore.SqlServer.Tests.Steps -{ - [Binding] - public class SqlServerConfigurationSteps - { - [Given(@"the connection string to my database is")] - public void x(string connectionString) - { - var sqlServerConfiguration = new SqlServerConfiguration(connectionString); - ScenarioContext.Current.Set(sqlServerConfiguration); - - DatabaseSteps.ClearTheEventStore(); - } - } -} \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/SqlServerEventStoreSteps.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/SqlServerEventStoreSteps.cs deleted file mode 100644 index 53c8652..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Steps/SqlServerEventStoreSteps.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using SimpleCqrs.Eventing; -using TechTalk.SpecFlow; - -namespace SimpleCqrs.EventStore.SqlServer.Tests.Specs -{ - [Binding] - public class SqlServerEventStoreSteps - { - [When(@"I add the domain events to the store")] - public void WhenIAddTheDomainEventsToTheStore() - { - var eventsToAdd = ScenarioContext.Current.Get>(); - - var eventStore = CreateTheEventStore(); - eventStore.Insert(eventsToAdd); - } - - [When(@"I retrieve the domain events for '(.*)' and sequence (.*)")] - public void z(string aggregateRootId, int sequence) - { - var eventStore = CreateTheEventStore(); - var events = eventStore.GetEvents(new Guid(aggregateRootId), sequence); - - ScenarioContext.Current.Set(events); - } - - [When(@"I retrieve the domain events for '(.*)'")] - public void z(string aggregateRootId) - { - var eventStore = CreateTheEventStore(); - var events = eventStore.GetEvents(new Guid(aggregateRootId), 0); - - ScenarioContext.Current.Set(events); - } - - [When(@"I retrieve the domain events for the following types")] - public void WhenIRetrieveTheDomainEventsForTheFollowingTypes(Table table) - { - var types = table.Rows.Select(x => Type.GetType(x["Type"])); - - var eventStore = CreateTheEventStore(); - var events = eventStore.GetEventsByEventTypes(types); - - ScenarioContext.Current.Set(events); - } - - private static SqlServerEventStore CreateTheEventStore() - { - var sqlServerConfiguration = ScenarioContext.Current.Get(); - var domainEventSerializer = ScenarioContext.Current.Get(); - return new SqlServerEventStore(sqlServerConfiguration, domainEventSerializer); - } - } -} \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/TestingRuntime.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/TestingRuntime.cs deleted file mode 100644 index f016a71..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/TestingRuntime.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using SimpleCqrs.Unity; - -namespace SimpleCqrs.EventStore.SqlServer.Tests -{ - public class TestingRuntime : SimpleCqrsRuntime - { - protected override ITypeCatalog GetTypeCatalog(IServiceLocator serviceLocator) - { - var assemblyTypeCatalog = new AssemblyTypeCatalog(new []{typeof(TestingRuntime).Assembly}); - return new TestingAssemblyTypeCatalog(assemblyTypeCatalog); - } - } - - public class TestingAssemblyTypeCatalog : ITypeCatalog - { - private ITypeCatalog typeCatalog; - public TestingAssemblyTypeCatalog(ITypeCatalog typeCatalog) - { - this.typeCatalog = typeCatalog; - } - - public Type[] GetDerivedTypes(Type type) - { - return typeCatalog.GetDerivedTypes(type); - } - - public Type[] GetDerivedTypes() - { - return typeCatalog.GetDerivedTypes(); - } - - public Type[] GetGenericInterfaceImplementations(Type type) - { - return typeCatalog.GetGenericInterfaceImplementations(type); - } - - public Type[] GetInterfaceImplementations(Type type) - { - return typeCatalog.GetInterfaceImplementations(type); - } - - public Type[] GetInterfaceImplementations() - { - return typeCatalog.GetInterfaceImplementations(); - } - } -} \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/with_automoqer.cs b/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/with_automoqer.cs deleted file mode 100644 index 7dc60ed..0000000 --- a/src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/with_automoqer.cs +++ /dev/null @@ -1,25 +0,0 @@ -using AutoMoq; -using Moq; - -namespace SimpleCqrs.EventStore.SqlServer.Tests -{ - public class with_automoqer - { - public static AutoMoqer mocker; - - public with_automoqer() - { - mocker = new AutoMoqer(); - } - - public static T Create() - { - return mocker.Resolve(); - } - - public static Mock GetMock() where T : class - { - return mocker.GetMock(); - } - } -} \ No newline at end of file diff --git a/src/Tests/EventStores/SimpleCrqs.EventStore.MongoDb.Tests/Properties/AssemblyInfo.cs b/src/Tests/EventStores/SimpleCrqs.EventStore.MongoDb.Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index 5875292..0000000 --- a/src/Tests/EventStores/SimpleCrqs.EventStore.MongoDb.Tests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +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("SimpleCrqs.EventStore.MongoDb.Tests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SimpleCrqs.EventStore.MongoDb.Tests")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] -[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("9a830515-c28d-4a01-b50d-16a97169cba7")] - -// 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.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Tests/EventStores/SimpleCrqs.EventStore.MongoDb.Tests/SimpleCrqs.EventStore.MongoDb.Tests.csproj b/src/Tests/EventStores/SimpleCrqs.EventStore.MongoDb.Tests/SimpleCrqs.EventStore.MongoDb.Tests.csproj deleted file mode 100644 index 8dc91d5..0000000 --- a/src/Tests/EventStores/SimpleCrqs.EventStore.MongoDb.Tests/SimpleCrqs.EventStore.MongoDb.Tests.csproj +++ /dev/null @@ -1,71 +0,0 @@ - - - - Debug - AnyCPU - - - 2.0 - {38E51E8F-7008-47EC-AC9F-862A1F377532} - Library - Properties - SimpleCrqs.EventStore.MongoDb.Tests - SimpleCrqs.EventStore.MongoDb.Tests - v4.0 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\..\lib\AutoMoq.dll - - - - - 3.5 - - - - - False - - - - - - - - {201A4DF5-2217-4202-80E8-E784737366BC} - SimpleCqrs.EventStore.MongoDb - - - {00634E6C-A282-404A-B08B-338FD4CA41A9} - SimpleCqrs.Unity - - - - - \ No newline at end of file diff --git a/src/Tests/SimpleCqrs.EventStore.Tests/DomainRepositoryTests.cs b/src/Tests/SimpleCqrs.EventStore.Tests/DomainRepositoryTests.cs deleted file mode 100644 index 2240543..0000000 --- a/src/Tests/SimpleCqrs.EventStore.Tests/DomainRepositoryTests.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using AutoMoq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using SimpleCqrs.Domain; -using SimpleCqrs.Events; - -namespace SimpleCqrs.EventStore.Tests -{ - [TestClass] - public class DomainRepositoryTests - { - private AutoMoqer mocker; - - [TestInitialize] - public void SetupMocksForAllTests() - { - mocker = new AutoMoqer(); - } - - [TestMethod] - public void EventsAreRetrievedFromTheEventStoreAndAppliedToTheAggregateRootWhenGetByIdIsCalled() - { - var repository = CreateDomainRepository(); - var aggregateRootId = new Guid(); - var domainEvents = new List {new MyTestEvent(), new MyTestEvent(), new MyTestEvent()}; - - mocker.GetMock() - .Setup(eventStore => eventStore.GetEvents(aggregateRootId, 0)) - .Returns(domainEvents); - - var aggregateRoot = repository.GetById(aggregateRootId); - - Assert.AreEqual(3, aggregateRoot.MyTestEventHandleCount); - } - - [TestMethod] - public void UncommittedEventsAreInsertedIntoTheEventStoreWhenSaved() - { - var repository = CreateDomainRepository(); - var aggregateRoot = new MyTestAggregateRoot(); - var domainEvents = new List {new MyTestEvent(), new MyTestEvent(), new MyTestEvent()}; - - aggregateRoot.Apply(domainEvents[0]); - aggregateRoot.Apply(domainEvents[1]); - aggregateRoot.Apply(domainEvents[2]); - - repository.Save(aggregateRoot); - - mocker.GetMock() - .Verify(eventStore => eventStore.Insert(It.Is>(events => events.All(domainEvents.Contains))), Times.Once()); - } - - [TestMethod] - public void UncommittedEventsArePublishedToTheEventBusWhenSaved() - { - var repository = CreateDomainRepository(); - var aggregateRoot = new MyTestAggregateRoot(); - var domainEvents = new List {new MyTestEvent(), new MyTestEvent(), new MyTestEvent()}; - - aggregateRoot.Apply(domainEvents[0]); - aggregateRoot.Apply(domainEvents[1]); - aggregateRoot.Apply(domainEvents[2]); - - repository.Save(aggregateRoot); - - mocker.GetMock() - .Verify(eventBus => eventBus.PublishEvents(It.IsAny>()), Times.Once()); - } - - [TestMethod] - public void UncommittedEventsShouldBeCommited() - { - var repository = CreateDomainRepository(); - var aggregateRoot = new MyTestAggregateRoot(); - - aggregateRoot.Apply(new MyTestEvent()); - aggregateRoot.Apply(new MyTestEvent()); - - repository.Save(aggregateRoot); - - Assert.AreEqual(0, aggregateRoot.UncommittedEvents.Count); - } - - public DomainRepository CreateDomainRepository() - { - return mocker.Resolve(); - } - - public class MyTestAggregateRoot : AggregateRoot - { - public int MyTestEventHandleCount { get; set; } - public List EventIds { get; set; } - - public MyTestAggregateRoot() - { - EventIds = new List(); - } - - private void OnMyTest(MyTestEvent myTestEvent) - { - MyTestEventHandleCount++; - EventIds.Add(myTestEvent.Sequence); - } - } - - public class MyTestEvent : DomainEvent - { - } - } -} \ No newline at end of file diff --git a/src/Tests/SimpleCqrs.EventStore.Tests/Properties/AssemblyInfo.cs b/src/Tests/SimpleCqrs.EventStore.Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index 58bd2ad..0000000 --- a/src/Tests/SimpleCqrs.EventStore.Tests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +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("SimpleCqrs.EventStore.Tests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("DEG")] -[assembly: AssemblyProduct("SimpleCqrs.EventStore.Tests")] -[assembly: AssemblyCopyright("Copyright © DEG 2010")] -[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("d046eff5-5702-46e5-a5d0-59de9b0fc0cc")] - -// 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.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Tests/SimpleCqrs.EventStore.Tests/SimpleCqrs.EventStore.Tests.csproj b/src/Tests/SimpleCqrs.EventStore.Tests/SimpleCqrs.EventStore.Tests.csproj deleted file mode 100644 index 7ed326a..0000000 --- a/src/Tests/SimpleCqrs.EventStore.Tests/SimpleCqrs.EventStore.Tests.csproj +++ /dev/null @@ -1,68 +0,0 @@ - - - - Debug - AnyCPU - - - 2.0 - {7BB13E79-4290-463F-A709-FB95260D34AF} - Library - Properties - SimpleCqrs.EventStore.Tests - SimpleCqrs.EventStore.Tests - v4.0 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\lib\AutoMoq.dll - - - - - 3.5 - - - - - False - - - - - - - - - {EC740994-5BB9-40B6-BB1A-614FC5E5D315} - SimpleCqrs.Core - - - - - \ No newline at end of file diff --git a/src/Tests/SimpleCqrs.Tests/Commanding/AggregateRootCommandHandlerTests.cs b/src/Tests/SimpleCqrs.Tests/Commanding/AggregateRootCommandHandlerTests.cs deleted file mode 100644 index 38edb0c..0000000 --- a/src/Tests/SimpleCqrs.Tests/Commanding/AggregateRootCommandHandlerTests.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using AutoMoq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using SimpleCqrs.Commanding; -using SimpleCqrs.Domain; - -namespace SimpleCqrs.Core.Tests.Commanding -{ - [TestClass] - public class AggregateRootCommandHandlerTests - { - private AutoMoqer mocker; - private MockServiceLocator mockServiceLocator; - - [TestInitialize] - public void SetupMocksForAllTest() - { - mocker = new AutoMoqer(); - mockServiceLocator = new MockServiceLocator(mocker); - - ServiceLocator.SetCurrent(mockServiceLocator); - } - - [TestMethod, Ignore] - public void When_the_command_is_handled_the_aggregateroot_with_the_aggregaterootid_is_retrieved_out_of_the_domainrepository() - { - var aggregateRootId = new Guid("438DBA36-8253-4AC3-BF37-0CBB86F167BB"); - var handlingContext = new MyHandlingContext(); - handlingContext.Command = new MyCommand{AggregateRootId = aggregateRootId}; - - var commandHandler = CreateAggregateRootCommandHandler(); - commandHandler.Handle(handlingContext); - - mocker.GetMock() - .Verify(repository => repository.GetById(aggregateRootId)); - } - - private IHandleCommands CreateAggregateRootCommandHandler() - { - return mocker.Resolve(); - } - } - - public class MyAggregateRootCommandHandler : AggregateRootCommandHandler - { - public override void Handle(MyCommand command, MyAggregateRoot aggregateRoot) - { - } - } - - public class MyCommand : CommandWithAggregateRootId - { - } - - public class MyAggregateRoot : AggregateRoot - { - } - - public class MyHandlingContext : ICommandHandlingContext - { - public MyCommand Command { get; set; } - - public void Return(int value) - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/src/Tests/SimpleCqrs.Tests/Commanding/LocalCommandBusTests.cs b/src/Tests/SimpleCqrs.Tests/Commanding/LocalCommandBusTests.cs deleted file mode 100644 index ffaa68a..0000000 --- a/src/Tests/SimpleCqrs.Tests/Commanding/LocalCommandBusTests.cs +++ /dev/null @@ -1,165 +0,0 @@ -using System; -using AutoMoq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using SimpleCqrs.Commanding; - -namespace SimpleCqrs.Core.Tests.Commanding -{ - [TestClass] - public class LocalCommandBusTests - { - private AutoMoqer mocker; - private MockServiceLocator serviceLocator; - - [TestInitialize] - public void SetupMocksForAllTest() - { - mocker = new AutoMoqer(); - serviceLocator = new MockServiceLocator(mocker); - } - - [TestMethod] - public void CommandHandlerNotFoundExceptionIsNotThrownWhenNoCommandHandlerIsFoundForASentCommandAndCommandBusIsInTestMode() - { - mocker.GetMock() - .Setup(typeCatalog => typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleCommands<>))) - .Returns(new[] {typeof(MyTestCommandHandler)}); - - var commandBus = CreateCommandBus(serviceLocator); - ((IHaveATestMode)commandBus).IsInTestMode = true; - - commandBus.Send(new MyTest3Command()); - } - - [TestMethod] - public void CommandHandlerNotFoundExceptionIsNotThrownWhenNoCommandHandlerIsFoundForAnExecutedCommandAndCommandBusIsInTestMode() - { - mocker.GetMock() - .Setup(typeCatalog => typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleCommands<>))) - .Returns(new[] {typeof(MyTestCommandHandler)}); - - var commandBus = CreateCommandBus(serviceLocator); - ((IHaveATestMode)commandBus).IsInTestMode = true; - - commandBus.Execute(new MyTest3Command {ReturnValue = 321}); - } - - [TestMethod] - [ExpectedException(typeof(CommandHandlerNotFoundException))] - public void CommandHandlerNotFoundExceptionIsThrownWhenNoCommandHandlerIsFoundForCommand() - { - mocker.GetMock() - .Setup(typeCatalog => typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleCommands<>))) - .Returns(new[] {typeof(MyTestCommandHandler)}); - - var commandBus = CreateCommandBus(serviceLocator); - commandBus.Execute(new MyTest3Command {ReturnValue = 321}); - } - - [TestMethod] - public void CommandHandlerForMyCommandIsCalledWhenHandlerTypeIsInTypeCatalog() - { - serviceLocator.ResolveFunc = Activator.CreateInstance; - - mocker.GetMock() - .Setup(typeCatalog => typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleCommands<>))) - .Returns(new[] {typeof(MyTestCommandHandler)}); - - var commandBus = CreateCommandBus(serviceLocator); - var result = commandBus.Execute(new MyTestCommand {ReturnValue = 321}); - - Assert.AreEqual(321, result); - } - - [TestMethod] - [ExpectedException(typeof(DuplicateCommandHandlersException))] - public void DuplicateCommandHandlersExceptionIsThrownWhenTwoCommandHandlersForSameCommandExist() - { - mocker.GetMock() - .Setup(typeCatalog => typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleCommands<>))) - .Returns(new[] - { - typeof(MyTestCommandHandler), - typeof(MyTestCommandHandler) - }); - - var commandBus = CreateCommandBus(serviceLocator); - commandBus.Execute(new MyTestCommand()); - } - - [TestMethod] - public void CommandHandlerThatImplementsTwoHandlersAreCalledWhenHandlerTypeIsInTypeCatalog() - { - mocker.GetMock() - .Setup(typeCatalog => typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleCommands<>))) - .Returns(new[] {typeof(HandlerForTwoCommands)}); - - var commandBus = CreateCommandBus(serviceLocator); - var result = commandBus.Execute(new MyTestCommand {ReturnValue = 102}); - var result2 = commandBus.Execute(new MyTest2Command {ReturnValue = 45}); - - Assert.AreEqual(102, result); - Assert.AreEqual(45, result2); - } - - [TestMethod] - public void Handle_WhenExceptionIsThrown_InvokerThrowsInitialException() - { - mocker.GetMock() - .Setup(typeCatalog => typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleCommands<>))) - .Returns(new[] {typeof(MyTestCommandHandler)}); - - mocker.GetMock() - .Setup(handler => handler.Handle(It.IsAny>())) - .Throws(new Exception("THE SANTA ROCKS!")); - - var commandBus = CreateCommandBus(serviceLocator); - - var ex = CustomAsserts.Throws(() => commandBus.Execute(new MyTestCommand())); - Assert.AreEqual("THE SANTA ROCKS!", ex.InnerException.Message); - } - - private ICommandBus CreateCommandBus(IServiceLocator serviceLocator) - { - var typeCatalog = mocker.Resolve(); - return new LocalCommandBus(typeCatalog, serviceLocator); - } - } - - public class MyTestCommandHandler : IHandleCommands - { - public virtual void Handle(ICommandHandlingContext handlingContext) - { - handlingContext.Return(handlingContext.Command.ReturnValue); - } - } - - public class HandlerForTwoCommands : IHandleCommands, IHandleCommands - { - public void Handle(ICommandHandlingContext handlingContext) - { - handlingContext.Return(handlingContext.Command.ReturnValue); - } - - public void Handle(ICommandHandlingContext handlingContext) - { - handlingContext.Return(handlingContext.Command.ReturnValue); - } - } - - public class MyTestCommand : ICommand - { - public int ReturnValue { get; set; } - } - - public class MyTest2Command : ICommand - { - public int ReturnValue { get; set; } - } - - public class MyTest3Command : ICommand - { - public int ReturnValue { get; set; } - } -} \ No newline at end of file diff --git a/src/Tests/SimpleCqrs.Tests/Commanding/MockServiceLocator.cs b/src/Tests/SimpleCqrs.Tests/Commanding/MockServiceLocator.cs deleted file mode 100644 index bdb5691..0000000 --- a/src/Tests/SimpleCqrs.Tests/Commanding/MockServiceLocator.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Collections.Generic; -using AutoMoq; - -namespace SimpleCqrs.Core.Tests.Commanding -{ - public class MockServiceLocator : IServiceLocator - { - private readonly AutoMoqer mocker; - private Func resolveFunc; - - public MockServiceLocator(AutoMoqer mocker) - { - this.mocker = mocker; - } - - public Func ResolveFunc - { - set { resolveFunc = value; } - } - - public void Dispose() - { - throw new NotImplementedException(); - } - - public T Resolve() where T : class - { - if(resolveFunc != null) - return (T)resolveFunc(typeof(T)); - - return mocker.GetMock().Object; - } - - public T Resolve(string key) where T : class - { - throw new NotImplementedException(); - } - - public object Resolve(Type type) - { - if(resolveFunc != null) - return resolveFunc(type); - - dynamic mock = typeof(AutoMoqer).GetMethod("GetMock").MakeGenericMethod(type).Invoke(mocker, null); - return mock.Object; - } - - public IList ResolveServices() where T : class - { - throw new NotImplementedException(); - } - - public void Register(Type implType) where TInterface : class - { - throw new NotImplementedException(); - } - - public void Register() where TImplementation : class, TInterface - { - throw new NotImplementedException(); - } - - public void Register(string key) where TImplementation : class, TInterface - { - throw new NotImplementedException(); - } - - public void Register(string key, Type type) - { - throw new NotImplementedException(); - } - - public void Register(Type serviceType, Type implType) - { - throw new NotImplementedException(); - } - - public void Register(TInterface instance) where TInterface : class - { - throw new NotImplementedException(); - } - - public void Release(object instance) - { - throw new NotImplementedException(); - } - - public void Reset() - { - throw new NotImplementedException(); - } - - public TService Inject(TService instance) where TService : class - { - throw new NotImplementedException(); - } - - public void TearDown(TService instance) where TService : class - { - throw new NotImplementedException(); - } - - public void Register(Func factoryMethod) where Interface : class - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/src/Tests/SimpleCqrs.Tests/CustomAsserts.cs b/src/Tests/SimpleCqrs.Tests/CustomAsserts.cs deleted file mode 100644 index 18b7fd6..0000000 --- a/src/Tests/SimpleCqrs.Tests/CustomAsserts.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Diagnostics; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace SimpleCqrs.Core.Tests -{ - public static class CustomAsserts - { - [DebuggerStepThrough()] - public static T Throws(Action action) where T : Exception - { - try - { - action.Invoke(); - } - catch (T ex) - { - return ex; - } - catch (Exception ex) - { - throw new AssertFailedException( - string.Format("Expected exception was not thrown! Got other exception: '{0}'.", ex.GetType()) - ,ex); - } - - throw new AssertFailedException("Expected exception was not thrown! None was thrown."); - } - } -} \ No newline at end of file diff --git a/src/Tests/SimpleCqrs.Tests/Domain/AggregateRootTests.cs b/src/Tests/SimpleCqrs.Tests/Domain/AggregateRootTests.cs deleted file mode 100644 index 670f433..0000000 --- a/src/Tests/SimpleCqrs.Tests/Domain/AggregateRootTests.cs +++ /dev/null @@ -1,289 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using SimpleCqrs.Domain; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.Core.Tests.Domain -{ - [TestClass] - public class AggregateRootTests - { - private Mock mockAggregateRoot; - - [TestInitialize] - public void SetupMockForAllTests() - { - mockAggregateRoot = new Mock {CallBase = true}; - } - - [TestMethod] - public void WhenRegisterEntityIsCalledEntityAggegrateRootIsAssigned() - { - var aggregateRoot = new MyAggregateRoot(); - var entity = new MyEntity(); - - aggregateRoot.RegisterEntity(entity); - - Assert.AreSame(aggregateRoot, entity.AggregateRoot); - } - - [TestMethod] - public void HandlerIsCalledWhenHandlerMeetsTheConventionAndEventIsApplied() - { - var domainEvent = new AggregateRootHandlerThatMeetsConventionEvent(); - var aggregateRoot = mockAggregateRoot.Object; - - aggregateRoot.Apply(domainEvent); - - mockAggregateRoot.Verify(ar => ar.OnAggregateRootHandlerThatMeetsConvention(domainEvent), Times.Once()); - } - - [TestMethod] - public void HandlerIsNotCalledWhenHandlerDoesNotMeetTheConventionAndEventIsApplied() - { - var domainEvent = new AggregateRootHandlerThatMeetsConventionEvent(); - var aggregateRoot = mockAggregateRoot.Object; - - aggregateRoot.Apply(domainEvent); - - mockAggregateRoot.Verify(ar => ar.OnAggregateRootHandlerThatDoesNotMeetsConvention(domainEvent), Times.Never()); - } - - [TestMethod] - public void HandlerIsNotCalledWhenHandlerHasTwoParametersAndEventIsApplied() - { - var domainEvent = new AggregateRootHandlerThatMeetsConventionEvent(); - var aggregateRoot = mockAggregateRoot.Object; - - aggregateRoot.Apply(domainEvent); - - mockAggregateRoot.Verify(ar => ar.OnAggregateRootHandlerThatMeetsConvention(domainEvent, "test"), Times.Never()); - } - - [TestMethod] - public void HandlerIsCalledWhenHandlerIsPrivateAndEventIsApplied() - { - var domainEvent = new AggregateRootPrivateHandlerThatMeetsConventionEvent(); - var aggregateRoot = new MyAggregateRoot(); - - aggregateRoot.Apply(domainEvent); - - Assert.IsTrue(aggregateRoot.OnAggregateRootPrivateHandlerThatMeetsConventionCalled); - } - - [TestMethod] - public void HandlerIsCalledWhenHandlerIsProtectedAndEventIsApplied() - { - var domainEvent = new AggregateRootProtectedHandlerThatMeetsConventionEvent(); - var aggregateRoot = new MyAggregateRoot(); - - aggregateRoot.Apply(domainEvent); - - Assert.IsTrue(aggregateRoot.OnAggregateRootProtectedHandlerThatMeetsConventionCalled); - } - - [TestMethod] - public void UncommittedEventsAreClearedWhenCommitEventsIsCalled() - { - var aggregateRoot = mockAggregateRoot.Object; - - aggregateRoot.Apply(new AggregateRootHandlerThatMeetsConventionEvent()); - aggregateRoot.Apply(new AggregateRootHandlerThatMeetsConventionEvent()); - aggregateRoot.Apply(new AggregateRootHandlerThatMeetsConventionEvent()); - - aggregateRoot.CommitEvents(); - - Assert.AreEqual(0, aggregateRoot.UncommittedEvents.Count); - } - - [TestMethod] - public void DomainEventIsPlacedInTheUncommittedEventsPropertyIfPublished() - { - var domainEvent = new AggregateRootHandlerThatMeetsConventionEvent(); - var aggregateRoot = mockAggregateRoot.Object; - - aggregateRoot.Apply(domainEvent); - - Assert.AreSame(domainEvent, aggregateRoot.UncommittedEvents.First()); - } - - [TestMethod] - public void MultipleDomainEventsArePlacedInTheUncommittedEventsPropertyInTheCorrectOrderIfPublished() - { - var domainEvent1 = new AggregateRootHandlerThatMeetsConventionEvent(); - var domainEvent2 = new AggregateRootHandlerThatMeetsConventionEvent(); - var domainEvent3 = new AggregateRootHandlerThatMeetsConventionEvent(); - var aggregateRoot = mockAggregateRoot.Object; - - aggregateRoot.Apply(domainEvent1); - aggregateRoot.Apply(domainEvent2); - aggregateRoot.Apply(domainEvent3); - - var uncommittedEvents = aggregateRoot.UncommittedEvents; - Assert.AreEqual(3, uncommittedEvents.Count()); - Assert.AreSame(domainEvent1, uncommittedEvents[0]); - Assert.AreSame(domainEvent2, uncommittedEvents[1]); - Assert.AreSame(domainEvent3, uncommittedEvents[2]); - } - - [TestMethod] - public void EventThatIsPublishedIsAssignedTheNextEventId() - { - var domainEvent = new AggregateRootHandlerThatMeetsConventionEvent(); - var aggregateRoot = mockAggregateRoot.Object; - - aggregateRoot.LoadFromHistoricalEvents(new AggregateRootHandlerThatMeetsConventionEvent {Sequence = 203}); - aggregateRoot.Apply(domainEvent); - - Assert.AreEqual(204, domainEvent.Sequence); - } - - [TestMethod] - public void DomainEventsAreAssignedSequentialSequenceWhenPublished() - { - var domainEvent1 = new AggregateRootHandlerThatMeetsConventionEvent(); - var domainEvent2 = new AggregateRootHandlerThatMeetsConventionEvent(); - var domainEvent3 = new AggregateRootHandlerThatMeetsConventionEvent(); - var aggregateRoot = mockAggregateRoot.Object; - - aggregateRoot.Apply(domainEvent1); - aggregateRoot.Apply(domainEvent2); - aggregateRoot.Apply(domainEvent3); - - Assert.AreEqual(1, domainEvent1.Sequence); - Assert.AreEqual(2, domainEvent2.Sequence); - Assert.AreEqual(3, domainEvent3.Sequence); - } - - [TestMethod] - public void EventsAreSortedBySequenceBeforeBeingAppliedToTheAggregateRoot() - { - var aggregateRoot = new MyAggregateRoot(); - var domainEvents = new List - { - new AggregateRootHandlerThatMeetsConventionEvent {Sequence = 5}, - new AggregateRootHandlerThatMeetsConventionEvent {Sequence = 1}, - new AggregateRootHandlerThatMeetsConventionEvent {Sequence = 100}, - new AggregateRootHandlerThatMeetsConventionEvent {Sequence = 2} - }; - - aggregateRoot.LoadFromHistoricalEvents(domainEvents.ToArray()); - - Assert.AreEqual(1, aggregateRoot.EventIds[0]); - Assert.AreEqual(2, aggregateRoot.EventIds[1]); - Assert.AreEqual(5, aggregateRoot.EventIds[2]); - Assert.AreEqual(100, aggregateRoot.EventIds[3]); - } - - [TestMethod] - public void AggregateRootIdIsAssignedToTheEventWhenTheEventIsAppliedAndTheAggregateRootIdIsGuidEmpty() - { - var aggregateRoot = mockAggregateRoot.Object; - var aggregateRootId = aggregateRoot.Id; - - aggregateRoot.Apply(new AggregateRootHandlerThatMeetsConventionEvent()); - aggregateRoot.Apply(new AggregateRootHandlerThatMeetsConventionEvent()); - aggregateRoot.Apply(new AggregateRootHandlerThatMeetsConventionEvent()); - - var allAggregateRootIdsMatch = aggregateRoot.UncommittedEvents - .All(domainEvent => domainEvent.AggregateRootId == aggregateRootId); - Assert.IsTrue(allAggregateRootIdsMatch); - } - - [TestMethod] - public void WhenEventModifierIsSetModificationsAreApplied() - { - // Arrange - var fakeModification = new FakeModification - { - ModifyValueTo = "Yes we can" - }; - var aggregateRoot = new MyAggregateRoot(); - var domainEvent = new EventForModificationTestEvent(); - - EventModifier.Modification = fakeModification; - - // Act - aggregateRoot.Apply(domainEvent); - - // Assert - Assert.AreEqual(domainEvent.ModifiedValue, fakeModification.ModifyValueTo); - - // Teardown - EventModifier.Modification = null; - } - - private class FakeModification : IEventModification - { - public void Apply(DomainEvent e) - { - if (e is EventForModificationTestEvent) - ((EventForModificationTestEvent)e).ModifiedValue = ModifyValueTo; - } - - public string ModifyValueTo { get; set; } - } - - private class EventForModificationTestEvent : DomainEvent - { - public string ModifiedValue { get; set; } - } - } - - public class MyEntity : Entity - { - } - - public class MyAggregateRoot : AggregateRoot - { - private int count; - - public MyAggregateRoot() - { - EventIds = new List(); - Id = Guid.NewGuid(); - } - - public List EventIds { get; private set; } - public bool OnAggregateRootPrivateHandlerThatMeetsConventionCalled { get; set; } - public bool OnAggregateRootProtectedHandlerThatMeetsConventionCalled { get; set; } - - public virtual void OnAggregateRootHandlerThatMeetsConvention(AggregateRootHandlerThatMeetsConventionEvent domainEvent) - { - EventIds.Add(domainEvent.Sequence); - } - - public virtual void OnAggregateRootHandlerThatDoesNotMeetsConvention(AggregateRootHandlerThatMeetsConventionEvent domainEvent) - { - } - - public virtual void OnAggregateRootHandlerThatMeetsConvention(AggregateRootHandlerThatMeetsConventionEvent domainEvent, string test) - { - } - - private void OnAggregateRootPrivateHandlerThatMeetsConvention(AggregateRootPrivateHandlerThatMeetsConventionEvent domainEvent) - { - OnAggregateRootPrivateHandlerThatMeetsConventionCalled = true; - } - - protected void OnAggregateRootProtectedHandlerThatMeetsConvention(AggregateRootProtectedHandlerThatMeetsConventionEvent domainEvent) - { - OnAggregateRootProtectedHandlerThatMeetsConventionCalled = true; - } - } - - public class AggregateRootHandlerThatMeetsConventionEvent : DomainEvent - { - } - - public class AggregateRootPrivateHandlerThatMeetsConventionEvent : DomainEvent - { - } - - public class AggregateRootProtectedHandlerThatMeetsConventionEvent : DomainEvent - { - } -} \ No newline at end of file diff --git a/src/Tests/SimpleCqrs.Tests/Domain/DomainRepositoryTests.cs b/src/Tests/SimpleCqrs.Tests/Domain/DomainRepositoryTests.cs deleted file mode 100644 index 60204b4..0000000 --- a/src/Tests/SimpleCqrs.Tests/Domain/DomainRepositoryTests.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using AutoMoq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using SimpleCqrs.Domain; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.Core.Tests.Domain -{ - [TestClass] - public class DomainRepositoryTests - { - private AutoMoqer mocker; - - [TestInitialize] - public void SetupMocksForAllTests() - { - mocker = new AutoMoqer(); - } - - [TestMethod] - public void EventsAreRetrievedFromTheEventStoreAndAppliedToTheAggregateRootWhenGetByIdIsCalled() - { - var repository = CreateDomainRepository(); - var aggregateRootId = new Guid(); - var domainEvents = new List {new MyTestEvent(), new MyTestEvent(), new MyTestEvent()}; - - mocker.GetMock() - .Setup(eventStore => eventStore.GetEvents(aggregateRootId, 0)) - .Returns(domainEvents); - - var aggregateRoot = repository.GetById(aggregateRootId); - - Assert.AreEqual(3, aggregateRoot.MyTestEventHandleCount); - } - - [TestMethod] - public void UncommittedEventsAreInsertedIntoTheEventStoreWhenSaved() - { - var repository = CreateDomainRepository(); - var aggregateRoot = new MyTestAggregateRoot(); - var domainEvents = new List {new MyTestEvent(), new MyTestEvent(), new MyTestEvent()}; - - aggregateRoot.Apply(domainEvents[0]); - aggregateRoot.Apply(domainEvents[1]); - aggregateRoot.Apply(domainEvents[2]); - - repository.Save(aggregateRoot); - - mocker.GetMock() - .Verify(eventStore => eventStore.Insert(It.Is>(events => events.All(domainEvents.Contains))), Times.Once()); - } - - [TestMethod] - public void UncommittedEventsArePublishedToTheEventBusWhenSaved() - { - var repository = CreateDomainRepository(); - var aggregateRoot = new MyTestAggregateRoot(); - var domainEvents = new List {new MyTestEvent(), new MyTestEvent(), new MyTestEvent()}; - - aggregateRoot.Apply(domainEvents[0]); - aggregateRoot.Apply(domainEvents[1]); - aggregateRoot.Apply(domainEvents[2]); - - repository.Save(aggregateRoot); - - mocker.GetMock() - .Verify(eventBus => eventBus.PublishEvents(It.IsAny>()), Times.Once()); - } - - [TestMethod] - public void UncommittedEventsShouldBeCommited() - { - var repository = CreateDomainRepository(); - var aggregateRoot = new MyTestAggregateRoot(); - - aggregateRoot.Apply(new MyTestEvent()); - aggregateRoot.Apply(new MyTestEvent()); - - repository.Save(aggregateRoot); - - Assert.AreEqual(0, aggregateRoot.UncommittedEvents.Count); - } - - [TestMethod] - public void GettingExistingByIdThrowsExceptionWhenNotFound() - { - var eventStore = new Mock().Object; - var snapshotStore = new Mock().Object; - var eventBus = new Mock().Object; - var repository = new DomainRepository(eventStore, snapshotStore, eventBus); - var aggregateRootId = Guid.NewGuid(); - - var exception = CustomAsserts.Throws(() => - repository.GetExistingById(aggregateRootId) - ); - - Assert.AreEqual(aggregateRootId, exception.AggregateRootId); - Assert.AreEqual(typeof(MyTestAggregateRoot), exception.Type); - } - - [TestMethod] - public void GettingExistingByIdReturnsAggregateWhenFound() - { - var aggregateRootId = Guid.NewGuid(); - - var eventStore = new Mock(); - eventStore.Setup(x => x.GetEvents(aggregateRootId, It.IsAny())).Returns(new[] { new MyTestEvent() }); - var snapshotStore = new Mock().Object; - var eventBus = new Mock().Object; - var repository = new DomainRepository(eventStore.Object, snapshotStore, eventBus); - - var fetchedAggregateRoot = repository.GetExistingById(aggregateRootId); - - Assert.IsNotNull(fetchedAggregateRoot); - } - - private DomainRepository CreateDomainRepository() - { - return mocker.Resolve(); - } - - public class MyTestAggregateRoot : AggregateRoot - { - public int MyTestEventHandleCount { get; set; } - public List EventIds { get; set; } - - public MyTestAggregateRoot() - { - EventIds = new List(); - } - - private void OnMyTest(MyTestEvent myTestEvent) - { - MyTestEventHandleCount++; - EventIds.Add(myTestEvent.Sequence); - } - } - - public class MyTestEvent : DomainEvent - { - } - } -} \ No newline at end of file diff --git a/src/Tests/SimpleCqrs.Tests/Domain/EntityTests.cs b/src/Tests/SimpleCqrs.Tests/Domain/EntityTests.cs deleted file mode 100644 index e2aef53..0000000 --- a/src/Tests/SimpleCqrs.Tests/Domain/EntityTests.cs +++ /dev/null @@ -1,185 +0,0 @@ -using System; -using System.Collections.Generic; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using SimpleCqrs.Domain; -using SimpleCqrs.Eventing; -using SimpleCqrs.Testing; - -namespace SimpleCqrs.Core.Tests.Domain -{ - [TestClass] - public class EntityTests - { - private Mock mockEntity; - - [TestInitialize] - public void SetupMockForAllTests() - { - mockEntity = new Mock(new Guid()) { CallBase = true }; - } - - [TestMethod] - public void HandlerIsCalledWhenHandlerMeetsTheConventionAndEventIsApplied() - { - var domainEvent = new EntityHandlerThatMeetsConventionEvent(); - var entity = mockEntity.Object; - entity.TurnTestModeOn(); - - entity.Apply(domainEvent); - - mockEntity.Verify(ar => ar.OnEntityHandlerThatMeetsConvention(domainEvent), Times.Once()); - } - - [TestMethod] - public void HandlerIsNotCalledWhenHandlerDoesNotMeetTheConventionAndEventIsApplied() - { - var domainEvent = new EntityHandlerThatMeetsConventionEvent(); - var entity = mockEntity.Object; - entity.TurnTestModeOn(); - - entity.Apply(domainEvent); - - mockEntity.Verify(ar => ar.OnEntityHandlerThatDoesNotMeetsConvention(domainEvent), Times.Never()); - } - - [TestMethod] - public void HandlerIsNotCalledWhenHandlerHasTwoParametersAndEventIsApplied() - { - var domainEvent = new EntityHandlerThatMeetsConventionEvent(); - var entity = mockEntity.Object; - entity.TurnTestModeOn(); - - entity.Apply(domainEvent); - - mockEntity.Verify(ar => ar.OnEntityHandlerThatMeetsConvention(domainEvent, "test"), Times.Never()); - } - - [TestMethod] - public void HandlerIsCalledWhenHandlerIsPrivateAndEventIsApplied() - { - var domainEvent = new EntityPrivateHandlerThatMeetsConventionEvent(); - var entity = new MyEntity(new Guid()); - entity.TurnTestModeOn(); - - entity.Apply(domainEvent); - - Assert.IsTrue(entity.OnEntityPrivateHandlerThatMeetsConventionCalled); - } - - [TestMethod] - public void HandlerIsCalledWhenHandlerIsProtectedAndEventIsApplied() - { - var domainEvent = new EntityProtectedHandlerThatMeetsConventionEvent(); - var entity = new MyEntity(new Guid()); - entity.TurnTestModeOn(); - - entity.Apply(domainEvent); - - Assert.IsTrue(entity.OnEntityProtectedHandlerThatMeetsConventionCalled); - } - - [TestMethod] - public void When_an_event_is_applied_to_the_entity_the_event_is_added_to_the_uncommittedevents() - { - var entityId = Guid.NewGuid(); - var entity = new MyEntity(entityId); - entity.AggregateRoot = new MyAggregateRoot(); - entity.TurnTestModeOn(); - - var entityCreatedEvent = new MyEntityCreatedEvent(); - - entity.Apply(entityCreatedEvent); - - Assert.AreSame(entity.UncommittedEvents[0], entityCreatedEvent); - } - - [TestMethod] - public void When_an_event_is_applied_to_the_entity_the_event_is_applied_to_the_aggregate_root() - { - var entityId = Guid.NewGuid(); - var entity = new MyEntity(entityId); - entity.AggregateRoot = new MyAggregateRoot(); - entity.TurnTestModeOn(); - - entity.Apply(new MyEntityCreatedEvent()); - - Assert.AreEqual(entity.UncommittedEvents[0].EntityId, entityId); - } - - [TestMethod] - [ExpectedException(typeof(NullReferenceException))] - public void If_test_mode_is_off_an_null_reference_exception_is_thrown_when_an_event_is_applied() - { - var entityId = Guid.NewGuid(); - var entity = new MyEntity(entityId); - entity.TurnTestModeOff(); - - entity.Apply(new MyEntityCreatedEvent()); - } - - [TestMethod] - public void EntityId_is_set_on_applied_events() - { - var entityId = Guid.NewGuid(); - var entity = new MyEntity(entityId); - entity.TurnTestModeOn(); - - entity.Apply(new MyEntityCreatedEvent()); - - Assert.AreEqual(entity.UncommittedEvents[0].EntityId, entityId); - } - - public class MyEntity : Entity - { - public List EventIds { get; private set; } - public bool OnEntityPrivateHandlerThatMeetsConventionCalled { get; set; } - public bool OnEntityProtectedHandlerThatMeetsConventionCalled { get; set; } - - public MyEntity(Guid entityId) - { - EventIds = new List(); - Id = entityId; - } - - public virtual void OnEntityHandlerThatMeetsConvention(EntityHandlerThatMeetsConventionEvent domainEvent) - { - EventIds.Add(domainEvent.Sequence); - } - - public virtual void OnEntityHandlerThatDoesNotMeetsConvention(EntityHandlerThatMeetsConventionEvent domainEvent) - { - } - - public virtual void OnEntityHandlerThatMeetsConvention(EntityHandlerThatMeetsConventionEvent domainEvent, string test) - { - } - - private void OnEntityPrivateHandlerThatMeetsConvention(EntityPrivateHandlerThatMeetsConventionEvent domainEvent) - { - OnEntityPrivateHandlerThatMeetsConventionCalled = true; - } - - protected void OnEntityProtectedHandlerThatMeetsConvention(EntityProtectedHandlerThatMeetsConventionEvent domainEvent) - { - OnEntityProtectedHandlerThatMeetsConventionCalled = true; - } - } - - public class MyEntityCreatedEvent : EntityDomainEvent - { - } - - public class EntityHandlerThatMeetsConventionEvent : EntityDomainEvent - { - } - - public class EntityPrivateHandlerThatMeetsConventionEvent : EntityDomainEvent - { - } - - public class EntityProtectedHandlerThatMeetsConventionEvent : EntityDomainEvent - { - } - } -} \ No newline at end of file diff --git a/src/Tests/SimpleCqrs.Tests/Events/DirectEventBusTests.cs b/src/Tests/SimpleCqrs.Tests/Events/DirectEventBusTests.cs deleted file mode 100644 index c3ff5ae..0000000 --- a/src/Tests/SimpleCqrs.Tests/Events/DirectEventBusTests.cs +++ /dev/null @@ -1,210 +0,0 @@ -using System; -using System.Collections.Generic; -using AutoMoq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using SimpleCqrs.Eventing; - -namespace SimpleCqrs.Core.Tests.Events -{ - [TestClass] - public class DirectEventBusTests - { - private AutoMoqer mocker; - - [TestInitialize] - public void SetupMocksForAllTests() - { - mocker = new AutoMoqer(); - } - - [TestMethod] - public void DomainEventHandlerForMyTestEventIsCalledWhenHandlerTypeIsInTypeCatalog() - { - mocker.GetMock() - .Setup(factory => factory.Create(It.IsAny())) - .Returns((Type type) => Activator.CreateInstance(type)); - - mocker.GetMock() - .Setup(typeCatalog => typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleDomainEvents<>))) - .Returns(new[] { typeof(MyTestEventHandler) }); - - var eventBus = CreateLocalEventBus(); - var myTestEvent = new MyTestEvent(); - - eventBus.PublishEvent(myTestEvent); - - Assert.AreEqual(101, myTestEvent.Result); - } - - [TestMethod] - public void DomainEventHandlerThatImplementsTwoHandlersAreCalledWhenHandlerTypeIsInTypeCatalog() - { - mocker.GetMock() - .Setup(factory => factory.Create(It.IsAny())) - .Returns((Type type) => Activator.CreateInstance(type)); - - mocker.GetMock() - .Setup(typeCatalog => typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleDomainEvents<>))) - .Returns(new[] { typeof(MyTest2EventHandler) }); - - var eventBus = CreateLocalEventBus(); - var myTestEvent = new MyTestEvent(); - var myTest2Event = new MyTest2Event(); - - eventBus.PublishEvents(new DomainEvent[] { myTestEvent, myTest2Event }); - - Assert.AreEqual(102, myTestEvent.Result); - Assert.AreEqual(45, myTest2Event.Result); - } - - [TestMethod] - public void AllEventHandlersAreCalledWhenHandlerTypesAreInTheTypeCatalog() - { - mocker.GetMock() - .Setup(factory => factory.Create(It.IsAny())) - .Returns((Type type) => Activator.CreateInstance(type)); - - mocker.GetMock() - .Setup(typeCatalog => typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleDomainEvents<>))) - .Returns(new[] { typeof(MyTestEventHandler), typeof(MyTest2EventHandler) }); - - var eventBus = CreateLocalEventBus(); - var myTestEvent = new MyTestEvent(); - - eventBus.PublishEvent(myTestEvent); - - Assert.IsTrue(myTestEvent.MyTestEventHandlerWasCalled); - Assert.IsTrue(myTestEvent.MyTest2EventHandlerWasCalled); - } - - private LocalEventBus CreateLocalEventBus() - { - var typeCatalog = mocker.Resolve(); - var factory = mocker.Resolve(); - var eventHandlerTypes = typeCatalog.GetGenericInterfaceImplementations(typeof(IHandleDomainEvents<>)); - - return new LocalEventBus(eventHandlerTypes, factory); - } - } - - public class MyTestEventHandler : IHandleDomainEvents - { - public void Handle(MyTestEvent domainEvent) - { - domainEvent.Result = 101; - domainEvent.MyTestEventHandlerWasCalled = true; - } - } - - public class MyTest2EventHandler : IHandleDomainEvents, IHandleDomainEvents - { - public void Handle(MyTest2Event domainEvent) - { - domainEvent.Result = 45; - } - - public void Handle(MyTestEvent domainEvent) - { - domainEvent.Result = 102; - domainEvent.MyTest2EventHandlerWasCalled = true; - } - } - - public class MyTestEvent : DomainEvent - { - public virtual int Result { get; set; } - public bool MyTestEventHandlerWasCalled { get; set; } - public bool MyTest2EventHandlerWasCalled { get; set; } - } - - public class MyTest2Event : DomainEvent - { - public int Result { get; set; } - } - - public class MockServiceLocator : IServiceLocator - { - public void Dispose() - { - throw new NotImplementedException(); - } - - public T Resolve() where T : class - { - throw new NotImplementedException(); - } - - public T Resolve(string key) where T : class - { - throw new NotImplementedException(); - } - - public Func ResolveFunc { get; set; } - - public object Resolve(Type type) - { - return ResolveFunc(type); - } - - public IList ResolveServices() where T : class - { - throw new NotImplementedException(); - } - - public void Register(Type implType) where TInterface : class - { - throw new NotImplementedException(); - } - - public void Register() where TImplementation : class, TInterface - { - throw new NotImplementedException(); - } - - public void Register(string key) where TImplementation : class, TInterface - { - throw new NotImplementedException(); - } - - public void Register(string key, Type type) - { - throw new NotImplementedException(); - } - - public void Register(Type serviceType, Type implType) - { - throw new NotImplementedException(); - } - - public void Register(TInterface instance) where TInterface : class - { - throw new NotImplementedException(); - } - - public void Release(object instance) - { - throw new NotImplementedException(); - } - - public void Reset() - { - throw new NotImplementedException(); - } - - public TService Inject(TService instance) where TService : class - { - throw new NotImplementedException(); - } - - public void TearDown(TService instance) where TService : class - { - throw new NotImplementedException(); - } - - public void Register(Func factoryMethod) where Interface : class - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/src/Tests/SimpleCqrs.Tests/Properties/AssemblyInfo.cs b/src/Tests/SimpleCqrs.Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index 3277c94..0000000 --- a/src/Tests/SimpleCqrs.Tests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +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("SimpleCqrs.Core.Tests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("DEG")] -[assembly: AssemblyProduct("SimpleCqrs.Core.Tests")] -[assembly: AssemblyCopyright("Copyright © DEG 2010")] -[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("0c55a564-940c-4f87-bf91-ebfd87108ef5")] - -// 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.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Tests/SimpleCqrs.Tests/SimpleCqrs.Tests.csproj b/src/Tests/SimpleCqrs.Tests/SimpleCqrs.Tests.csproj deleted file mode 100644 index 5943b8f..0000000 --- a/src/Tests/SimpleCqrs.Tests/SimpleCqrs.Tests.csproj +++ /dev/null @@ -1,77 +0,0 @@ - - - - Debug - AnyCPU - - - 2.0 - {6AEAEE90-CF43-47CE-BD60-9F9519120BC6} - Library - Properties - SimpleCqrs.Core.Tests - SimpleCqrs.Core.Tests - v4.0 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\lib\AutoMoq.dll - - - - - - 3.5 - - - - - False - - - - - - - - - - - - - - - - {E04C12B5-A6D3-4D64-9F38-896BEE68162E} - SimpleCqrs - - - - - - \ No newline at end of file diff --git a/tools/Simple-CQRS Visual Studio Extensions/Simple-CQRS Visual Studio Extensions.sln b/tools/Simple-CQRS Visual Studio Extensions/Simple-CQRS Visual Studio Extensions.sln deleted file mode 100644 index c7a2107..0000000 --- a/tools/Simple-CQRS Visual Studio Extensions/Simple-CQRS Visual Studio Extensions.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleCqrs.VisualStudio.Extensions", "SimpleCqrs.VisualStudio.Extensions\SimpleCqrs.VisualStudio.Extensions.csproj", "{01404D42-9C36-4AFB-BBDD-B31CD3C8E5FC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {01404D42-9C36-4AFB-BBDD-B31CD3C8E5FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {01404D42-9C36-4AFB-BBDD-B31CD3C8E5FC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {01404D42-9C36-4AFB-BBDD-B31CD3C8E5FC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {01404D42-9C36-4AFB-BBDD-B31CD3C8E5FC}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/GlobalSuppressions.cs b/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/GlobalSuppressions.cs deleted file mode 100644 index 15f47e2..0000000 --- a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/GlobalSuppressions.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")] \ No newline at end of file diff --git a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Guids.cs b/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Guids.cs deleted file mode 100644 index deb2235..0000000 --- a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Guids.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace SimpleCqrs.VisualStudio.Extensions -{ - static class Guids - { - public const string GuidSimpleCqrsPkgString = "d846aad1-bc98-4a9f-9303-b17509457dbc"; - public const string GuidSimpleCqrsCmdSetString = "67f09cb0-3702-4855-b37b-4e494c699d30"; - public static readonly Guid GuidSimpleCqrsCmdSet = new Guid(GuidSimpleCqrsCmdSetString); - }; -} \ No newline at end of file diff --git a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Key.snk b/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Key.snk deleted file mode 100644 index 7c24176..0000000 Binary files a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Key.snk and /dev/null differ diff --git a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Properties/AssemblyInfo.cs b/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Properties/AssemblyInfo.cs deleted file mode 100644 index 74062bf..0000000 --- a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Reflection; -using System.Resources; -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("SimpleCqrs.VisualStudio.Extensions")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Tyrone Groves")] -[assembly: AssemblyProduct("SimpleCqrs.VisualStudio.Extensions")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] -[assembly: ComVisible(false)] -[assembly: CLSCompliant(false)] -[assembly: NeutralResourcesLanguage("en-US")] - -// 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 Revision and Build Numbers -// by using the '*' as shown below: - -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] - - - diff --git a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Resources.Designer.cs b/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Resources.Designer.cs deleted file mode 100644 index 3663e98..0000000 --- a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Resources.Designer.cs +++ /dev/null @@ -1,63 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.1 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace SimpleCqrs.VisualStudio.Extensions { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SimpleCqrs.VisualStudio.Extensions.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - } -} diff --git a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Resources.resx b/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Resources.resx deleted file mode 100644 index 891c592..0000000 --- a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Resources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Resources/Package.ico b/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Resources/Package.ico deleted file mode 100644 index ea3b23f..0000000 Binary files a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/Resources/Package.ico and /dev/null differ diff --git a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/SimpleCqrs.VisualStudio.Extensions.csproj b/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/SimpleCqrs.VisualStudio.Extensions.csproj deleted file mode 100644 index dfcef02..0000000 --- a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/SimpleCqrs.VisualStudio.Extensions.csproj +++ /dev/null @@ -1,156 +0,0 @@ - - - - Debug - AnyCPU - 2.0 - {01404D42-9C36-4AFB-BBDD-B31CD3C8E5FC} - {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Library - Properties - SimpleCqrs.VisualStudio.Extensions - SimpleCqrs.VisualStudio.Extensions - True - Key.snk - v4.0 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - true - - - - - - - - - - - false - - - - - - - - - - - - - {80CC9F66-E7D8-4DDD-85B6-D9E6CD0E93E2} - 8 - 0 - 0 - primary - False - False - - - {26AD1324-4B7C-44BC-84F8-B86AED45729F} - 10 - 0 - 0 - primary - False - False - - - {1A31287A-4D7D-413E-8E32-3B374931BD89} - 8 - 0 - 0 - primary - False - False - - - {2CE2370E-D744-4936-A090-3FFFE667B0E1} - 9 - 0 - 0 - primary - False - False - - - {1CBA492E-7263-47BB-87FE-639000619B15} - 8 - 0 - 0 - primary - False - False - - - {00020430-0000-0000-C000-000000000046} - 2 - 0 - 0 - primary - False - False - - - - - - True - True - Resources.resx - - - - - - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - true - VSPackage - - - - - Designer - - - - - - - - - - true - - - - - \ No newline at end of file diff --git a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/SimpleCqrsPackage.cs b/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/SimpleCqrsPackage.cs deleted file mode 100644 index fd93166..0000000 --- a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/SimpleCqrsPackage.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Diagnostics; -using System.Globalization; -using System.Runtime.InteropServices; -using Microsoft.VisualStudio.Shell; - -namespace SimpleCqrs.VisualStudio.Extensions -{ - [PackageRegistration(UseManagedResourcesOnly = true)] - [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)] - [Guid(Guids.GuidSimpleCqrsPkgString)] - public sealed class SimpleCqrsPackage : Package - { - public SimpleCqrsPackage() - { - Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", ToString())); - } - - protected override void Initialize() - { - Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", ToString())); - base.Initialize(); - } - } -} \ No newline at end of file diff --git a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/VSPackage.resx b/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/VSPackage.resx deleted file mode 100644 index 9cf7e53..0000000 --- a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/VSPackage.resx +++ /dev/null @@ -1,140 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - SimpleCqrs.VisualStudio.Extensions - - - The Simple-CQRS Visual Studio Extensions assists architects and developers creating applications that uses the CQRS and Event Sourcing design patterns. - - - Resources\Package.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - \ No newline at end of file diff --git a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/source.extension.vsixmanifest b/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/source.extension.vsixmanifest deleted file mode 100644 index f1ce631..0000000 --- a/tools/Simple-CQRS Visual Studio Extensions/SimpleCqrs.VisualStudio.Extensions/source.extension.vsixmanifest +++ /dev/null @@ -1,25 +0,0 @@ - - - - Simple-CQRS Visual Studio Extensions - Tyrone Groves - 1.0 - The Simple-CQRS Visual Studio Extensions assists architects and developers creating applications that uses the CQRS and Event Sourcing design patterns. - 1033 - false - - - Pro - - - - - - - Visual Studio MPF - - - - |%CurrentProject%;PkgdefProjectOutputGroup| - -