I'm investigating optimistic concurrency in NHibernate. I have a scenario that is very similar to what is being described here:
http://weblogs.asp.net/stefansedich/archive/2008/10/01/set-the-value-of-a-version-column-in-nhibernate-manually.aspx
Would you recommend going with the proposed solution in this blog post?
Thanks
The blog suggests using an interceptor to re-load the current version number from the database in order to perform a manual version check with the version passed in through the entity from a DTO object. This would certainly work, but as described in the article, it adds an extra DB hit to load the current version number.
The better solution, which seems pretty obvious since it's actually what's described in the documentation for "Application version checking" as described and quoted in that blog entry. That is, perform the version check on the initially loaded entity using the DTO's version. More specifically, using the code from the article (changes to the article's code are bold):
public void Update(MyDTO dto) {
// Select the item.
var item = this.repository.SelectById(dto.Id);
// Verify there hasn't been a concurrent change
if(item.Version != dto.Version)
{
throw new StaleObjectStateException();
}
// Map values from DTO to model.
item.Name = dto.Name;
item.Version = dto.Version;
// Call update
this.repository.Update(item);
}
Related
I'm working through a basic example of working with NEventStore with RavenDB and I've hit a stumbling block.
I've managed to succesfully commit my events to the RavenDB datasource, but now I need to pull them back out, to replay them (CQRS - ES) pattern.
I can bring back the Collection of EventMesssage objects by usng the NEventStore IStoreEvents Unterface like this :-
public IEnumerable<EventMessage> GetEvents(Guid aggregateRootId)
{
using (var stream = _store.OpenStream(aggregateRootId, 0))
{
return stream.CommittedEvents;
}
}
In each EventMessage, I can access the Header & the Body Properties. In the body property is the actual event that i have submitted, which i want to pull out and inspect.
I'm not sure if what I'm trying to achieve is correct.
Should I be using the Raven IDocumentStore class to retrieve the event objects or should this be done via NEventstore Stream.
At basic level what you're doing is correct: it's the same code shown in the quick-start NEventstore sample code.
If you work in a more DDD context, probably you should emit events from your Aggregates using the CommonDomain library that is embedded in NEventStore, and retrieve them from IRepository Interface.
You could find some example in the web.
One of them is a my training project: https://github.com/williamverdolini/CQRS-ES-Todos (some notes about that). I'm not using RavenDB and I'm still learnig...but could be useful ;-)
I want to change my RavenDB "schema" and perform a Migration at startup of ASP.Net MVC web app.
Patching mechanism seems to fit the purpose, and I try to use it like:
store.DatabaseCommands.UpdateByIndex(
"Raven/DocumentsByEntityName",
new IndexQuery
{
Query = "Tag:LogEntries",
},
new ScriptedPatchRequest()
{
Script = #"
this.IsDeleted = false;
"
}
).WaitForCompletion();
The problem is, that Patch will simply throw exception if the index is stale. But I really need to be sure that Migration was performed before continue to run the app. Are there better alternatives than wrapping it in something like:
while (true)
{
try
{
RunPatch();
break;
}
catch (Exception)
{
}
}
With Entity Framework or NHibernate (FluentMigrations) it's easy to write a Migration class, assign a Version to it, and then needed Migrations will be executed automatically in proper order.
Is there a similar built-in mechanism for Raven? Or any known best-practices for that?
Here's an answer, albeit 6 years after you asked! There is the RavenMigrations project on GitHub here:
https://github.com/migrating-ravens/RavenMigrations
This is a migration framework for RavenDB, similar to those that you will find for relational databases.
Restlet looks cool, but Im sorry, I'm just banging my head all day due to lack of documentation on a simple client.
I've managed to crib some useful stuff from
http://restlet.org/learn/guide/2.1/core/resource/client
But there is just nothing that actually works as a full download (which would be nice). For example is the Customer here a pojo only ? or must it implement Serializable (I think it must).
My specific issue is as follows:
I have some code which makes a call to a URL and gets back this:
{"result":"success","data":{"last_local":{"value":"889.66000","value_int":"88966000","display":"$889.66","display_short":"$889.66","currency":"USD"},"last":{"value":"889.66000","value_int":"88966000","display":"$889.66","display_short":"$889.66","currency":"USD"},"last_orig":{"value":"889.66000","value_int":"88966000","display":"$889.66","display_short":"$889.66","currency":"USD"},"last_all":{"value":"889.66000","value_int":"88966000","display":"$889.66","display_short":"$889.66","currency":"USD"},"buy":{"value":"889.00000","value_int":"88900000","display":"$889.00","display_short":"$889.00","currency":"USD"},"sell":{"value":"889.66000","value_int":"88966000","display":"$889.66","display_short":"$889.66","currency":"USD"},"now":"1388846889233438"}}
The bit I'm struggling with, is the MAGIC that happens as follows:
ClientResource cr = new ClientResource(….); // fine
IDataStruct resource = cr.wrap(IDataStruct.class); // <---- Magic here, but fine at Runtime.
if(cr.getResponse().getStatus().isSuccess()) // fine
{
PriceObject price = resource.retrieve();//<--- get to this line but then everything blows up because no converter is found. I can't use Jackson because GAE does not like it
}
The question is, what should the IDataStruct interface look like ??
Will.
Customer in the example is indeed a POJO. Depending on the converter you would use, you can make it serializable or not. BTW, Jackson should work on GAE, which issue did you encounter exactly?
IDataStruct should be a Java interface annotated with Restlet API annotations such as #Get, #Post, etc.
Regarding the user guide, you can find the edited version in GitHub, where I just fixed some of the broken links (will be published soon on Restlet.org):
https://github.com/restlet/restlet-sites/blob/master/modules/org.restlet/learn/guide/2.1/introduction/first-steps/first-client.md
The code:
public ChatMessage[] GetAllMessages(int chatRoomId)
{
using (ChatModelContainer context = new ChatModelContainer(CS))
{
//var temp = context.ChatMessages.ToArray();
ChatRoom cr = context.ChatRooms.FirstOrDefault(c => c.Id == chatRoomId);
if (cr == null) return null;
return cr.ChatMessages.ToArray();
}
}
The problem:
The method (part of WCF-service) returns an empty array. If I uncomment the commented line it starts working as expected. I have tried turning of lazy loading but it didnt help.
Also, when it works, I get ChatMessages with a reference to ChatRoom populated but not the ChatParticipant. They are both referenced by the ChatMessage-entity in the schema with both Id and Navigation Properties. The Ids are set and points to the right entities but on the client-side only the ChatRoom-reference has been populated.
Related questions:
Is an array the preferred method to return collections of EF-entities like this?
When making a change in my model (edmx) Im required to run the "Generate Database from Model..."-option before I can run context.CreateDatabase(). Why? I get some error message pointing to old SSDL but I cant find where the SSDL is stored. Is this created when I run this "Generate Database..."-option?
Is it safe to return entire entity-graphs to the client? Ive read some about "circular reference exeptions" but is this fixed in EF4?
How and when is references populated in EF4? If I have lazy-loading turned on I suspect only entities I touch is populated? But with lazy loading turned off, should the entire graph be populated always then?
Are there any drawbacks of using self-updating entities over ordinary entities in EF4? I dont need self-updating right now but I might do later. Can I upgrade easily or should I start with self-updating from the start?
Why cant I use entity-keys with type string?
Each of your questions needs a separate answer, but I'll try to answer them as briefly as possible.
First of all, in the code sample you provided, you get a ChatRoom object and then try to access a related object that is not included in your query (ChatMessages). If lazy loading is turned off as you had suggested, then you will need the Include("ChatMessages") call in your query, so your LINQ query should look like this:
ChatRoom cr = context.ChatRooms.Include("ChatMessages").FirstOrDefault(c => c.Id == chatRoomId);
Please ensure that your connection string is in your config file as well.
For the related questions:
You can return collections in any way you choose - I have typically done them in a List object (and I think that's the common way), but you could use arrays if you want. To return as a list, use the .ToList() method call on your query.
I don't understand what you're trying to do here, are you using code to create your database from your EDMX file or something? I've typically used a database-first approach, so I create my tables etc then update my EDMX from the database. Even if you generate your DB from your model, you shouldn't have to run CreateDatabase in code, you should be able to run the generated script against your DB. If you are using code-only then you need to dump the EDMX file.
You can generally return entity graphs to the client, should handle ok.
EF4 should only populate what you need. If you use lazy loading, it will automatically load things that you do not include in your LINQ query when you reference them and execute the query (e.g. do a ToList() operation). This won't work so well if your client is across a physical boundary (eg a service boundary) obviously :) If you don't use lazy loading, it will load what you tell it to in your query and that is all.
Self tracking entities are used for n-tier apps, where objects have to be passed across physical boundaries (eg services). They come with an overhead of generated code for each object to keep track of its changes, they also generate POCO objects which are not dependent on EF4 (but obviously contain generated code that would make the tracked changes work with the EF4 tracker). I'd say it depends on your usage, if you're building a small app that's quite self contained, and don't really care about separation for testability without the infrastructure in place, then you don't need to use self tracking entities. I say only use framework features when you need them, so if you're not writing an enterprise scale application (enterprise doesn't have to be big, but something scalable, highly testable, high quality etc) then no need to go for self tracking POCOs.
I haven't tried but you should be able to do that - that would be a candidate for a separate question if you can't get it to work :)
I'd like to ensure, that when I'm persisting any data to the database, using Fluent NHibernate, the operations are executed inside a transaction. Is there any way of checking that a transaction is active via an interceptor? Or any other eventing mechanism?
More specifically, I'm using the System.Transaction.TransactionScope for transaction management, and just want to stop myself from not using it.
If you had one place in your code that built your session, you could start the transaction there and fix the problem at a stroke.
I haven't tried this, but I think you could create a listener implementing IFlushEventListener. Something like:
public void OnFlush(FlushEvent #event)
{
if (!#event.Session.Transaction.IsActive)
{
throw new Exception("Flushing session without an active transaction!");
}
}
It's not clear to me (and Google didn't help) exactly when OnFlush is called. There also may be an implicit transaction that could set IsActive to true.
If you had been using Spring.Net for your transaction handling, you could use an anonymous inner object to ensure that your DAOs/ServiceLayer Objects are always exposed with a TransactionAdvice around their service methods.
See the spring documentation for an example.
To what end? NHProf will give you warnings if you're not executing inside a transaction. Generally you should be developing with this tool open anyway...