System.Reactive: Implement an IObservable<T> - system.reactive

I need to create a custom IObservable. I've read a bit over there, I've ended up I shouldn't implement IObservable<T> directly.
I've noticed that there is an ObservableBase<T>. This is an abstract class, so I need to implement the abstract method:
public class Store<TState> : ObservableBase<TState>, IObserver<IAction>
{
public void OnCompleted()
{
throw new NotImplementedException();
}
public void OnError(Exception error)
{
throw new NotImplementedException();
}
public void OnNext(IAction value)
{
throw new NotImplementedException();
}
protected override IDisposable SubscribeCore(IObserver<TState> observer)
{
>>>>>>>>>>>>>>>>>******<<<<<<<<<<<<<<<<<<<<<<<
throw new NotImplementedException();
}
}
How should I implement this method?

I don't know your problem, but if you can replace implementing IObservable for exposing a property/method that returns IObservable you'll be a lot better off. If you can do that, you can easily return an Rx-based Observable from some of Rx's create methods.
If you can't do that, I would recommend wrapping a Subject<T>:
public class MyIntObservable : IObservable<int>
{
private readonly Subject<int> _mySubject = new Subject<int>();
public IDisposable Subscribe(IObserver<int> observer)
{
return _mySubject.Subscribe(observer);
}
}

I'm guessing you don't want to be doing what you are doing.
From a brief look at the "Store" class that you want to mimic, it appears to be some sort of Subject. A Subject is both a IObserver and an IObservable and there are many implementations that are provided out of the box. Here is the interface:
public interface ISubject<in TSource, out TResult> : IObserver<TSource>, IObservable<TResult>
{
}
This is a very good article about Subjects and when to use them here:
http://davesexton.com/blog/post/To-Use-Subject-Or-Not-To-Use-Subject.aspx

Related

Persisting & Restoring Current State in Spring Statemachine

I'm introducing Spring Statemachine into an existing project, with the hope of amalgamating and clarifying our business logic. We have various JPA entities with interconnected states and I'm having some trouble with setting a persisted state as the current state of an existing state machine.
I'm using a StateMachineFactory to create a new StateMachine instance for each entity instance. I'm storing the current state of the StateMachine in a separate field for Hibernate to persist and ideally need to sync the value of the persisted field with the StateMachine. My question is around how this should be typically achieved in Spring Statemachine.
#Entity
#EntityListeners(MyEntityListener.class)
public class MyEntity {
#Column
private MyState internalState; // Using AttributeConverter
#Transient
private StateMachine<MyState, Event> stateMachine;
}
public class MyEntityListener {
#PostLoad
public void postLoad(MyEntity entity) {
// TODO Set StateMachine's current state to entity's internal state
);
}
One approach may be to define local transitions to move the initial state into the persisted state. I could then do a conditional check to find an event tied to a local transition, which would move the source state into the target state. This seems a little messy to me and I'd like to keep my state machine's configuration as clean as possible.
I can't see how I can set the StateMachine's current state through a public API without moving through a transition and so another approach I explored is to wrap the StateMachine instance to expose the following method (as it's conveniently default scope):
package org.springframework.statemachine.support;
public abstract class AbstractStateMachine<S, E> extends StateMachineObjectSupport<S, E> implements StateMachine<S, E>, StateMachineAccess<S, E> {
void setCurrentState(State<S, E> state, Message<E> message, Transition<S, E> transition, boolean exit, StateMachine<S, E> stateMachine)
}
package org.springframework.statemachine.support;
public class MyStateMachineWrapper<S, E> {
private AbstractStateMachine<S, E> stateMachine;
public MyStateMachineWrapper(StateMachine<S, E> stateMachine) {
if (stateMachine instanceof AbstractStateMachine) {
this.stateMachine = (AbstractStateMachine<S, E>)stateMachine;
} else {
throw new IllegalArgumentException("Provided StateMachine is not a valid type");
}
}
public void setCurrentState(S status) {
stateMachine.setCurrentState(findState(status), null, null, false, stateMachine);
}
private State<S, E> findState(S status) {
for (State<S, E> state : stateMachine.getStates()) {
if (state.getId() == status) {
return state;
}
}
throw new IllegalArgumentException("Specified status does not equate to valid State");
}
}
I could then throw the following code into MyEntityListener.postLoad:
MyStateMachineWrapper<MyState, Event> myStateMachineWrapper = new MyStateMachineWrapper<>(entity.getStateMachine());
myStateMachineWrapper.setCurrentState(entity.getInternalState());
The above approach seems to work fine but I can't imagine this is how it was envisioned to work. Surely there's a cleaner method to achieve this or maybe the project isn't mature enough and doesn't include this functionality yet?
Thanks for any thoughts and opinions.
I've cleaned up option #2 above, changing the wrapper class to a utils class. To be clear, this approach takes advantage of the setCurrentState method having a default accessor and so this may end up being a brittle solution.
package org.springframework.statemachine.support;
public abstract class MyStateMachineUtils extends StateMachineUtils {
public static <S, E> void setCurrentState(StateMachine<S, E> stateMachine, S state) {
if (stateMachine instanceof AbstractStateMachine) {
setCurrentState((AbstractStateMachine<S, E>)stateMachine, state);
} else {
throw new IllegalArgumentException("Provided StateMachine is not a valid type");
}
}
public static <S, E> void setCurrentState(AbstractStateMachine<S, E> stateMachine, S state) {
stateMachine.setCurrentState(findState(stateMachine, state), null, null, false, stateMachine);
}
private static <S, E> State<S, E> findState(AbstractStateMachine<S, E> stateMachine, S stateId) {
for (State<S, E> state : stateMachine.getStates()) {
if (state.getId() == stateId) {
return state;
}
}
throw new IllegalArgumentException("Specified State ID is not valid");
}
}
This can then be used quite nicely like so:
MyStateMachineUtils.setCurrentState(entity.getStateMachine(), entity.getInternalState());

MvvmCross: IoC with Decorator pattern, two implementations of the same interface

I'd like to implement the Decorator pattern in one of my Mvx projects. That is, I'd like to have two implementations of the same interface: one implementation that is available to all of the calling code, and another implementation that is injected into the first implementation.
public interface IExample
{
void DoStuff();
}
public class DecoratorImplementation : IExample
{
private IExample _innerExample;
public Implementation1(IExample innerExample)
{
_innerExample = innerExample;
}
public void DoStuff()
{
// Do other stuff...
_innerExample.DoStuff();
}
}
public class RegularImplementation : IExample
{
public void DoStuff()
{
// Do some stuff...
}
}
Is it possible to wire up the MvvmCross IoC container to register IExample with a DecoratorImplementation containing a RegularImplementation?
It depends.
If DecoratorImplementation is a Singleton, then you could do something like:
Mvx.RegisterSingleton<IExample>(new DecoratorImplementation(new RegularImplementation()));
Then calls to Mvx.Resolve<IExample>() will return the instance of DecoratorImplementation.
However, if you need a new instance, unfortunately the MvvmCross IoC Container doesn't support that. It would be nice if you could do something like:
Mvx.RegisterType<IExample>(() => new DecoratorImplementation(new RegularImplementation()));
Where you'd pass in a lambda expression to create a new instance, similar to StructureMap's ConstructedBy.
Anyway, you may need to create a Factory class to return an instance.
public interface IExampleFactory
{
IExample CreateExample();
}
public class ExampleFactory : IExampleFactory
{
public IExample CreateExample()
{
return new DecoratorImplementation(new RegularImplementation());
}
}
Mvx.RegisterSingleton<IExampleFactory>(new ExampleFactory());
public class SomeClass
{
private IExample _example;
public SomeClass(IExampleFactory factory)
{
_example = factory.CreateExample();
}
}

entity framework unit of work in winforms

I found this sample but its for web. Can any one check this proj. and add a simple sample using winforms(no wpf).
Source Code
Thx
What kind of problem were you facing? Anyways I have made sample (yet basic) structure of how you can achieve this in WinForm. I have done using sort of Model View Presenter pattern.
First of all we have a presenter, which would deal with unit of work almost similarly the way controller does
internal class EmployeePresenter
{
private readonly IEmployeeFormView _employeeFormView;
private readonly IUnitOfWork _unitOfWork;
public EmployeePresenter(IEmployeeFormView view)
{
_employeeFormView = view;
_unitOfWork = new SqlUnitOfWork();
}
internal void GetData()
{
var id = 1; //parameter
var employee = _unitOfWork.Employees.Single(e => e.Id == id);
_employeeFormView.PopulateData(employee.Name);
}
}
Then we have an interface and a form implementing that interface
public interface IEmployeeFormView
{
void PopulateData(string data);
}
public partial class EmployeeForm : Form, IEmployeeFormView
{
private readonly EmployeePresenter _presenter;
public EmployeeForm()
{
InitializeComponent();
_presenter = new EmployeePresenter(this);
}
#region IEmployeeFormView Members
public void PopulateData(string data)
{
txtName.Text = data; //txtName is a textbox on form
}
#endregion
private void btnGet_Click(object sender, EventArgs e)
{
_presenter.GetData();
}
}
Add the required reference and you are done. This might not be the best way but it's certainly a way to achieve this.
Solution is upload here.
Hope this helps. Please feel free to discuss, if required.

How to dispose resources with dependency injection

I'm using StructureMap to resolve references to my repository class. My repository interface implements IDisposable, e.g.
public interface IMyRepository : IDisposable
{
SomeClass GetById(int id);
}
An implementation of the interface using Entity Framework:
public MyRepository : IMyRepository
{
private MyDbContext _dbContext;
public MyDbContext()
{
_dbContext = new MyDbContext();
}
public SomeClass GetById(int id)
{
var query = from x in _dbContext
where x.Id = id
select x;
return x.FirstOrDefault();
}
public void Dispose()
{
_dbContext.Dispose();
}
}
Anyway as mentioned I'm using StructureMap to resolve IMyRepository. So when, where and how should I call my dispose method?
WARNING: please note that my views have changed, and you should consider the following advise outdated. Please see this answer for an updated view: https://stackoverflow.com/a/30287923/264697
While DI frameworks can manage lifetime of objects for you and some could even dispose objects for you after you're done using with them, it makes object disposal just too implicit. The IDisposable interface is created because there was the need of deterministic clean-up of resources. Therefore, in the context of DI, I personally like to make this clean-up very explicit. When you make it explicit, you've got basically two options: 1. Configure the DI to return transient objects and dispose these objects yourself. 2. Configure a factory and instruct the factory to create new instances.
I favor the second approach over the first, because especially when doing Dependency Injection, your code isn't as clean as it could be. Look for instance at this code:
public sealed class Client : IDisposable
{
private readonly IDependency dependency;
public Client(IDependency dependency)
{
this. dependency = dependency;
}
public void Do()
{
this.dependency.DoSomething();
}
public Dispose()
{
this.dependency.Dispose();
}
}
While this code explicitly disposes the dependency, it could raise some eyebrows to readers, because resources should normally only be disposed by the owner of the resource. Apparently, the Client became the owner of the resource, when it was injected.
Because of this, I favor the use of a factory. Look for instance at this example:
public sealed class Client
{
private readonly IDependencyFactory factory;
public Client(IDependencyFactory factory)
{
this.factory = factory;
}
public void Do()
{
using (var dependency = this.factory.CreateNew())
{
dependency.DoSomething();
}
}
}
This example has the exact same behavior as the previous example, but see how the Client class doesn't have to implement IDisposable anymore, because it creates and disposes the resource within the Do method.
Injecting a factory is the most explicit way (the path of least surprise) to do this. That's why I prefer this style. Downside of this is that you often need to define more classes (for your factories), but I personally don't mind.
RPM1984 asked for a more concrete example.
I would not have the repository implement IDisposable, but have a Unit of Work that implements IDisposable, controls/contains repositories and have a factory that knows how to create new unit of works. With that in mind, the above code would look like this:
public sealed class Client
{
private readonly INorthwindUnitOfWorkFactory factory;
public Client(INorthwindUnitOfWorkFactory factory)
{
this.factory = factory;
}
public void Do()
{
using (NorthwindUnitOfWork db =
this.factory.CreateNew())
{
// 'Customers' is a repository.
var customer = db.Customers.GetById(1);
customer.Name = ".NET Junkie";
db.SubmitChanges();
}
}
}
In the design I use, and have described here, I use a concrete NorthwindUnitOfWork class that wraps an IDataMapper that is the gateway to the underlying LINQ provider (such as LINQ to SQL or Entity Framework). In sumary, the design is as follows:
An INorthwindUnitOfWorkFactory is injected in a client.
The particular implementation of that factory creates a concrete NorthwindUnitOfWork class and injects a O/RM specific IDataMapper class into it.
The NorthwindUnitOfWork is in fact a type-safe wrapper around the IDataMapper and the NorthwindUnitOfWork requests the IDataMapper for repositories and forwards requests to submit changes and dispose to the mapper.
The IDataMapper returns Repository<T> classes and a repository implements IQueryable<T> to allow the client to use LINQ over the repository.
The specific implementation of the IDataMapper holds a reference to the O/RM specific unit of work (for instance EF's ObjectContext). For that reason the IDataMapper must implement IDisposable.
This results in the following design:
public interface INorthwindUnitOfWorkFactory
{
NorthwindUnitOfWork CreateNew();
}
public interface IDataMapper : IDisposable
{
Repository<T> GetRepository<T>() where T : class;
void Save();
}
public abstract class Repository<T> : IQueryable<T>
where T : class
{
private readonly IQueryable<T> query;
protected Repository(IQueryable<T> query)
{
this.query = query;
}
public abstract void InsertOnSubmit(T entity);
public abstract void DeleteOnSubmit(T entity);
// IQueryable<T> members omitted.
}
The NorthwindUnitOfWork is a concrete class that contains properties to specific repositories, such as Customers, Orders, etc:
public sealed class NorthwindUnitOfWork : IDisposable
{
private readonly IDataMapper mapper;
public NorthwindUnitOfWork(IDataMapper mapper)
{
this.mapper = mapper;
}
// Repository properties here:
public Repository<Customer> Customers
{
get { return this.mapper.GetRepository<Customer>(); }
}
public void Dispose()
{
this.mapper.Dispose();
}
}
What's left is an concrete implementation of the INorthwindUnitOfWorkFactory and a concrete implementation of the IDataMapper. Here's one for Entity Framework:
public class EntityFrameworkNorthwindUnitOfWorkFactory
: INorthwindUnitOfWorkFactory
{
public NorthwindUnitOfWork CreateNew()
{
var db = new ObjectContext("name=NorthwindEntities");
db.DefaultContainerName = "NorthwindEntities";
var mapper = new EntityFrameworkDataMapper(db);
return new NorthwindUnitOfWork(mapper);
}
}
And the EntityFrameworkDataMapper:
public sealed class EntityFrameworkDataMapper : IDataMapper
{
private readonly ObjectContext context;
public EntityFrameworkDataMapper(ObjectContext context)
{
this.context = context;
}
public void Save()
{
this.context.SaveChanges();
}
public void Dispose()
{
this.context.Dispose();
}
public Repository<T> GetRepository<T>() where T : class
{
string setName = this.GetEntitySetName<T>();
var query = this.context.CreateQuery<T>(setName);
return new EntityRepository<T>(query, setName);
}
private string GetEntitySetName<T>()
{
EntityContainer container =
this.context.MetadataWorkspace.GetEntityContainer(
this.context.DefaultContainerName, DataSpace.CSpace);
return (
from item in container.BaseEntitySets
where item.ElementType.Name == typeof(T).Name
select item.Name).First();
}
private sealed class EntityRepository<T>
: Repository<T> where T : class
{
private readonly ObjectQuery<T> query;
private readonly string entitySetName;
public EntityRepository(ObjectQuery<T> query,
string entitySetName) : base(query)
{
this.query = query;
this.entitySetName = entitySetName;
}
public override void InsertOnSubmit(T entity)
{
this.query.Context.AddObject(entitySetName, entity);
}
public override void DeleteOnSubmit(T entity)
{
this.query.Context.DeleteObject(entity);
}
}
}
You can find more information about this model here.
UPDATE December 2012
This an an update written two years after my original answer. The last two years much has changed in the way I try to design the systems I'm working on. Although it has suited me in the past, I don't like to use the factory approach anymore when dealing with the Unit of Work pattern. Instead I simply inject a Unit of Work instance into consumers directly. Whether this design is feasibly for you however, depends a lot on the way your system is designed. If you want to read more about this, please take a look at this newer Stackoverflow answer of mine: One DbContext per web request…why?
If you want to get it right, i'd advise on a couple of changes:
1 - Don't have private instances of the data context in the repository. If your working with multiple repositories then you'll end up with multiple contexts.
2 - To solve the above - wrap the context in a Unit of Work. Pass the unit of work to the Repositories via the ctor: public MyRepository(IUnitOfWork uow)
3 - Make the Unit of Work implement IDisposable. The Unit of Work should be "newed up" when a request begins, and therefore should be disposed when the request finishes. The Repository should not implement IDisposable, as it is not directly working with resources - it is simply mitigating them. The DataContext / Unit of Work should implement IDispoable.
4 - Assuming you are using a web application, you do not need to explicitly call dispose - i repeat, you do not need to explicitly call your dispose method. StructureMap has a method called HttpContextBuildPolicy.DisposeAndClearAll();. What this does is invoke the "Dispose" method on any HTTP-scoped objects that implement IDisposable. Stick this call in Application_EndRequest (Global.asax). Also - i believe there is an updated method, called ReleaseAllHttpScopedObjects or something - can't remember the name.
Instead of adding Dispose to IMyRepository, you could declare IMyRepository like this:
public interface IMyRepository: IDisposable
{
SomeClass GetById(int id);
}
This way, you ensure all repository will call Dispose sometimes, and you can use the C# "using" pattern on a Repository object:
using (IMyRepository rep = GetMyRepository(...))
{
... do some work with rep
}

RIA Services Repository Save does not work?

Doing my first SL4 MVVM RIA based application and i ran into the following situation:
updating a record (EF4,NO-POCOS!!) in the SL-client seems to take place, but values in the dbms are unchanged. Debugging with Fiddler the message on save is (amongst others):
EntityActions.nil� b9http://schemas.microsoft.com/2003/10/Serialization/Arrays^HasMemberChanges�^Id�^ Operation�Update
I assume that this says only: hey! the dbms should do an update on this record, AND nothing more! Is that right?!
I 'm using a generic repository like this:
public class Repository<T> : IRepository<T> where T : class
{
IObjectSet<T> _objectSet;
IObjectContext _objectContext;
public Repository(IObjectContext objectContext)
{
this._objectContext = objectContext;
_objectSet = objectContext.CreateObjectSet<T>();
}
public IQueryable<T> AsQueryable()
{
return _objectSet;
}
public IEnumerable<T> GetAll()
{
return _objectSet.ToList();
}
public IEnumerable<T> Find(Expression<Func<T, bool>> where)
{
return _objectSet.Where(where);
}
public T Single(Expression<Func<T, bool>> where)
{
return _objectSet.Single(where);
}
public T First(Expression<Func<T, bool>> where)
{
return _objectSet.First(where);
}
public void Delete(T entity)
{
_objectSet.DeleteObject(entity);
}
public void Add(T entity)
{
_objectSet.AddObject(entity);
}
public void Attach(T entity)
{
_objectSet.Attach(entity);
}
public void Save()
{
_objectContext.SaveChanges();
}
}
The DomainService Update Method is the following:
[Update]
public void UpdateCulture(Culture currentCulture)
{
if (currentCulture.EntityState == System.Data.EntityState.Detached)
{
this.cultureRepository.Attach(currentCulture);
}
this.cultureRepository.Save();
}
I know that the currentCulture-Entity is detached. What confuses me (amongst other things) is this: is the _objectContext still alive? (which means it "will be"??? aware of the changes made to record, so simply calling Attach() and then Save() should be enough!?!?)
What am i missing?
Development Environment: VS2010RC - Entity Framework 4 (no POCOs)
Thanks in advance
You are attaching the culture in the context, but you are not telling the context that the object has actually changed.
The generated code I have on my machine is:
public void UpdateDepartment(Department currentDepartment) {
if ((currentDepartment.EntityState == EntityState.Detached)) {
this.ObjectContext.AttachAsModified(currentDepartment, this.ChangeSet.GetOriginal(currentDepartment));
}
}
What matters is the 'AttachAsModified'.
Timores pointed me in the correct direction, the solution (as far as my problem concerns) is very simple: simply add this method to the repository and we're done:
public void AttachModified(T entity)
{
_objectSet.Attach(entity);
_context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);
}
Now instead of calling Attach() we call AttachModified().
Thank you Timores!