Asynchronous DAO in Flex / Sqlite? - sql

The article gives a good insight of how to deal with sqlite in Flex; but it doesn't get deep into how to tackle asynchronous data access.
For example, if I have an EmployeesDAO that does the followings:
updateEmployee(emp:Employee):void
findEmployee(emp:Employee):void
findAllEmployees():ICollectionView
etc..
As long as the EmployeesDAO implements asynchronous mode these methods are only legitimate after the db is connected and the tables are created. The client has to know about this asynchronous nature in order to use these methods as the following will throw an SQLErrorOperation as findAllEmployees will attempt to execute a "SELECT" operation before the db is connected:
var dao:IEmployeesDAO = new EmployeesDAO();
var employees:ArrayCollection = dao.findAllEmployees();
What is the best practice to deal with instantiation of the asynchronous DAO? Is it possible to hide the asynchronous nature from the client of the data access objects (i.e., the client isn't aware whether it's using sync or asynchronous DAOs)?

The only way I know to tackle a problem like that is to use pass the results to a callback. That's how we tackled listening to various async tokens or event messages.

What you are asking is not possible in the flash universe to my knowledge. In JS I know of only one project that effectively tackles this problem.
http://stratifiedjs.org tries to be javascript-like language with just some extra keywords to decide what you want to do in asynchronous situations and compiles to not-so-readeable but very performant JS behind the scenes.

Have a look: http://elromdesign.com/blog/2009/01/18/adobe-air-sqlite-manager-help-you-handle-your-database-easily/

There is a fundamental difference between asynchronous and sync programming and the client code has to be aware of that to use the service. The pattern for dealing with asynchronous database connectivity is to have the client pass callbacks to a specific operation invocation to handle the result (if successful) or fault (if operation failed). The callbacks can be encapsulated in things such as flash.net.Responder or mx.rpc.IResponder, etc.. In a LOB application, the life-cycle of the app is tied to the DB connectivity such that the moment the app attempts to start, DB connection has to either already be established (such as user being authenticated) or otherwise the UI locks the user out. After the DB connection has been established, all the DAO instances can get hold of the DB connection. Of course the subsequent operations on the DB still need to implement the callback patterns mentioned above.

Related

#RepositoryEventHandler only invoked via HTTP - why?

when I use a #RepositoryEventHandler then its methods are only invoked when the call into the repository comes in via HTTP.
Any reason why? OK, it is called Spring Data REST, but wouldn't it be VERY useful to invoke the handler too, when I call my Repo directly, not via HTTP?
Any way to invoke the handler when called directly (some magic AOP-stuff)?
Thank you
The reason for that is that the different persistence mechanisms covered by the different Spring Data modules already ship with event mechanisms. Depending on the one you use you now get a different mechanism to use.
Unfortunately this can't be unified as e.g. with JPA not all persistence operations need to go through the repository in the first place, as JPA automatically flushes all changes that were made to an attached instance on EntityManager flush. In this case even AOP on the repository instance doesn't help.
So you're basically left with two choices:
The events exposed by Spring Data REST for all repositories (as we basically don't make use of the automatic change tracking in JPA).
The store specific event mechanisms that will make sure that the persistence mechanism exposes events as documented.
I don't know if the solution I put below from other stackoverflow questions would seen as acceptable by #Olivier-drotbohm, but from:
SpringDataRest #RepositoryEventHandler not running when Controller is added
and
#RepositoryEventHandler events stop with #RepositoryRestController
you could inject/autowire the "ApplicationEventPublisher" and fire the BeforeCreateEvent/AfterCreateEvent manually to trigger the RepositoryEventHandler.
This is not a perfect solution, but I hope it is good enough for you (and we tested it: it works).

XSockets.Net - how to manage NHibernate Session Context

I wonder what is the best way to manage NHibernate Session Context
when using NH data layer from Xsockets controller.
Particularly I refer to self hosted winservice/console application or Azure worker role,
where HTTPContext is not available.
Of course there is always an option to create and dispose session per call, but that means a performance hit, so better reuse sessions in some way.
My controller provides API for CRUD operations in underlying NH repository and is pushing updates to relevant subscribers when certain records are updated in DB.
Your ideas appreciated :)
I'm using StructureMap to handle dependencies and create a NestedContainer to handle session per request. Don't have to mess with CurrentSessionContext or HttpContext anymore for storing session.
http://structuremap.github.io/the-container/nested-containers/
You could even just create a middleware UnitOfWork if you are using OWIN with WebAPI.
Since XSockets has state is will be bad for your database if you open the connection in the OnOpen event since the connection will remain open as long as the socket is open. Best is to use the repository only in the methods calling the CRUD operations as briefly as possible.
To get the instance of your repository should not be a bottleneck in this case.
I will be happy to review any code you might have.
Regards
Uffe

How should one write an XPC service with state?

I've read the NSXPC* docs, which advise making the vended service as stateless as possible. It's a good idea, at least to the docs and examples I've read, since the service and the calling app see each other as singletons and only one instance of the service runs at a time. This means that the methods are essentially non-member functions (to use a C++ term).
Why do I want to get around this? I want to put the network code into a XPC. Since the XPC will be working with a GUI app, which will have multiple windows, I need to support multiple simultaneous connections. That doesn't work with singletons, at least directly.
The network API is C-based, with the main state type a pointer to a custom struct. So why don't we do something similar:
Have the creation function return a value type, like NSUUID or something. (Passing a pointer across processes would be a bad idea.)
In the service, create a NSDictionary (or std::map or whatever) mapping between the NSUUID and the API C-pointer.
The various service APIs take the UUID and convert it to the C-pointer to use the network API.
Aside: Since the token is random, if the XPC service crashes, the main app will have a token that's useless after the XPC is restarted. Maybe I should a URL (which would have all the information to restart) instead. But then we get potential conflicts if two connections happen to be to the same server. Maybe I can combine the ideas with the token being a URL/UUID pair. (The UUID value would move from being returned by the service to supplied by the main app.)
Would this be a good way to implement state-full XPCs?
You may want to add a method to your service interface which replies with a long-lived proxy object. You can arrange for this to happen by means of a call to -[NSXPCInterface setInterface:forSelector:argumentIndex:ofReply:], passing YES for the last parameter. Details are available here:
https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSXPCInterface_reference/#//apple_ref/occ/instm/NSXPCInterface/setInterface:forSelector:argumentIndex:ofReply:

Best Practice for WCF Service Proxy lifetime?

When working with WCF services, is it better to create a new instance of the service every time you use it? Or is it better to create one and re-use it? Why is either approach better? Is it the same for asynchronous proxies?
Or is it better to create one and re-use it?
Do not start to implement your own pooling implementation. That has already been done in the framework. A WCF proxy uses cached channels factories underneath. Therefore, creating new proxies is not overly expensive (but see Guy Starbuck's reply regarding sessions and security!).
Also be aware that a proxy times out after a certain idle time (10mins by default).
If you want more explicit control you might consider using ChannelFactories and channels directly instead of the "easy to go, full out of the box" ClientBase proxies.
http://msdn.microsoft.com/en-us/library/ms734681.aspx
And a "must read" regarding this topic is:
http://blogs.msdn.com/wenlong/archive/2007/10/27/performance-improvement-of-wcf-client-proxy-creation-and-best-practices.aspx
in addition to the things Guy Starbuck mentioned a key factor would be the security model you're using (in conjunction with the session requirements) - if you don't re-use your proxy, you can't re-use a security sessions.
This means that the client would have to authenticate itself with each call which is wasteful.
If, however, you decide this is what you wish to do, make sure to configure the client to not establish a security context (as you will never use it), this will save you a couple of roundtrips to the server :-)
One more point to consider is channel faults. By design WCF does not allow to use client proxy after unhandled exception happened.
IMyContract proxy = new MyContractClient( );
try
{
proxy.MyMethod( );
}
catch
{}
//Throws CommunicationObjectFaultedException
proxy.MyMethod( );
There is a corollary here to Server Activated Objects in .NET Remoting (one of the technologies that is replaced by WCF), which have two modes, "Single Call" (stateless) and "Singleton" (stateful).
The approach you take in WCF should be based on your performance and scaling requirements in conjunction with the needs of your consumers, as well as server-side design constraints.
If you have to maintain state between calls to the service, then you will obviously want to have a stateful instance, but if you don't you should probably implement it so that it is static, which should scale better (you can more easily load balance, etc).

NHibernate session management in Windows Service applications

I'm developing and application that runs as a Windows service. There are other components which include a few WCF services, a client GUI and so on - but it is the Windows service that access the database.
So, the application is a long-running server, and I'd like to improve its performance and scalability, I was looking to improve data access among other things. I posted in another thread about second-level caching.
This post is about session management for the long-running thread that accesses the database.
Should I be using a thread-static context?
If so, is there any example of how that would be implemented.
Every one around the net who is using NHibernate seem to be heavily focussed on web-application style architectures. There seems to be a great lack of documentation / discussion for non-web app designs.
At the moment, my long running thread does this:
Call 3 or 4 DAO methods
Verify the state of the detached objects returned.
Update the state if needed.
Call a couple of DAO methods to persist the updated instances. (pass in the id of the object and the instance itself - the DAO will retrieve the object from the DB again, and set the updated values and session.SaveOrUpdate() before committing the transaction.
Sleep for 'n' seconds
Repeat all over again!
So, the following is a common pattern we use for each of the DAO methods:
Open session using sessionFactory.OpenSession()
Begin transaction
Do db work. retrieve / update etc
Commit trans
(Rollback in case of exceptions)
Finally always dispose transaction and session.Close()
This happens for every method call to a DAO class.
I suspect this is some sort of an anti-pattern the way we are doing it.
However, I'm not able to find enough direction anywhere as to how we could improve it.
Pls note, while this thread is running in the background, doing its stuff, there are requests coming in from the WCF clients each of which could make 2-3 DAO calls themselves - sometimes querying/updating the same objects the long running thread deals with.
Any ideas / suggestions / pointers to improve our design will be greatly appreciated.
If we can get some good discussion going, we could make this a community wiki, and possbily link to here from http://nhibernate.info
Krishna
There seems to be a great lack of documentation / discussion for non-web app designs.
This has also been my experience. However, the model you are following seems correct to me. You should always open a session, commit changes, then close it again.
This question is a little old now, but another technique would be to use Contextual Sessions rather than creating a new session in each DAO.
In our case, we're thinking of creating the session once per thread (for our multi-threaded win32 service), and make it available to the DAOs using either a property that returns SessionFactory.GetCurrentSession() (using the ThreadContext current session provider, so it's session-per-thread) or via DI (dependency injection - once again using ThreadContext.)
More info on GetCurrentSession and Contextual Sessions here.
You can also flush the session without actually closing it and it achieves the same thing. I do.
We've recently started using an IoC container to manage session lifecycle, as a replacement for the contextual sessions mentioned above. (More details here).
I agree, there aren't many examples for stateful apps.
I'm thinking of doing the following:
Like you I have a windows service hosting a number of WCF services. So the WCF services are the entry points.
Ultimately all my WCF services inherit from AbstractService - which handles a lot of logging and basic DB inserts/updates.
In one of the best NHibernate posts I've seen, a HttpModule does the following:
see http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx
private void BeginTransaction(object sender, EventArgs e) {
NHibernateSessionManager.Instance.BeginTransaction();
}
private void CommitAndCloseSession(object sender, EventArgs e) {
try {
NHibernateSessionManager.Instance.CommitTransaction();
}
finally {
NHibernateSessionManager.Instance.CloseSession();
}
}
So perhaps I should do something similar in AbstractService. So effectively I'll end up with a session per service invocation. If you examine the NHib best practices article link above, you'll see that the NHibernateSessionManager should deal with everything else, as long as I open and close the session (AbstractService constructor and destructor).
Just a thought. But I'm experiencing errors because my session seems to be hanging around for too long, and I'm getting the infamous error - NHibernate.AssertionFailure: null id in entry (don't flush the Session after an exception occurs).