Skip to content

Instantly share code, notes, and snippets.

@mcintyre321
Last active May 18, 2016 14:58
Show Gist options
  • Save mcintyre321/147b1ae9856afbd1b20b0fa78cd7a9f7 to your computer and use it in GitHub Desktop.
Save mcintyre321/147b1ae9856afbd1b20b0fa78cd7a9f7 to your computer and use it in GitHub Desktop.
Simple Event Sourcing using NMF
void Main()
{
var events = new ObservableCollection<Event>();
var state = new NotifyCollection<object>();
events.OnAdd(next =>
{
if (next is UserWasAdded)
{
var userWasAdded = (UserWasAdded)next;
state.Add(new User() { UserName = userWasAdded.UserName });
}
if (next is UserWasDeleted)
{
var userWasDeleted = (UserWasDeleted)next;
var user = state.OfType<User>().Single(u => u.UserName == userWasDeleted.UserName);
user.Deleted = true;
}
});
var activeUsers = state.WithUpdates().OfType<User>().Where(u => u.Deleted == false);
("Active users: " + activeUsers.Count()).Dump();
events.Add(new UserWasAdded() { UserName = "Harry" });
("Active users: " + activeUsers.Count()).Dump();
events.Add(new UserWasDeleted() { UserName = "Harry" });
("Active users: " + activeUsers.Count()).Dump();
}
class Event { }
class UserWasAdded : Event { public string UserName { get; set; } }
class UserWasDeleted : Event { public string UserName { get; set; } }
class User : INotifyPropertyChanged {
public string UserName { get; set; }
bool _deleted;
public bool Deleted
{
get { return _deleted; } set{ _deleted = value; OnPropertyChanged();}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
@mcintyre321
Copy link
Author

mcintyre321 commented May 18, 2016

@bwanner Am I using this incorrectly? I get InvalidOperationException: Sequence contains no elements on line 6

edit: ah you need to provide a seed to Aggregate if the collection is empty.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment