├── .gitattributes ├── .gitignore ├── LICENSE ├── Orleans.EventSourcing ├── EventSourcing │ ├── AggregateGrainBase.cs │ ├── EventSourcing.csproj │ ├── IAggregateState.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── StateTransformer.cs ├── EventStoreStorage │ ├── EventStoreProvider.cs │ ├── EventStoreStorage.csproj │ ├── Exceptions │ │ └── NotAggregateStateException.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── packages.config ├── Orleans.EventSourcing.sln ├── Test.Client │ ├── App.config │ ├── DevTestClientConfiguration.xml │ ├── DevTestServerConfiguration.xml │ ├── OrleansHostWrapper.cs │ ├── Program.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── Test.Client.csproj ├── Test.Implementation │ ├── Person.cs │ ├── PersonEvents.cs │ ├── Properties │ │ ├── AssemblyInfo.cs │ │ └── orleans.codegen.cs │ └── Test.Implementation.csproj └── Test.Interfaces │ ├── IPerson.cs │ ├── Properties │ ├── AssemblyInfo.cs │ └── orleans.codegen.cs │ └── Test.Interfaces.csproj └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * -text 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | # Build results 10 | [Dd]ebug/ 11 | [Dd]ebugPublic/ 12 | [Rr]elease/ 13 | x64/ 14 | build/ 15 | bld/ 16 | [Bb]in/ 17 | [Oo]bj/ 18 | 19 | # MSTest test Results 20 | [Tt]est[Rr]esult*/ 21 | [Bb]uild[Ll]og.* 22 | 23 | #NUNIT 24 | *.VisualState.xml 25 | TestResult.xml 26 | 27 | # Build Results of an ATL Project 28 | [Dd]ebugPS/ 29 | [Rr]eleasePS/ 30 | dlldata.c 31 | 32 | *_i.c 33 | *_p.c 34 | *_i.h 35 | *.ilk 36 | *.meta 37 | *.obj 38 | *.pch 39 | *.pdb 40 | *.pgc 41 | *.pgd 42 | *.rsp 43 | *.sbr 44 | *.tlb 45 | *.tli 46 | *.tlh 47 | *.tmp 48 | *.tmp_proj 49 | *.log 50 | *.vspscc 51 | *.vssscc 52 | .builds 53 | *.pidb 54 | *.svclog 55 | *.scc 56 | 57 | # Chutzpah Test files 58 | _Chutzpah* 59 | 60 | # Visual C++ cache files 61 | ipch/ 62 | *.aps 63 | *.ncb 64 | *.opensdf 65 | *.sdf 66 | *.cachefile 67 | 68 | # Visual Studio profiler 69 | *.psess 70 | *.vsp 71 | *.vspx 72 | 73 | # TFS 2012 Local Workspace 74 | $tf/ 75 | 76 | # Guidance Automation Toolkit 77 | *.gpState 78 | 79 | # ReSharper is a .NET coding add-in 80 | _ReSharper*/ 81 | *.[Rr]e[Ss]harper 82 | *.DotSettings.user 83 | 84 | # JustCode is a .NET coding addin-in 85 | .JustCode 86 | 87 | # TeamCity is a build add-in 88 | _TeamCity* 89 | 90 | # DotCover is a Code Coverage Tool 91 | *.dotCover 92 | 93 | # NCrunch 94 | *.ncrunch* 95 | _NCrunch_* 96 | .*crunch*.local.xml 97 | 98 | # MightyMoose 99 | *.mm.* 100 | AutoTest.Net/ 101 | 102 | # Web workbench (sass) 103 | .sass-cache/ 104 | 105 | # Installshield output folder 106 | [Ee]xpress/ 107 | 108 | # DocProject is a documentation generator add-in 109 | DocProject/buildhelp/ 110 | DocProject/Help/*.HxT 111 | DocProject/Help/*.HxC 112 | DocProject/Help/*.hhc 113 | DocProject/Help/*.hhk 114 | DocProject/Help/*.hhp 115 | DocProject/Help/Html2 116 | DocProject/Help/html 117 | 118 | # Click-Once directory 119 | publish/ 120 | 121 | # Publish Web Output 122 | *.[Pp]ublish.xml 123 | *.azurePubxml 124 | 125 | # NuGet Packages Directory 126 | packages/ 127 | ## TODO: If the tool you use requires repositories.config uncomment the next line 128 | #!packages/repositories.config 129 | 130 | # Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets 131 | # This line needs to be after the ignore of the build folder (and the packages folder if the line above has been uncommented) 132 | !packages/build/ 133 | 134 | # Windows Azure Build Output 135 | csx/ 136 | *.build.csdef 137 | 138 | # Windows Store app package directory 139 | AppPackages/ 140 | 141 | # Others 142 | sql/ 143 | *.Cache 144 | ClientBin/ 145 | [Ss]tyle[Cc]op.* 146 | ~$* 147 | *~ 148 | *.dbmdl 149 | *.dbproj.schemaview 150 | *.pfx 151 | *.publishsettings 152 | node_modules/ 153 | 154 | # RIA/Silverlight projects 155 | Generated_Code/ 156 | 157 | # Backup & report files from converting an old project file to a newer 158 | # Visual Studio version. Backup files are not needed, because we have git ;-) 159 | _UpgradeReport_Files/ 160 | Backup*/ 161 | UpgradeLog*.XML 162 | UpgradeLog*.htm 163 | 164 | # SQL Server files 165 | *.mdf 166 | *.ldf 167 | 168 | # Business Intelligence projects 169 | *.rdl.data 170 | *.bim.layout 171 | *.bim_*.settings 172 | 173 | # Microsoft Fakes 174 | FakesAssemblies/ 175 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/EventSourcing/AggregateGrainBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Orleans.EventSourcing 8 | { 9 | public abstract class AggregateGrainBase : Grain 10 | where S : class, IAggregateState 11 | { 12 | protected Task RaiseEvent(dynamic @event, bool store = true) 13 | { 14 | this.State.UncommitedEvents.Add(@event); 15 | 16 | StateTransformer.ApplyEvent(@event, this.State); 17 | 18 | return store 19 | ? this.State.WriteStateAsync() 20 | : TaskDone.Done; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/EventSourcing/EventSourcing.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {F5673D05-C7E1-42F0-B012-6A6398936609} 8 | Library 9 | Properties 10 | Orleans.EventSourcing 11 | Orleans.EventSourcing 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | $(OrleansSDK)\Binaries\OrleansServer\Orleans.dll 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 58 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/EventSourcing/IAggregateState.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Orleans.EventSourcing 8 | { 9 | public interface IAggregateState : IGrainState 10 | { 11 | List UncommitedEvents { get; set; } 12 | int Version { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/EventSourcing/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("EventSourcing")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("EventSourcing")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("0b3c37c6-3279-48f6-bbd7-0c37ec0ffbe4")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/EventSourcing/StateTransformer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Orleans.EventSourcing 8 | { 9 | public static class StateTransformer 10 | { 11 | public static void ApplyEvent(dynamic @event, IAggregateState grainState) 12 | { 13 | dynamic state = grainState; 14 | @event.Apply(state); 15 | 16 | grainState.Version++; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/EventStoreStorage/EventStoreProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Net.Sockets; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using EventStore.ClientAPI; 10 | using EventStore.ClientAPI.Exceptions; 11 | using EventStore.ClientAPI.SystemData; 12 | using Newtonsoft.Json; 13 | using Newtonsoft.Json.Linq; 14 | using Orleans.CodeGeneration; 15 | using Orleans.EventSourcing.EventStoreStorage.Exceptions; 16 | using Orleans.Runtime; 17 | using Orleans.Storage; 18 | 19 | namespace Orleans.EventSourcing.EventStoreStorage 20 | { 21 | public class EventStoreProvider : IStorageProvider 22 | { 23 | private IEventStoreConnection Connection; 24 | 25 | private const int WritePageSize = 500; 26 | private const int ReadPageSize = 500; 27 | 28 | private static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None }; 29 | 30 | public string Name { get; private set; } 31 | public OrleansLogger Log { get; private set; } 32 | 33 | public Task Init(string name, Orleans.Providers.IProviderRuntime providerRuntime, Orleans.Providers.IProviderConfiguration config) 34 | { 35 | this.Name = name; 36 | this.Log = providerRuntime.GetLogger(this.GetType().FullName, Logger.LoggerType.Application); 37 | 38 | // Create EventStore connection 39 | var username = config.Properties.ContainsKey("Username") ? config.Properties["Username"] : "admin"; 40 | var password = config.Properties.ContainsKey("Password") ? config.Properties["Password"] : "changeit"; 41 | 42 | var settings = ConnectionSettings.Create() 43 | .KeepReconnecting().KeepRetrying() 44 | .SetDefaultUserCredentials(new UserCredentials(username, password)); 45 | 46 | // Connection string format: : 47 | var connectionStringParts = config.Properties["ConnectionString"].Split(':'); 48 | var hostName = connectionStringParts[0]; 49 | var hostPort = int.Parse(connectionStringParts[1]); 50 | var hostAddress = Dns.GetHostAddresses(hostName).First(a => a.AddressFamily == AddressFamily.InterNetwork); 51 | 52 | this.Connection = EventStoreConnection.Create(settings, new IPEndPoint(hostAddress, hostPort)); 53 | 54 | // Connect to EventStore 55 | return this.Connection.ConnectAsync(); 56 | } 57 | 58 | public Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) 59 | { 60 | if (!(grainState is IAggregateState)) 61 | throw new NotAggregateStateException(grainState.GetType()); 62 | 63 | var state = grainState as IAggregateState; 64 | var stream = this.GetStreamName(grainType, grainReference); 65 | 66 | return this.Connection.DeleteStreamAsync(stream, state.Version); 67 | } 68 | 69 | public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) 70 | { 71 | if (!(grainState is IAggregateState)) 72 | throw new NotAggregateStateException(grainState.GetType()); 73 | 74 | var stream = this.GetStreamName(grainType, grainReference); 75 | 76 | var sliceStart = 0; 77 | StreamEventsSlice currentSlice; 78 | 79 | do 80 | { 81 | var sliceCount = sliceStart + ReadPageSize; 82 | 83 | currentSlice = await this.Connection.ReadStreamEventsForwardAsync(stream, sliceStart, sliceCount, true); 84 | 85 | if (currentSlice.Status == SliceReadStatus.StreamNotFound) 86 | return; 87 | 88 | if (currentSlice.Status == SliceReadStatus.StreamDeleted) 89 | throw new StreamDeletedException(); 90 | 91 | sliceStart = currentSlice.NextEventNumber; 92 | 93 | foreach (var @event in currentSlice.Events) 94 | { 95 | dynamic deserialisedEvent = DeserializeEvent(@event.Event); 96 | StateTransformer.ApplyEvent(deserialisedEvent, grainState as IAggregateState); 97 | } 98 | 99 | } while (!currentSlice.IsEndOfStream); 100 | } 101 | 102 | public async Task WriteStateAsync(string grainType, GrainReference grainReference, Orleans.IGrainState grainState) 103 | { 104 | if (!(grainState is IAggregateState)) 105 | throw new NotAggregateStateException(grainState.GetType()); 106 | 107 | var state = grainState as IAggregateState; 108 | var stream = this.GetStreamName(grainType, grainReference); 109 | 110 | var newEvents = state.UncommitedEvents; 111 | 112 | if (newEvents.Count == 0) 113 | return; 114 | 115 | var originalVersion = state.Version - newEvents.Count - 1; 116 | var expectedVersion = originalVersion == -1 ? ExpectedVersion.NoStream : originalVersion; 117 | var eventsToSave = newEvents.Select(e => ToEventData(e)).ToList(); 118 | 119 | if (eventsToSave.Count < WritePageSize) 120 | { 121 | await this.Connection.AppendToStreamAsync(stream, expectedVersion, eventsToSave.ToArray()); 122 | } 123 | else 124 | { 125 | var transaction = await this.Connection.StartTransactionAsync(stream, expectedVersion); 126 | 127 | var position = 0; 128 | while (position < eventsToSave.Count) 129 | { 130 | var pageEvents = eventsToSave.Skip(position).Take(WritePageSize); 131 | await transaction.WriteAsync(pageEvents); 132 | position += WritePageSize; 133 | } 134 | 135 | await transaction.CommitAsync(); 136 | } 137 | 138 | state.UncommitedEvents.Clear(); 139 | } 140 | 141 | public Task Close() 142 | { 143 | this.Connection.Close(); 144 | 145 | return TaskDone.Done; 146 | } 147 | 148 | // TODO: Create extension point here 149 | private string GetStreamName(string grainType, GrainReference grainReference) 150 | { 151 | return string.Concat(grainType, "-", grainReference.ToKeyString()); 152 | } 153 | 154 | #region Event serialisation 155 | 156 | private static object DeserializeEvent(RecordedEvent @event) 157 | { 158 | var eventType = Type.GetType(@event.EventType); 159 | Debug.Assert(eventType != null, "Couldn't load type '{0}'. Are you missing an assembly reference?", @event.EventType); 160 | 161 | return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(@event.Data), eventType); 162 | } 163 | 164 | private static JObject DeserializeMetadata(byte[] metadata) 165 | { 166 | return JObject.Parse(Encoding.UTF8.GetString(metadata)); 167 | } 168 | 169 | private static EventData ToEventData(object processedEvent) 170 | { 171 | return ToEventData(Guid.NewGuid(), processedEvent, new Dictionary()); 172 | } 173 | 174 | private static EventData ToEventData(Guid eventId, object evnt, IDictionary headers) 175 | { 176 | var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(evnt, SerializerSettings)); 177 | var metadata = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(headers, SerializerSettings)); 178 | 179 | var eventTypeName = evnt.GetType().AssemblyQualifiedName; 180 | return new EventData(eventId, eventTypeName, true, data, metadata); 181 | } 182 | 183 | #endregion 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/EventStoreStorage/EventStoreStorage.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {98C927A9-5D60-45E1-AEC2-85E77E9D2055} 8 | Library 9 | Properties 10 | Orleans.EventSourcing.EventStoreStorage 11 | Orleans.EventSourcing.EventStoreStorage 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | $(OrleansSDK)\Binaries\OrleansServer\Orleans.dll 35 | 36 | 37 | ..\packages\EventStore.Client.3.0.0-rc2\lib\net40\EventStore.ClientAPI.dll 38 | 39 | 40 | False 41 | ..\packages\Newtonsoft.Json.6.0.3\lib\net45\Newtonsoft.Json.dll 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | {f5673d05-c7e1-42f0-b012-6a6398936609} 59 | EventSourcing 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | if exist "$(OrleansSDK)\LocalSilo" ( 68 | copy /y *.dll "$(OrleansSDK)\LocalSilo\" 69 | copy /y *.pdb "$(OrleansSDK)\LocalSilo\" 70 | ) 71 | 72 | 73 | 80 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/EventStoreStorage/Exceptions/NotAggregateStateException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Orleans.EventSourcing.EventStoreStorage.Exceptions 8 | { 9 | [Serializable] 10 | public class NotAggregateStateException : Exception 11 | { 12 | public Type StateType { get; private set; } 13 | 14 | public NotAggregateStateException(Type stateType) 15 | { 16 | this.StateType = stateType; 17 | } 18 | 19 | protected NotAggregateStateException( 20 | System.Runtime.Serialization.SerializationInfo info, 21 | System.Runtime.Serialization.StreamingContext context) 22 | : base(info, context) { } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/EventStoreStorage/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("EventStoreStorage")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("EventStoreStorage")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("fde1cd99-dcb8-4011-ae09-44470805b87f")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/EventStoreStorage/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Orleans.EventSourcing.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.30110.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EventStoreStorage", "EventStoreStorage\EventStoreStorage.csproj", "{98C927A9-5D60-45E1-AEC2-85E77E9D2055}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EventSourcing", "EventSourcing\EventSourcing.csproj", "{F5673D05-C7E1-42F0-B012-6A6398936609}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test.Client", "Test.Client\Test.Client.csproj", "{8B8CE994-8B18-4FAE-904E-6D253B7E02F7}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test.Implementation", "Test.Implementation\Test.Implementation.csproj", "{09334D17-203E-455D-B6B2-36138F51044E}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test.Interfaces", "Test.Interfaces\Test.Interfaces.csproj", "{08EE195C-5936-42DE-A667-2A8DED9B281D}" 15 | EndProject 16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test Projects", "Test Projects", "{753E1742-EC0D-4DB0-8063-3712F696C84D}" 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|Any CPU = Debug|Any CPU 21 | Release|Any CPU = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 24 | {98C927A9-5D60-45E1-AEC2-85E77E9D2055}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {98C927A9-5D60-45E1-AEC2-85E77E9D2055}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {98C927A9-5D60-45E1-AEC2-85E77E9D2055}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {98C927A9-5D60-45E1-AEC2-85E77E9D2055}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {F5673D05-C7E1-42F0-B012-6A6398936609}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {F5673D05-C7E1-42F0-B012-6A6398936609}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {F5673D05-C7E1-42F0-B012-6A6398936609}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {F5673D05-C7E1-42F0-B012-6A6398936609}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {8B8CE994-8B18-4FAE-904E-6D253B7E02F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {8B8CE994-8B18-4FAE-904E-6D253B7E02F7}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {8B8CE994-8B18-4FAE-904E-6D253B7E02F7}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {8B8CE994-8B18-4FAE-904E-6D253B7E02F7}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {09334D17-203E-455D-B6B2-36138F51044E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {09334D17-203E-455D-B6B2-36138F51044E}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {09334D17-203E-455D-B6B2-36138F51044E}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {09334D17-203E-455D-B6B2-36138F51044E}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {08EE195C-5936-42DE-A667-2A8DED9B281D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {08EE195C-5936-42DE-A667-2A8DED9B281D}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {08EE195C-5936-42DE-A667-2A8DED9B281D}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {08EE195C-5936-42DE-A667-2A8DED9B281D}.Release|Any CPU.Build.0 = Release|Any CPU 44 | EndGlobalSection 45 | GlobalSection(SolutionProperties) = preSolution 46 | HideSolutionNode = FALSE 47 | EndGlobalSection 48 | GlobalSection(NestedProjects) = preSolution 49 | {08EE195C-5936-42DE-A667-2A8DED9B281D} = {753E1742-EC0D-4DB0-8063-3712F696C84D} 50 | {8B8CE994-8B18-4FAE-904E-6D253B7E02F7} = {753E1742-EC0D-4DB0-8063-3712F696C84D} 51 | {09334D17-203E-455D-B6B2-36138F51044E} = {753E1742-EC0D-4DB0-8063-3712F696C84D} 52 | EndGlobalSection 53 | EndGlobal 54 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Client/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Client/DevTestClientConfiguration.xml: -------------------------------------------------------------------------------- 1 |  2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Client/DevTestServerConfiguration.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Client/OrleansHostWrapper.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft. All rights reserved. 3 | // 4 | // Apache 2.0 License 5 | // 6 | // You may obtain a copy of the License at 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 | // implied. See the License for the specific language governing 13 | // permissions and limitations under the License. 14 | // 15 | //********************************************************* 16 | using System; 17 | using System.Net; 18 | 19 | using Orleans.Host; 20 | 21 | namespace Test.Client 22 | { 23 | internal class OrleansHostWrapper : IDisposable 24 | { 25 | public bool Debug 26 | { 27 | get { return siloHost != null && siloHost.Debug; } 28 | set { siloHost.Debug = value; } 29 | } 30 | 31 | private OrleansSiloHost siloHost; 32 | 33 | public OrleansHostWrapper(string[] args) 34 | { 35 | ParseArguments(args); 36 | Init(); 37 | } 38 | 39 | public bool Run() 40 | { 41 | bool ok = false; 42 | 43 | try 44 | { 45 | siloHost.InitializeOrleansSilo(); 46 | 47 | ok = siloHost.StartOrleansSilo(); 48 | 49 | if (ok) 50 | { 51 | Console.WriteLine(string.Format("Successfully started Orleans silo '{0}' as a {1} node.", siloHost.SiloName, siloHost.SiloType)); 52 | } 53 | else 54 | { 55 | throw new SystemException(string.Format("Failed to start Orleans silo '{0}' as a {1} node.", siloHost.SiloName, siloHost.SiloType)); 56 | } 57 | } 58 | catch (Exception exc) 59 | { 60 | siloHost.ReportStartupError(exc); 61 | var msg = string.Format("{0}:\n{1}\n{2}", exc.GetType().FullName, exc.Message, exc.StackTrace); 62 | Console.WriteLine(msg); 63 | } 64 | 65 | return ok; 66 | } 67 | 68 | public bool Stop() 69 | { 70 | bool ok = false; 71 | 72 | try 73 | { 74 | siloHost.StopOrleansSilo(); 75 | 76 | Console.WriteLine(string.Format("Orleans silo '{0}' shutdown.", siloHost.SiloName)); 77 | } 78 | catch (Exception exc) 79 | { 80 | siloHost.ReportStartupError(exc); 81 | var msg = string.Format("{0}:\n{1}\n{2}", exc.GetType().FullName, exc.Message, exc.StackTrace); 82 | Console.WriteLine(msg); 83 | } 84 | 85 | return ok; 86 | } 87 | 88 | private void Init() 89 | { 90 | siloHost.LoadOrleansConfig(); 91 | } 92 | 93 | private bool ParseArguments(string[] args) 94 | { 95 | bool debug = false; 96 | string deploymentId = null; 97 | 98 | string configFileName = "DevTestServerConfiguration.xml"; 99 | string siloName = Dns.GetHostName(); // Default to machine name 100 | 101 | int argPos = 1; 102 | for (int i = 0; i < args.Length; i++) 103 | { 104 | string a = args[i]; 105 | if (a.StartsWith("-") || a.StartsWith("/")) 106 | { 107 | switch (a.ToLowerInvariant()) 108 | { 109 | case "/?": 110 | case "/help": 111 | case "-?": 112 | case "-help": 113 | // Query usage help 114 | return false; 115 | case "/debug": 116 | debug = true; 117 | break; 118 | default: 119 | Console.WriteLine("Bad command line arguments supplied: " + a); 120 | return false; 121 | } 122 | } 123 | else if (a.Contains("=")) 124 | { 125 | string[] split = a.Split('='); 126 | if (String.IsNullOrEmpty(split[1])) 127 | { 128 | Console.WriteLine("Bad command line arguments supplied: " + a); 129 | return false; 130 | } 131 | switch (split[0].ToLowerInvariant()) 132 | { 133 | case "deploymentid": 134 | deploymentId = split[1]; 135 | break; 136 | case "deploymentgroup": 137 | // TODO: Remove this at some point in future 138 | Console.WriteLine("Ignoring deprecated command line argument: " + a); 139 | break; 140 | default: 141 | Console.WriteLine("Bad command line arguments supplied: " + a); 142 | return false; 143 | } 144 | } 145 | // unqualified arguments below 146 | else if (argPos == 1) 147 | { 148 | siloName = a; 149 | argPos++; 150 | } 151 | else if (argPos == 2) 152 | { 153 | configFileName = a; 154 | argPos++; 155 | } 156 | else 157 | { 158 | // Too many command line arguments 159 | Console.WriteLine("Too many command line arguments supplied: " + a); 160 | return false; 161 | } 162 | } 163 | 164 | siloHost = new OrleansSiloHost(siloName); 165 | siloHost.ConfigFileName = configFileName; 166 | if (deploymentId != null) 167 | siloHost.DeploymentId = deploymentId; 168 | 169 | return true; 170 | } 171 | 172 | public void PrintUsage() 173 | { 174 | Console.WriteLine( 175 | @"USAGE: 176 | OrleansHost.exe [ []] [DeploymentId=] [/debug] 177 | Where: 178 | - Name of this silo in the Config file list (optional) 179 | - Path to the Config file to use (optional) 180 | DeploymentId= 181 | - Which deployment group this host instance should run in (optional) 182 | /debug - Turn on extra debug output during host startup (optional)"); 183 | } 184 | 185 | public void Dispose() 186 | { 187 | Dispose(true); 188 | } 189 | 190 | protected virtual void Dispose(bool dispose) 191 | { 192 | siloHost.Dispose(); 193 | siloHost = null; 194 | } 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Client/Program.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft. All rights reserved. 3 | // 4 | // Apache 2.0 License 5 | // 6 | // You may obtain a copy of the License at 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 | // implied. See the License for the specific language governing 13 | // permissions and limitations under the License. 14 | // 15 | //********************************************************* 16 | using System; 17 | using Orleans; 18 | using Test.Interfaces; 19 | 20 | namespace Test.Client 21 | { 22 | /// 23 | /// Orleans test silo host 24 | /// 25 | public class Program 26 | { 27 | static void Main(string[] args) 28 | { 29 | // The Orleans environment is initialized in its own app domain in order to more 30 | // closely emulate the distributed situation, when the client and the server cannot 31 | // pass data via shared memory. 32 | AppDomain hostDomain = AppDomain.CreateDomain("OrleansHost", null, new AppDomainSetup 33 | { 34 | AppDomainInitializer = InitSilo, 35 | AppDomainInitializerArguments = args, 36 | }); 37 | 38 | Orleans.OrleansClient.Initialize("DevTestClientConfiguration.xml"); 39 | 40 | var johnGrain = PersonFactory.GetGrain(1); 41 | 42 | // If the name is set, we've run this code before. 43 | if (johnGrain.GetFirstName().Result == null) 44 | { 45 | johnGrain.Register(new PersonalAttributes { FirstName = "John", LastName = "Doe", Gender = GenderType.Male }).Wait(); 46 | Console.WriteLine("We just wrote something to the persistent store (Id: {0}). Please verify!", johnGrain.GetPrimaryKey()); 47 | } 48 | else 49 | { 50 | Console.WriteLine("\n\nThis was found in the persistent store: {0}, {1}, {2}\n\n", 51 | johnGrain.GetFirstName().Result, 52 | johnGrain.GetLastName().Result, 53 | johnGrain.GetGender().Result.ToString()); 54 | } 55 | 56 | var aliceGrain = PersonFactory.GetGrain(2); 57 | 58 | // If the name is set, we've run this code before. 59 | if (aliceGrain.GetFirstName().Result == null) 60 | { 61 | aliceGrain.Register(new PersonalAttributes { FirstName = "Alice", LastName = "Williams", Gender = GenderType.Female }).Wait(); 62 | Console.WriteLine("We just wrote something to the persistent store (Id: {0}). Please verify!", aliceGrain.GetPrimaryKey()); 63 | } 64 | else 65 | { 66 | Console.WriteLine("\n\nThis was found in the persistent store: {0}, {1}, {2}\n\n", 67 | aliceGrain.GetFirstName().Result, 68 | aliceGrain.GetLastName().Result, 69 | aliceGrain.GetGender().Result.ToString()); 70 | } 71 | 72 | aliceGrain.Marry(johnGrain).Wait(); 73 | 74 | 75 | Console.WriteLine("Alice " + aliceGrain.GetLastName().Result); 76 | 77 | 78 | var bobGrain = PersonFactory.GetGrain(3); 79 | bobGrain.Register(new PersonalAttributes { FirstName = "Bob", LastName = "Hoskins", Gender = GenderType.Male }).Wait(); 80 | 81 | aliceGrain.Marry(bobGrain).Wait(); 82 | 83 | Console.WriteLine("Alice " + aliceGrain.GetLastName().Result); 84 | 85 | Console.WriteLine("Orleans Silo is running.\nPress Enter to terminate..."); 86 | Console.ReadLine(); 87 | 88 | hostDomain.DoCallBack(ShutdownSilo); 89 | } 90 | 91 | static void InitSilo(string[] args) 92 | { 93 | hostWrapper = new OrleansHostWrapper(args); 94 | 95 | if (!hostWrapper.Run()) 96 | { 97 | Console.Error.WriteLine("Failed to initialize Orleans silo"); 98 | } 99 | } 100 | 101 | static void ShutdownSilo() 102 | { 103 | if (hostWrapper != null) 104 | { 105 | hostWrapper.Dispose(); 106 | GC.SuppressFinalize(hostWrapper); 107 | } 108 | } 109 | 110 | private static OrleansHostWrapper hostWrapper; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Client/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft. All rights reserved. 3 | // 4 | // Apache 2.0 License 5 | // 6 | // You may obtain a copy of the License at 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 | // implied. See the License for the specific language governing 13 | // permissions and limitations under the License. 14 | // 15 | //********************************************************* 16 | using System.Reflection; 17 | using System.Runtime.CompilerServices; 18 | using System.Runtime.InteropServices; 19 | 20 | // General Information about an assembly is controlled through the following 21 | // set of attributes. Change these attribute values to modify the information 22 | // associated with an assembly. 23 | [assembly: AssemblyTitle("Test.Client")] 24 | [assembly: AssemblyDescription("")] 25 | [assembly: AssemblyConfiguration("")] 26 | [assembly: AssemblyCompany("")] 27 | [assembly: AssemblyProduct("Test.Client")] 28 | [assembly: AssemblyCopyright("Copyright © 2014")] 29 | [assembly: AssemblyTrademark("")] 30 | [assembly: AssemblyCulture("")] 31 | 32 | // Setting ComVisible to false makes the types in this assembly not visible 33 | // to COM components. If you need to access a type in this assembly from 34 | // COM, set the ComVisible attribute to true on that type. 35 | [assembly: ComVisible(false)] 36 | 37 | // The following GUID is for the ID of the typelib if this project is exposed to COM 38 | [assembly: Guid("913db7ba-2c39-48e2-be91-acb9e718fdd3")] 39 | 40 | // Version information for an assembly consists of the following four values: 41 | // 42 | // Major Version 43 | // Minor Version 44 | // Build Number 45 | // Revision 46 | // 47 | // You can specify all the values or you can default the Build and Revision Numbers 48 | // by using the '*' as shown below: 49 | // [assembly: AssemblyVersion("1.0.*")] 50 | [assembly: AssemblyVersion("1.0.0.0")] 51 | [assembly: AssemblyFileVersion("1.0.0.0")] 52 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Client/Test.Client.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | 8.0.30703 7 | 2.0 8 | {8B8CE994-8B18-4FAE-904E-6D253B7E02F7} 9 | Exe 10 | Properties 11 | Test.Client 12 | Test.Client 13 | v4.5 14 | 512 15 | 16 | 17 | true 18 | full 19 | false 20 | $(OrleansSDK)\LocalSilo\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | false 25 | 26 | 27 | pdbonly 28 | true 29 | $(OrleansSDK)\LocalSilo\ 30 | TRACE 31 | prompt 32 | 4 33 | false 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | $(OrleansSDK)\Binaries\OrleansClient\Orleans.dll 49 | False 50 | 51 | 52 | $(OrleansSDK)\Binaries\OrleansServer\OrleansRuntime.dll 53 | False 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | PreserveNewest 67 | 68 | 69 | PreserveNewest 70 | Designer 71 | 72 | 73 | 74 | 75 | {09334d17-203e-455d-b6b2-36138f51044e} 76 | Test.Implementation 77 | 78 | 79 | {08ee195c-5936-42de-a667-2a8ded9b281d} 80 | Test.Interfaces 81 | 82 | 83 | 84 | 91 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Implementation/Person.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft. All rights reserved. 3 | // 4 | // Apache 2.0 License 5 | // 6 | // You may obtain a copy of the License at 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 | // implied. See the License for the specific language governing 13 | // permissions and limitations under the License. 14 | // 15 | //********************************************************* 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Linq; 19 | using System.Threading.Tasks; 20 | using System.Text; 21 | using Orleans; 22 | using Test.Interfaces; 23 | using Orleans.EventSourcing; 24 | using Orleans.Providers; 25 | 26 | namespace Test.Implementation 27 | { 28 | [StorageProvider(ProviderName = "EventStore")] 29 | public class Person : AggregateGrainBase, Test.Interfaces.IPerson 30 | { 31 | Task IPerson.Register(PersonalAttributes props) 32 | { 33 | return this.RaiseEvent(new PersonRegistered 34 | { 35 | FirstName = props.FirstName, 36 | LastName = props.LastName, 37 | Gender = props.Gender 38 | }); 39 | } 40 | 41 | async Task IPerson.Marry(IPerson spouse) 42 | { 43 | var spouseLastName = await spouse.GetLastName(); 44 | 45 | await this.RaiseEvent(new PersonMarried 46 | { 47 | SpouseId = spouse.GetPrimaryKey(), 48 | SpouseFirstName = await spouse.GetFirstName(), 49 | SpouseLastName = spouseLastName 50 | }, store: false); // We are not storing the first event here 51 | 52 | 53 | if (this.State.LastName != spouseLastName) 54 | { 55 | await this.RaiseEvent(new PersonLastNameChanged 56 | { 57 | LastName = spouseLastName 58 | }, store: false); 59 | } 60 | 61 | await this.State.WriteStateAsync(); 62 | } 63 | 64 | Task IPerson.GetFirstName() 65 | { 66 | return Task.FromResult(State.FirstName); 67 | } 68 | 69 | Task IPerson.GetLastName() 70 | { 71 | return Task.FromResult(State.LastName); 72 | } 73 | 74 | Task IPerson.GetGender() 75 | { 76 | return Task.FromResult(State.Gender); 77 | } 78 | } 79 | 80 | public interface IPersonState : IAggregateState 81 | { 82 | string FirstName { get; set; } 83 | string LastName { get; set; } 84 | GenderType Gender { get; set; } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Implementation/PersonEvents.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Orleans; 7 | using Test.Interfaces; 8 | 9 | namespace Test.Implementation 10 | { 11 | public class PersonRegistered 12 | { 13 | public string FirstName { get; set; } 14 | public string LastName { get; set; } 15 | public GenderType Gender { get; set; } 16 | 17 | public void Apply(IPersonState state) 18 | { 19 | state.FirstName = this.FirstName; 20 | state.LastName = this.LastName; 21 | state.Gender = this.Gender; 22 | } 23 | } 24 | 25 | public class PersonMarried 26 | { 27 | public Guid SpouseId { get; set; } 28 | public string SpouseFirstName { get; set; } 29 | public string SpouseLastName { get; set; } 30 | 31 | public void Apply(IPersonState state) 32 | { 33 | } 34 | } 35 | 36 | public class PersonLastNameChanged 37 | { 38 | public string LastName { get; set; } 39 | 40 | public void Apply(IPersonState state) 41 | { 42 | state.LastName = this.LastName; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Implementation/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft. All rights reserved. 3 | // 4 | // Apache 2.0 License 5 | // 6 | // You may obtain a copy of the License at 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 | // implied. See the License for the specific language governing 13 | // permissions and limitations under the License. 14 | // 15 | //********************************************************* 16 | using System.Reflection; 17 | using System.Runtime.CompilerServices; 18 | using System.Runtime.InteropServices; 19 | 20 | // General Information about an assembly is controlled through the following 21 | // set of attributes. Change these attribute values to modify the information 22 | // associated with an assembly. 23 | [assembly: AssemblyTitle("Test.Implementation")] 24 | [assembly: AssemblyDescription("")] 25 | [assembly: AssemblyConfiguration("")] 26 | [assembly: AssemblyCompany("")] 27 | [assembly: AssemblyProduct("Test.Implementation")] 28 | [assembly: AssemblyCopyright("Copyright © 2014")] 29 | [assembly: AssemblyTrademark("")] 30 | [assembly: AssemblyCulture("")] 31 | 32 | // Setting ComVisible to false makes the types in this assembly not visible 33 | // to COM components. If you need to access a type in this assembly from 34 | // COM, set the ComVisible attribute to true on that type. 35 | [assembly: ComVisible(false)] 36 | 37 | // The following GUID is for the ID of the typelib if this project is exposed to COM 38 | [assembly: Guid("ba4c73b4-d811-4940-a4a1-0ecf0fc007d6")] 39 | 40 | // Version information for an assembly consists of the following four values: 41 | // 42 | // Major Version 43 | // Minor Version 44 | // Build Number 45 | // Revision 46 | // 47 | // You can specify all the values or you can default the Build and Revision Numbers 48 | // by using the '*' as shown below: 49 | // [assembly: AssemblyVersion("1.0.*")] 50 | [assembly: AssemblyVersion("1.0.0.0")] 51 | [assembly: AssemblyFileVersion("1.0.0.0")] 52 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Implementation/Properties/orleans.codegen.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.34209 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | #if !EXCLUDE_CODEGEN 11 | #pragma warning disable 162 12 | #pragma warning disable 219 13 | #pragma warning disable 693 14 | #pragma warning disable 1591 15 | #pragma warning disable 1998 16 | 17 | namespace Test.Implementation 18 | { 19 | using System.Collections.Generic; 20 | using System.Collections; 21 | using System; 22 | using Test.Interfaces; 23 | using Orleans.CodeGeneration; 24 | using Orleans; 25 | using Orleans.EventSourcing; 26 | using System.Runtime.InteropServices; 27 | using System.Runtime.Serialization; 28 | 29 | 30 | [System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.0.970.29197")] 31 | [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute()] 32 | [SerializableAttribute()] 33 | [global::Orleans.CodeGeneration.GrainStateAttribute("Test.Implementation.Test.Implementation.Person")] 34 | public class PersonState : global::Orleans.CodeGeneration.GrainState, IPersonState 35 | { 36 | 37 | 38 | public List UncommitedEvents { get; set; } 39 | 40 | public Int32 Version { get; set; } 41 | 42 | public String FirstName { get; set; } 43 | 44 | public String LastName { get; set; } 45 | 46 | public GenderType Gender { get; set; } 47 | 48 | public override void SetAll(System.Collections.Generic.IDictionary values) 49 | { 50 | object value; 51 | if (values == null) { InitStateFields(); return; } 52 | if (values.TryGetValue("UncommitedEvents", out value)) UncommitedEvents = (List) value; 53 | if (values.TryGetValue("Version", out value)) Version = value is Int64 ? (Int32)(Int64)value : (Int32)value; 54 | if (values.TryGetValue("FirstName", out value)) FirstName = (String) value; 55 | if (values.TryGetValue("LastName", out value)) LastName = (String) value; 56 | if (values.TryGetValue("Gender", out value)) Gender = (GenderType) value; 57 | } 58 | 59 | public override System.String ToString() 60 | { 61 | return System.String.Format("PersonState( UncommitedEvents={0} Version={1} FirstName={2} LastName={3} Gender={4} )", UncommitedEvents, Version, FirstName, LastName, Gender); 62 | } 63 | 64 | public PersonState() : 65 | base("Test.Implementation.Person") 66 | { 67 | this.InitStateFields(); 68 | } 69 | 70 | public override System.Collections.Generic.IDictionary AsDictionary() 71 | { 72 | System.Collections.Generic.Dictionary result = new System.Collections.Generic.Dictionary(); 73 | result["UncommitedEvents"] = this.UncommitedEvents; 74 | result["Version"] = this.Version; 75 | result["FirstName"] = this.FirstName; 76 | result["LastName"] = this.LastName; 77 | result["Gender"] = this.Gender; 78 | return result; 79 | } 80 | 81 | private void InitStateFields() 82 | { 83 | this.UncommitedEvents = new List(); 84 | this.Version = default(Int32); 85 | this.FirstName = default(String); 86 | this.LastName = default(String); 87 | this.Gender = default(GenderType); 88 | } 89 | 90 | [global::Orleans.CodeGeneration.CopierMethodAttribute()] 91 | public static object _Copier(object original) 92 | { 93 | PersonState input = ((PersonState)(original)); 94 | return input.DeepCopy(); 95 | } 96 | 97 | [global::Orleans.CodeGeneration.SerializerMethodAttribute()] 98 | public static void _Serializer(object original, global::Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected) 99 | { 100 | PersonState input = ((PersonState)(original)); 101 | input.SerializeTo(stream); 102 | } 103 | 104 | [global::Orleans.CodeGeneration.DeserializerMethodAttribute()] 105 | public static object _Deserializer(System.Type expected, global::Orleans.Serialization.BinaryTokenStreamReader stream) 106 | { 107 | PersonState result = new PersonState(); 108 | result.DeserializeFrom(stream); 109 | return result; 110 | } 111 | } 112 | } 113 | #pragma warning restore 162 114 | #pragma warning restore 219 115 | #pragma warning restore 693 116 | #pragma warning restore 1591 117 | #pragma warning restore 1998 118 | #endif 119 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Implementation/Test.Implementation.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | 8.0.30703 7 | 2.0 8 | {09334D17-203E-455D-B6B2-36138F51044E} 9 | Library 10 | Properties 11 | Test.Implementation 12 | Test.Implementation 13 | v4.5 14 | 512 15 | 16 | 17 | Program 18 | $(OrleansSDK)\LocalSilo\OrleansHost.exe 19 | $(OrleansSDK)\LocalSilo 20 | 21 | 22 | true 23 | full 24 | false 25 | bin\Debug\ 26 | DEBUG;TRACE 27 | prompt 28 | 4 29 | 30 | 31 | pdbonly 32 | true 33 | bin\Release\ 34 | TRACE 35 | prompt 36 | 4 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | $(OrleansSDK)\Binaries\OrleansClient\Orleans.dll 48 | False 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | {f5673d05-c7e1-42f0-b012-6a6398936609} 60 | EventSourcing 61 | 62 | 63 | {98c927a9-5d60-45e1-aec2-85e77e9d2055} 64 | EventStoreStorage 65 | 66 | 67 | {08ee195c-5936-42de-a667-2a8ded9b281d} 68 | Test.Interfaces 69 | 70 | 71 | 72 | 73 | Server 74 | 75 | 76 | 77 | 78 | if exist "$(OrleansSDK)\LocalSilo" ( 79 | if not exist "$(OrleansSDK)\LocalSilo\Applications" (md "$(OrleansSDK)\LocalSilo\Applications") 80 | if not exist "$(OrleansSDK)\LocalSilo\Applications\StorageProviders.Test" (md "$(OrleansSDK)\LocalSilo\Applications\StorageProviders.Test") 81 | copy /y *.dll "$(OrleansSDK)\LocalSilo\Applications\StorageProviders.Test\" 82 | copy /y *.pdb "$(OrleansSDK)\LocalSilo\Applications\StorageProviders.Test\" 83 | ) 84 | if exist "$(OrleansSDK)\Binaries" ( 85 | if not exist "$(OrleansSDK)\Binaries\Applications" (md "$(OrleansSDK)\Binaries\Applications") 86 | if not exist "$(OrleansSDK)\Binaries\Applications\StorageProviders.Test" (md "$(OrleansSDK)\Binaries\Applications\StorageProviders.Test") 87 | copy /y *.dll "$(OrleansSDK)\Binaries\Applications\StorageProviders.Test\" 88 | copy /y *.pdb "$(OrleansSDK)\Binaries\Applications\StorageProviders.Test\" 89 | ) 90 | 91 | 92 | 96 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Interfaces/IPerson.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft. All rights reserved. 3 | // 4 | // Apache 2.0 License 5 | // 6 | // You may obtain a copy of the License at 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 | // implied. See the License for the specific language governing 13 | // permissions and limitations under the License. 14 | // 15 | //********************************************************* 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Threading.Tasks; 19 | using Orleans; 20 | 21 | namespace Test.Interfaces 22 | { 23 | public enum GenderType { Male, Female } 24 | 25 | [Serializable] 26 | public class PersonalAttributes 27 | { 28 | public string FirstName { get; set; } 29 | public string LastName { get; set; } 30 | public GenderType Gender { get; set; } 31 | } 32 | 33 | /// 34 | /// Orleans grain communication interface IPerson 35 | /// 36 | public interface IPerson : Orleans.IGrain 37 | { 38 | Task Register(PersonalAttributes person); 39 | Task Marry(IPerson spouse); 40 | 41 | Task GetFirstName(); 42 | Task GetLastName(); 43 | Task GetGender(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Interfaces/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft. All rights reserved. 3 | // 4 | // Apache 2.0 License 5 | // 6 | // You may obtain a copy of the License at 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 | // implied. See the License for the specific language governing 13 | // permissions and limitations under the License. 14 | // 15 | //********************************************************* 16 | using System.Reflection; 17 | using System.Runtime.CompilerServices; 18 | using System.Runtime.InteropServices; 19 | 20 | // General Information about an assembly is controlled through the following 21 | // set of attributes. Change these attribute values to modify the information 22 | // associated with an assembly. 23 | [assembly: AssemblyTitle("Test.Interfaces")] 24 | [assembly: AssemblyDescription("")] 25 | [assembly: AssemblyConfiguration("")] 26 | [assembly: AssemblyCompany("")] 27 | [assembly: AssemblyProduct("Test.Interfaces")] 28 | [assembly: AssemblyCopyright("Copyright © 2014")] 29 | [assembly: AssemblyTrademark("")] 30 | [assembly: AssemblyCulture("")] 31 | 32 | // Setting ComVisible to false makes the types in this assembly not visible 33 | // to COM components. If you need to access a type in this assembly from 34 | // COM, set the ComVisible attribute to true on that type. 35 | [assembly: ComVisible(false)] 36 | 37 | // The following GUID is for the ID of the typelib if this project is exposed to COM 38 | [assembly: Guid("f066b708-5554-4fde-a9f9-4b1875ec3697")] 39 | 40 | // Version information for an assembly consists of the following four values: 41 | // 42 | // Major Version 43 | // Minor Version 44 | // Build Number 45 | // Revision 46 | // 47 | // You can specify all the values or you can default the Build and Revision Numbers 48 | // by using the '*' as shown below: 49 | // [assembly: AssemblyVersion("1.0.*")] 50 | [assembly: AssemblyVersion("1.0.0.0")] 51 | [assembly: AssemblyFileVersion("1.0.0.0")] 52 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Interfaces/Properties/orleans.codegen.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.34209 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | #if !EXCLUDE_CODEGEN 11 | #pragma warning disable 162 12 | #pragma warning disable 219 13 | #pragma warning disable 693 14 | #pragma warning disable 1591 15 | #pragma warning disable 1998 16 | 17 | namespace Test.Interfaces 18 | { 19 | using System; 20 | using System.Net; 21 | using System.Runtime.Serialization; 22 | using System.Runtime.Serialization.Formatters.Binary; 23 | using System.IO; 24 | using System.Collections.Generic; 25 | using System.Reflection; 26 | using Orleans.Serialization; 27 | using Test.Interfaces; 28 | using Orleans; 29 | using Orleans.Runtime; 30 | using System.Collections; 31 | 32 | 33 | [System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.0.970.29197")] 34 | [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute()] 35 | public class PersonFactory 36 | { 37 | 38 | 39 | public static Test.Interfaces.IPerson GetGrain(long primaryKey) 40 | { 41 | return Cast(global::Orleans.CodeGeneration.GrainFactoryBase.MakeGrainReferenceInternal(typeof(Test.Interfaces.IPerson), -627797884, primaryKey)); 42 | } 43 | 44 | public static Test.Interfaces.IPerson GetGrain(long primaryKey, string grainClassNamePrefix) 45 | { 46 | return Cast(global::Orleans.CodeGeneration.GrainFactoryBase.MakeGrainReferenceInternal(typeof(Test.Interfaces.IPerson), -627797884, primaryKey, grainClassNamePrefix)); 47 | } 48 | 49 | public static Test.Interfaces.IPerson GetGrain(System.Guid primaryKey) 50 | { 51 | return Cast(global::Orleans.CodeGeneration.GrainFactoryBase.MakeGrainReferenceInternal(typeof(Test.Interfaces.IPerson), -627797884, primaryKey)); 52 | } 53 | 54 | public static Test.Interfaces.IPerson GetGrain(System.Guid primaryKey, string grainClassNamePrefix) 55 | { 56 | return Cast(global::Orleans.CodeGeneration.GrainFactoryBase.MakeGrainReferenceInternal(typeof(Test.Interfaces.IPerson), -627797884, primaryKey, grainClassNamePrefix)); 57 | } 58 | 59 | public static Test.Interfaces.IPerson Cast(global::Orleans.Runtime.IAddressable grainRef) 60 | { 61 | 62 | return PersonReference.Cast(grainRef); 63 | } 64 | 65 | [System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.0.970.29197")] 66 | [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute()] 67 | [System.SerializableAttribute()] 68 | [global::Orleans.CodeGeneration.GrainReferenceAttribute("Test.Interfaces.Test.Interfaces.IPerson")] 69 | internal class PersonReference : global::Orleans.Runtime.GrainReference, global::Orleans.Runtime.IAddressable, Test.Interfaces.IPerson 70 | { 71 | 72 | 73 | public static Test.Interfaces.IPerson Cast(global::Orleans.Runtime.IAddressable grainRef) 74 | { 75 | 76 | return (Test.Interfaces.IPerson) global::Orleans.Runtime.GrainReference.CastInternal(typeof(Test.Interfaces.IPerson), (global::Orleans.Runtime.GrainReference gr) => { return new PersonReference(gr);}, grainRef, -627797884); 77 | } 78 | 79 | protected internal PersonReference(global::Orleans.Runtime.GrainReference reference) : 80 | base(reference) 81 | { 82 | } 83 | 84 | protected internal PersonReference(SerializationInfo info, StreamingContext context) : 85 | base(info, context) 86 | { 87 | } 88 | 89 | protected override int InterfaceId 90 | { 91 | get 92 | { 93 | return -627797884; 94 | } 95 | } 96 | 97 | protected override string InterfaceName 98 | { 99 | get 100 | { 101 | return "Test.Interfaces.Test.Interfaces.IPerson"; 102 | } 103 | } 104 | 105 | [global::Orleans.CodeGeneration.CopierMethodAttribute()] 106 | public static object _Copier(object original) 107 | { 108 | PersonReference input = ((PersonReference)(original)); 109 | return ((PersonReference)(global::Orleans.Runtime.GrainReference.CopyGrainReference(input))); 110 | } 111 | 112 | [global::Orleans.CodeGeneration.SerializerMethodAttribute()] 113 | public static void _Serializer(object original, global::Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected) 114 | { 115 | PersonReference input = ((PersonReference)(original)); 116 | global::Orleans.Runtime.GrainReference.SerializeGrainReference(input, stream, expected); 117 | } 118 | 119 | [global::Orleans.CodeGeneration.DeserializerMethodAttribute()] 120 | public static object _Deserializer(System.Type expected, global::Orleans.Serialization.BinaryTokenStreamReader stream) 121 | { 122 | return PersonReference.Cast(((global::Orleans.Runtime.GrainReference)(global::Orleans.Runtime.GrainReference.DeserializeGrainReference(expected, stream)))); 123 | } 124 | 125 | public override bool IsCompatible(int interfaceId) 126 | { 127 | return (interfaceId == this.InterfaceId); 128 | } 129 | 130 | protected override string GetMethodName(int interfaceId, int methodId) 131 | { 132 | return PersonMethodInvoker.GetMethodName(interfaceId, methodId); 133 | } 134 | 135 | System.Threading.Tasks.Task Test.Interfaces.IPerson.Register(Test.Interfaces.PersonalAttributes person) 136 | { 137 | 138 | return base.InvokeMethodAsync(-1544510960, new object[] {person} ); 139 | } 140 | 141 | System.Threading.Tasks.Task Test.Interfaces.IPerson.Marry(Test.Interfaces.IPerson spouse) 142 | { 143 | 144 | return base.InvokeMethodAsync(1859357851, new object[] {spouse is global::Orleans.Grain ? Test.Interfaces.PersonFactory.Cast(spouse.AsReference()) : spouse} ); 145 | } 146 | 147 | System.Threading.Tasks.Task Test.Interfaces.IPerson.GetFirstName() 148 | { 149 | 150 | return base.InvokeMethodAsync(513673718, new object[] {} ); 151 | } 152 | 153 | System.Threading.Tasks.Task Test.Interfaces.IPerson.GetLastName() 154 | { 155 | 156 | return base.InvokeMethodAsync(160660420, new object[] {} ); 157 | } 158 | 159 | System.Threading.Tasks.Task Test.Interfaces.IPerson.GetGender() 160 | { 161 | 162 | return base.InvokeMethodAsync(-1388702422, new object[] {} ); 163 | } 164 | } 165 | } 166 | 167 | [System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.0.970.29197")] 168 | [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute()] 169 | [global::Orleans.CodeGeneration.MethodInvokerAttribute("Test.Interfaces.Test.Interfaces.IPerson", -627797884)] 170 | internal class PersonMethodInvoker : global::Orleans.CodeGeneration.IGrainMethodInvoker 171 | { 172 | 173 | int global::Orleans.CodeGeneration.IGrainMethodInvoker.InterfaceId 174 | { 175 | get 176 | { 177 | return -627797884; 178 | } 179 | } 180 | 181 | global::System.Threading.Tasks.Task global::Orleans.CodeGeneration.IGrainMethodInvoker.Invoke(global::Orleans.Runtime.IAddressable grain, int interfaceId, int methodId, object[] arguments) 182 | { 183 | 184 | try 185 | {{ if (grain == null) throw new System.ArgumentNullException("grain"); 186 | switch (interfaceId) 187 | { 188 | case -627797884: // IPerson 189 | switch (methodId) 190 | { 191 | case -1544510960: 192 | return ((IPerson)grain).Register((PersonalAttributes)arguments[0]).ContinueWith(t => {if (t.Status == System.Threading.Tasks.TaskStatus.Faulted) throw t.Exception; return (object)null; }); 193 | case 1859357851: 194 | return ((IPerson)grain).Marry((IPerson)arguments[0]).ContinueWith(t => {if (t.Status == System.Threading.Tasks.TaskStatus.Faulted) throw t.Exception; return (object)null; }); 195 | case 513673718: 196 | return ((IPerson)grain).GetFirstName().ContinueWith(t => {if (t.Status == System.Threading.Tasks.TaskStatus.Faulted) throw t.Exception; return (object)t.Result; }); 197 | case 160660420: 198 | return ((IPerson)grain).GetLastName().ContinueWith(t => {if (t.Status == System.Threading.Tasks.TaskStatus.Faulted) throw t.Exception; return (object)t.Result; }); 199 | case -1388702422: 200 | return ((IPerson)grain).GetGender().ContinueWith(t => {if (t.Status == System.Threading.Tasks.TaskStatus.Faulted) throw t.Exception; return (object)t.Result; }); 201 | default: 202 | throw new NotImplementedException("interfaceId="+interfaceId+",methodId="+methodId); 203 | } 204 | default: 205 | throw new System.InvalidCastException("interfaceId="+interfaceId); 206 | } 207 | }} 208 | catch(Exception ex) 209 | {{ 210 | var t = new System.Threading.Tasks.TaskCompletionSource(); 211 | t.SetException(ex); 212 | return t.Task; 213 | }} 214 | } 215 | 216 | public static string GetMethodName(int interfaceId, int methodId) 217 | { 218 | 219 | switch (interfaceId) 220 | { 221 | 222 | case -627797884: // IPerson 223 | switch (methodId) 224 | { 225 | case -1544510960: 226 | return "Register"; 227 | case 1859357851: 228 | return "Marry"; 229 | case 513673718: 230 | return "GetFirstName"; 231 | case 160660420: 232 | return "GetLastName"; 233 | case -1388702422: 234 | return "GetGender"; 235 | 236 | default: 237 | throw new NotImplementedException("interfaceId="+interfaceId+",methodId="+methodId); 238 | } 239 | 240 | default: 241 | throw new System.InvalidCastException("interfaceId="+interfaceId); 242 | } 243 | } 244 | } 245 | 246 | [System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.0.970.29197")] 247 | [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute()] 248 | [global::Orleans.CodeGeneration.RegisterSerializerAttribute()] 249 | internal class Test_Interfaces_PersonalAttributesSerialization 250 | { 251 | 252 | static Test_Interfaces_PersonalAttributesSerialization() 253 | { 254 | Register(); 255 | } 256 | 257 | public static object DeepCopier(object original) 258 | { 259 | Test.Interfaces.PersonalAttributes input = ((Test.Interfaces.PersonalAttributes)(original)); 260 | Test.Interfaces.PersonalAttributes result = new Test.Interfaces.PersonalAttributes(); 261 | Orleans.Serialization.SerializationContext.Current.RecordObject(original, result); 262 | result.FirstName = input.FirstName; 263 | result.Gender = input.Gender; 264 | result.LastName = input.LastName; 265 | return result; 266 | } 267 | 268 | public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected) 269 | { 270 | Test.Interfaces.PersonalAttributes input = ((Test.Interfaces.PersonalAttributes)(untypedInput)); 271 | Orleans.Serialization.SerializationManager.SerializeInner(input.FirstName, stream, typeof(String)); 272 | Orleans.Serialization.SerializationManager.SerializeInner(input.Gender, stream, typeof(GenderType)); 273 | Orleans.Serialization.SerializationManager.SerializeInner(input.LastName, stream, typeof(String)); 274 | } 275 | 276 | public static object Deserializer(System.Type expected, global::Orleans.Serialization.BinaryTokenStreamReader stream) 277 | { 278 | Test.Interfaces.PersonalAttributes result = new Test.Interfaces.PersonalAttributes(); 279 | result.FirstName = ((String)(Orleans.Serialization.SerializationManager.DeserializeInner(typeof(String), stream))); 280 | result.Gender = ((GenderType)(Orleans.Serialization.SerializationManager.DeserializeInner(typeof(GenderType), stream))); 281 | result.LastName = ((String)(Orleans.Serialization.SerializationManager.DeserializeInner(typeof(String), stream))); 282 | return result; 283 | } 284 | 285 | public static void Register() 286 | { 287 | global::Orleans.Serialization.SerializationManager.Register(typeof(Test.Interfaces.PersonalAttributes), DeepCopier, Serializer, Deserializer); 288 | } 289 | } 290 | } 291 | #pragma warning restore 162 292 | #pragma warning restore 219 293 | #pragma warning restore 693 294 | #pragma warning restore 1591 295 | #pragma warning restore 1998 296 | #endif 297 | -------------------------------------------------------------------------------- /Orleans.EventSourcing/Test.Interfaces/Test.Interfaces.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | 8.0.30703 7 | 2.0 8 | {08EE195C-5936-42DE-A667-2A8DED9B281D} 9 | Library 10 | Properties 11 | Test.Interfaces 12 | Test.Interfaces 13 | v4.5 14 | 512 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | $(OrleansSDK)\Binaries\OrleansClient\Orleans.dll 43 | False 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | Client 54 | 55 | 56 | 57 | 58 | 59 | 60 | 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Orleans.EventSourcing 2 | ===================== 3 | 4 | Event sourcing support for MSR Orleans (http://orleans.codeplex.com) using EventStore (http://geteventstore.com) 5 | 6 | 7 | Prerequisites 8 | ------------- 9 | 10 | 1. Orleans SDK. You can obtain it from here: http://aka.ms/orleans. 11 | 2. EventStore 3.0.0. You can obtain a prerelease version from here: http://geteventstore.com/downloads. 12 | 13 | 14 | Usage 15 | ----- 16 | 17 | 1. Compile the solution first. This will copy the assemblies to the local silo folder (post-build event). 18 | 19 | 2. Start EventStore. 20 | 21 | 3. Configure EventStoreProvider in `DevTestServerConfiguration.xml`. Connection string is in `:` format. 22 | 23 | ``` 24 | 25 | 26 | 27 | 28 | ``` 29 | 30 | *Username and Password can be omitted if you're using default values.* 31 | 32 | 4. Run the Test.Client project. This will start the local silo and execute sample code from Program.Main(). 33 | 34 | 35 | How does it work? 36 | ----- 37 | 38 | The most important thing to understand is that it is the *state* that is event sourced, not the grain. 39 | 40 | The second most important thing is that event sourcing is hidden in the Implementation project and not present in the Interfaces project - *the fact that a certain grain is event sourced is encapsulated in this grain and doesn't impact other grains*. 41 | 42 | 43 | 1. Define your state 44 | 45 | Derive from `IAggregateState` instead of `IState`. 46 | 47 | ``` 48 | public interface IPersonState : IAggregateState 49 | { 50 | string FirstName { get; set; } 51 | string LastName { get; set; } 52 | GenderType Gender { get; set; } 53 | bool IsMarried { get; set; } 54 | } 55 | ``` 56 | 57 | 2. Define your events 58 | 59 | Events are plain classes. By convention, add a `public void Apply(IYourAggregateState state)` method that will mutate the state by applying the current event. 60 | 61 | ``` 62 | public class PersonRegistered 63 | { 64 | public string FirstName { get; set; } 65 | public string LastName { get; set; } 66 | public GenderType Gender { get; set; } 67 | 68 | public void Apply(IPersonState state) 69 | { 70 | state.FirstName = this.FirstName; 71 | state.LastName = this.LastName; 72 | state.Gender = this.Gender; 73 | } 74 | } 75 | ``` 76 | 77 | 3. Raise events from the grain 78 | 79 | Call `RaiseEvent` method passing your event in the grain. `RaiseEvent` will mutate the grain state so you don't have to do it yourself. By default the event will be persisted in event store. If you know that you will be raising multiple events and want to persist them in a single commit, you can pass `store: false` argument. In that case the state will be mutated but the event won't be persisted until `RaiseEvent(@event, store: true)` or `this.State.WriteStateAsync()` is called. 80 | 81 | ``` 82 | Task IPerson.Register(PersonalAttributes props) 83 | { 84 | return this.RaiseEvent(new PersonRegistered 85 | { 86 | FirstName = props.FirstName, 87 | LastName = props.LastName, 88 | Gender = props.Gender 89 | }); 90 | } 91 | ``` 92 | 93 | 94 | Roadmap 95 | ----- 96 | 97 | Currently the project supports EventStore only and the code may not be performant enough for a high traffic production environments (using dynamic dispatch through `dynamic` objects). 98 | 99 | Planned work includes supporting other event stores, by either implementing own provider model or using Common Domain (https://github.com/NEventStore/CommonDomain) 100 | --------------------------------------------------------------------------------