Spring Statemachine - building hierarchical state machine from UML - spring-statemachine

Short: Is it possible to create hierarchichal (nested) statemachine UML diagram in Papyrus and then use it to build working statemachine instance?
Explained:
Simple example without nested states, as in documentation, is working correctly.
I tried two ways to create nested state:
creating state in my main machine and linking another submachine to it (Properties -> Submachine)
creating everything in single state machine, creating state with substates
In both cases, created Spring statemachine does not recognize submachine states.
When I list all states in my application with this code:
public List<String> getAllStates() {
List<String> list = new ArrayList<>();
Collection<State<String, String>> states = machine.getStates();
for (State state : states) {
Collection<State<String, String>> substates = state.getStates();
for (State<String, String> substate : substates) {
list.add(substate.getIds().toString());
}
}
return list;
}
, it lists only two states, INITIALIZATION and PROCESSING. When I send events, machine enters from INITIALIZATION to PROCESSING, not to [PROCESSING, PREPARATION].
Am I doing something incorrectly or am I trying to do something that is not even implemented by Spring Statemachine? That is, is it possible to only create single level state machines from UML diagrams?
EDIT:
Thanks to Janne Valkealahti for reading this question and for assuring that spring-statemachine has this option.
It seems it was my fault after all, but I'm not sure where and how (several similar diagrams were created / edited with no success). Possibly it was linked with some Papyrus / Eclipse warnings and errors on my Fedora 24 that occurred yesterday.
Today, after creating new diagram from scratch, everything is working as expected. Here is new, working, diagram, for which state machine lists all states and substates.

Linking submachine doesn't work yet but work for that is happening in Support for UML Sub State Machines #121.
Substates need to be configured within a single machine as you tried. Uml test source for this is at simple-submachine.uml. If you post your uml xml I can look if there's anything obvious missing(or put all 3 papyrus files, di, notation, uml) somewhere(github gist maybe) so that I can open it in papyrus.

Related

Writing a Unit Test to ensure dynamic proxy creation by testing for IEntityWithChangeTracker (EF4)

I've been working through Julie Lerman's books on Entity Framework, and I've run into somewhat of a snag...
In "Programming Entity Framework DbContext" on page 66 Julie suggests writing a Unit Test to make sure that dynamic proxies are being created, since the requirements for getting Entity Framework to create change tracking proxies are fairly simple, but also very easy to miss.
With that being said, I followed the general structure of Julie's example to write the following test for my code:
[Test]
public void IsDynamicProxy()
{
using (var scienceFairToGoContext = new ScienceFairToGoContext())
{
var scienceFair = scienceFairToGoContext.ScienceFairs.Create();
Assert.IsTrue(scienceFair is IEntityWithChangeTracker);
}
}
When I hover over the scienceFair object its pretty obvious its a change tracking proxy
System.Data.Entity.DynamicProxies.ScienceFair_D3C57A2F699E75F716E63553D950EF7EC75F0C603F69093FCD78122CC0D6452C
...but whenever I run the unit test it always fails because "scienceFair is IEntityWithChangeTracker" always evaluates to false.
It appears as though someone else ran into this issue as well and posted it to the O'Reilly forums, but there doesn't seem to be a solution posted, nor do my Google searches return any type of answer.
I'm currently using Visual Studio 2010, EF4, NUnit, and running my tests through ReSharper. It's also worth mentioning that if run the code in a simple console application and debug it I get the same results.
Actually, it looks like I figured out the issue. While working through Julie's book, I thought it would be a good idea to have all of the entities inherit from a base class, ScienceFairToGoEntity.
It looks like I forgot to mark the 4 properties I had on the base class (InsertBy, InsertDate, UpdateBy, UpdateDate) as virtual, so the dynamic proxies were for Lazy Loading/ Relationship Fix-up and not for Change Tracking.
It's weird to find this non-working piece of code in such a good book. You can however execute you test by:
using (var scienceFairToGoContext = new ScienceFairToGoContext())
{
var scienceFair = scienceFairToGoContext.ScienceFairs.Create();
Assert.IsTrue(scienceFair.GetType().IsSubclassOf(typeof(ScienceFair)));
}
although it is less generally applicable when there are entities in inheritance hierarchies. With derived entities you'd have to use
scienceFairToGoContext.BaseEntities.Create<TDerivedEntity>()

How to Inject Controller for MVC4/VS2012/Web API

I have read or tried to read far too many "how to"s on this and have gotten exactly nowhere. Unity? System.Web.Http.Dependencies? Ninject? StructureMap? Ugh. I just want something simple that works! I just can't figure out what the current state of this is. There are wildly different approaches and the examples appear to be incomplete. Heck the best lead had a sample project with it ... that I can't load in VS2010 or 2012. ARG! I waster 3/4 of the day on something that I feel should have been half an hour at most and move on! It's just plumbing!
I have a repository that's based on generics to process a number of data sets that all support the same operations.
IRepository
I want to control which repository each data set is bound to. This will allow me to bind everything to a test XML repository, transitioning them over to a SQL repository as the project advances.
I sure would appreciate some help getting this going! Thank you!
Sounds like you are at the state I was a couple of years ago.
Note, if you need any further help I cn send you some code. It's just hard to put all the code in here.
Ill try to explain the current architecture in the project I am working on. This post is a bit long winded but I am trying to give you a big picture of how using IOC can help you in many ways.
So I use Ninject. After trying to use Castle Windsor for a while I found Ninject easy to get up and running. Ninject has a cool website that will get you started.
First of all my project structure is as follows: (top down and it's MVC)
View - razor
ViewModel - I use 1 view model per view
ViewModelBuilder - Builds my view models for my views (used to abstract code away from my controller so my controller stays neat and tidy)
AutoMapper - to map domain entities to my view models
Controller - calls my service layer to get Domain Entities
Domain Entities - representations of my domain
ServiceLayer (business layer) - Calls my repository layer to get Domain entities or collections of these
AutoMapper again - to map custom types from my 3rd party vendors into my domain entities
RepositoryLayer - does CRUD operations to my data stores
This is a hierarchy but Domain entities kind of sit along side and are used in a few different layer.
Note: some extra tools mentioned in this post are:
AutoMapper - maps entities to other entities - eliminates the need to write loads of mapping code
Moq - Allows you to mock stuff for unit testing. This is mentioned later.
Now, regarding Ninject.
Each layer is marked with an interface. This must be done so Ninject can say to its self.
When I find IVehicleRepository inject it with a real VehicleRepository or even inject it with FakeVehicleRepository if I need a fake.
(this relates to your comment - "This will allow me to bind everything to a test XML repository")
Now every layer has a contstructor so that Ninject (or any other IOC container) can inject what it needs to:
public VehicleManager(IVehicleRepository vehicleRepository)
{
this._vehicleRepository = vehicleRepository;
}
VehicleManager is in my serviceLayer (not to be confused with anything to do with web services). The service layer is really what we would call the business layer. It seems that a lot of people are using the word service. (even though I think it is annoying as it makes me think about web services or WCF instead of just a business layer.... anyway...)
now without getting into the nitty gritty of Ninject setup the following line of code in my NinjectWebCommon.cs tells ninject what to do:
kernel.Bind<IVehicleRepository>().To<VehicleRepository>().InRequestScope();
This says:
Hey Ninject, when I ask for IVehicleRepository give my a concrete implementation of VehicleRepository.
As mentioned before I could replace VehicleRepository with FakeVehicleRepository so that I didnt have to read from a real database.
So, as you can now imagine, every layer is only dependent on interfaces.
I dont know how much unit testing you have done but you can also imagine that if you wanted to unit test your service layer and it had concrete references to your repository layer then you would not be able to unit test as you would be ACTUALLY hitting your repository and hence reading from a real database.
Remember unit testing is called unit testing because it tests ONE thing only. Hence the word UNIT. So because everything only knows about interfaces, it means that you can test a method on your service layer and mock the repository.
So if your service layer has a method like this:
public bool ThisIsACar(int id)
{
bool isCar = false;
var vehicle = vehicleRepository.GetVehicleById(id);
if(vehicle.Type == VehicleType.Car)
{
isCar = true;
}
else
{
isCar = false;
}
}
You would not want the vehicleRepository to be call so you could Moq what the VehicleRepository gives you back. You can mostly only Mock stuff if it implements an interface.
So your unit test would look like this (some pseudo code here):
[TestMethod]
public void ServiceMethodThisIsACar_Returns_True_When_VehicleIsACar()
{
// Arrange
_mockRepository.Setup(x => x.ThisIsACar(It.IsAny<int>)).returns(new Car with a type of VehicleType.Car)
// Act
var vehicleManager = new VehicleManager(_mockVehicleRepository.Object);
var vehicle = vehicleManager.ThisIsACar(3);
// Assert
Assert.IsTrue(vehicle.VehicleType == VehicleType.Car)
}
So as you can see, at this point and it is very simplified, you only want to test the IF statement in your service layer to make sure the outcome is correct.
You would test your repository in its own unit tests and possibly mock the entity frame work if you were using it.
So, overall, I would say, use what ever IOC container gets you up and running the fastest with the least amount of pain.
I would also say, try and unit test all that you can. This is great for a few different reasons. Obviously it tests the code you have written but it will also immediately show you if you have done some thing stupid like new-ing up a concrete repository. You will quickly see that you wont have an interface to mock in your unit tests and this will lead you to go back and refactor your code.
I found that with IOC, it takes a while to just get it. It confuses the crap out of you until one day it just clicks. After that it is so easy you wonder how you ever lived without it.
Here is a list of things I cant live without
Automapper
Moq
Fluent Validation
Resharper - some hate it, I love it, mostly for its unit testing UI.
Anyway, this is getting too long. Let me know what you think.
thanks
RuSs

Best practice for persisting database-stored lookup data at app level in MVC

Slogging through MVC+EF and trying to focus on doing things the right way. Right now I'm looking to add a dropdown to a form but I'd like to avoid hitting the database every time the page loads so I'd like to store the data in the app level. I figure creating an application level variable isn't the best approach. I've read about using the cache and static utility functions but surprisingly, nothing has sounded terribly definitive. (Static classes bad for unit testing, caching bad
So I have two scenarios that I'm curious about, I'm not sure if the approach would differ between the two.
1) A basic lookup, let's say the fifty states. Small, defined, will never change. Load at application startup. (Not looking for a hard coded solution but retrieval from the database.)
2) A lookup that will very rarely change and only via an admin-like screen. Let's say, cities/stores where your product is being sold. So data would be stored
in the model but would be relatively static unless someone made changes via the application. So not looking to hit the database every time I need to populate a dropdown/listbox.
Seems like basic stuff but it's basically the same as this topic that was never answered:
Is it good to use a static EF object context in an MVC application for better perf?
Any help is appreciated.
I will address you question in a few parts. First off, is it inherently bad to use static variables or caching patterns in MVC. The answer is simply no. As long as your architecture supports them it is OK. Just put your cache in the right place and design for testability as I will explain later.
The second part is what is the "right" way to have this type of persisted data stored so you don't have to make round trips to the DB to populate common UI items. For this, I don't recommend storing EF objects. I would create POCO objects (View models or similar) that you cache. So in the example of your 50 states you might have something like this:
public class State
{
public string Abbreviation { get; set; }
public string Name { get; set; }
}
Then you would do something like this to create your cached list:
List<State> states = Context.StateData.Select(s => new State { Abbreviation = s.Abbreviation, Name = s.Name}).ToList();
Finally, whatever your caching solution is, it should implement an interface so you can mock that caching method for testing.
To do this without running into circular references or using reflection, you will need at least 3 assemblies:
Your MVC application
A class library to define your POCO objects and interfaces
A class library do perform your data access and caching (this can obviously be split into 2 libraries if that makes it easier to maintain and/or test)
That way you could have something like this in your MVC code:
ICache myCache = CacheFactory.CreateCache();
List<State> states = myCache.ListStates();
// populate your view model with states
Where ICache and State are in one library and your actual implementation of ICache is in another.
This is what I do for my standard architecture: splitting POCO objects and interfacees which are data access agnostic into a separate library from data access which is the separate from my MVC app.
Look into using a Dependency Injection tool such as unity, ninject, structuremap, etc. These will allow for the application level control you are looking for by implementing a kernel which holds on to objects in a very similar way to what you seem to be describing.

Separation of domain and ui layer in a composite

i'm wondering if there is a pattern how to separate the domain logic of a class from the ui responsibilities of the objects in the domain layer.
Example:
// Domain classes
interface MachinePart
{
CalculateX(in, out)
// Where do we put these:
// Draw(Screen) ??
// ShowProperties(View) ??
// ...
}
class Assembly : MachinePart
{
CalculateX(in, out)
subParts
}
class Pipe : MachinePart
{
CalculateX(in, out)
length, diamater...
}
There is an application that calculates the value X for machines assembled from many machine parts. The assembly is loaded from a file representation and is designed as a composite. Each concrete part class stores some data to implement the CalculateX(in,out) method to simulate behaviour of the whole assembly. The application runs well but without GUI. To increase the usability a GUi should be developed on top of the existing implementation (changes to the existing code are allowed). The GUI should show a schematic graphical representation of the assembly and provide part specific dialogs to edit several parameters.
To achieve these goals the application needs new functionality for each machine part to draw a schematic representation on the screen, show a property dialog and other things not related to the domain of machine simulation. I can think of some different solutions to implement a Draw(Screen) functionality for each part but i am not happy with each of them.
First i could add a Draw(Screen) method to the MachinePart interface but this would mix-up domain code with ui code and i had to add a lot of functionality to each machine part class what makes my domain model hard to read and hard to understand.
Another "simple" solution is to make all parts visitable and implement ui code in visitors but Visitor does not belong to my favorite patterns.
I could derive UI variants from each machine part class to add the UI implementation there but i had to check if each part class is suited for inheritance and had to be careful on changes to the base classes.
My currently favorite design is to create a parallel composite hierarchy where each component stores data to define a machine part, has implementation for UI methods and a factory method which creates instances of the corresponding domain classes, so that i can "convert" a UI assembly to a domain assembly. But there are problems to go back from the created domain hierarchy to the UI hierarchy for showing calculation results in the drawing for example (imagine some parts store some values during the calculation i want to show in the schematic representation after the simluation).
Maybe there are some proven patterns for such problems?
Agree with #Marjin, and to generalise his answer. What you need is Model-View-Controller of which MVP and MVVM are variants. From your comments I think you understand that, but need to understand how to implement the pattern. Without knowing your language & target architecture it's hard to give absolute specifics. Notwithstanding, I'd start with the Observer pattern (link has sample code).
The problem you're dealing with is how to provide observable access from the domain to the UI - without encumbering the domain with UI-specific code. Observer provides a means to do that. It does require domain changes, in particular to enable registration of observers and notification of changes. However there's nothing GUI-specific in that so it stays well encapsulated.
hth.
PS: If your app is a typical thin-client web app you'll need to modify the approach. And beware: lots of web app frameworks are advertised as "MVC", but the implementation is architecturally quite different to the Observer pattern.
You can take a look at the model-view-presenter (mvp) and model-view-viewmodel (mvvm) patterns.
Fowler's presentation model includes two sample applications; it also might be of interest to you.
I think that investigating these patterns will give you some ideas on how to continue. Mvvm looks a lot like your current solution; so i'd start there if I were you.
Maybe a View Helper can help. It's not a C++, but a Java EE pattern, but in your case it will definitely separate your domain objects from their presentation details...

BizTalk mapper and the [ThreadStatic] attribute

I've recently encountered an issue with the multi-threaded nature of the BizTalk Mapper and how it handles external assemblies.
As this quote from MSDN indicates:
Important Any code written in an
external assembly for use in a
scripting functoid needs to be thread
safe. This is required because
multiple instances of a map can use
these .NET instances at run time under
stress conditions.
The Mapper will reuse instances of external assemblies.
In a utility assembly my team was using we had the following code:
public class MapUtil
{
private string _storeReference;
public void SetStoreReference(string ref)
{
_storeReference = ref;
}
public string GetStoreReference()
{
return _storeReference;
}
}
This was causing storereferences from one file to be mapped to different files.
I (appear) to have fixed this by decorating the private field with [ThreadStatic]
[ThreadStatic]
private static string _storeReference;
My question is - does anyone know of any issues with this in the BizTalk Mapper? I'm aware that there are issues using [ThreadStatic] in Asp.Net for examble, due to threads being reused, but can find no documentation on the way the BizTalk mapper deals with threads.
I have used ThreadStatic to set a variable is custom receive pipeline and then access its value within BizTalk Map (through a helper class). have not got any problem so far - tested with ~50 invocations in parallel.
I've still not found a definitive statement along the lines of 'The threading behaviour within the BizTalk Mapper is xyz, so you should take care you use method abc' and I'm not sure that such an answer is going to come from anywhere outside the BizTalk product team.
My one colleague with direct contacts to the product team is on extended Christmas leave (lucky dog) so until he returns I just thought I'd note that with the change made to our code we have not seen a single recurrence of the threading issues on a high volume production server.
Well - that isn't quite true, I managed to miss the static keyword from one property on my helper class and for that property we did still see the threading issues. I'll take that as proof of ThreadStatic being the right way to go for now.

Resources