checking if DB4o ObjectContainer is closed - db4o

DB4O doesn't seem to provide a method to check if the database (ObjectContainer) is closed. So right now, this is the code I use to see if it's closed. I get the feeling there is a better way to do this.
public ObjectContainer getDb() {
if (db == null) {
System.out.println("db was null in " + dbci
+ " connection. Had to create new DB object.");
db = Db4oEmbedded.openFile(dbci.getConnectionName());
}
try{
db.query();
}
catch(Exception e){
db = Db4oEmbedded.openFile(dbci.getConnectionName());
}
return db;
}
Is there a way around a try/catch block like this?

db4o does provide a method to check if the object container is closed or not.
Take a look in ExtObjectContainer#isClosed() method.
http://source.db4o.com/db4o/trunk/db4oj/core/src/com/db4o/ext/ExtObjectContainer.java
Hope this helps

Related

How to intercept delete and advise user it is not possible?

I am starting to develop with Breeze.js and ASP MVC+WebApi Controllers. I am concerned about securities, as we should all be concerned about the possibility of a hacker coming into play. Now I did find the BeforeSaveEntity intercept and it does seem to be exactly what I want to use on the server side. I managed to get the security I want on the server side, but how do I deal with it on the client side, in my case with AngularJS, what and how should I catch the output and deal with it? Let me show you some code sample I use on the server side:
public class ConferenceContextProvider : EFContextProvider<ConferenceContext>
{
public ConferenceContextProvider() : base() { }
// Creating the BeforeSaveEntity for Security purposes, see more details at http://www.breezejs.com/documentation/efcontextprovider#SaveInterception
protected override bool BeforeSaveEntity(EntityInfo entityInfo)
{
// return false if we don’t want the entity saved.if (entityInfo.Entity.GetType() == typeof(Role)
&& entityInfo.EntityState == EntityState.Deleted)
{
return false;
}
else
{
return true;
}
}
protected override Dictionary<Type, List<EntityInfo>> BeforeSaveEntities(Dictionary<Type, List<EntityInfo>> saveMap)
{
// return a map of those entities we want saved.
return saveMap;
}
}
and then on client side with AngularJS
// AngularJS DataService
function saveChanges() {
if (manager.hasChanges()) {
var promise =
manager.saveChanges()
.catch(queryFailed)
.finally(function (data) {
toastr.success('Save to DB Succeeded');
});
} else {
toastr.warning("Nothing to save");
};
}
How do I catch the result and deal with it? With Firebug I can see that the POST returns a JSON object with Entities array being filled (if user has access) or that same array being empty (if user has access denied). But if multiple changes happen, then the array might be filled with a portion of it applied. So what is the best approach on the client side with an access denied? Can someone give me a proper sample code on how to deal with acces denied? Thanks for your help
Overriding the BeforeSaveEntity method will mean that on the server once the payload it received your server will call the BeforeSaveEntity method once for each entity before the entity is saved. As the docs show if you return false it will simply not save the entity. Take note of the following line -
If the method returns false then the entity will be excluded from the
save. If the method throws an exception, the entire save is aborted
and the exception is returned to the client.
If you throw an HTTP error I think it should propagate properly you should be able to catch that error client side and display it. This is assuming if a payload contains an entity to delete you want to cancel the whole save.
Example -
protected override bool BeforeSaveEntity(EntityInfo entityInfo)
{
// throw http exception if there is an entity flagged for deletion
if (entityInfo.Entity.GetType() == typeof(Role)&& entityInfo.EntityState == EntityState.Deleted)
{
var response = new HttpResponseMessage(HttpStatusCode.BadRequest){ Content = new StringContent("Cannot delete an entity") };
throw new HttpResponseException(response);
}
else
{
return true;
}
}
And on your client-side query where you have a queryFailed method (pseudo code, examine the error that is thrown to construct this properly) -
function queryFailed (error) {
alert('Query failed - ' + error.message);
}
If you want to save all the other entities but this one and then return custom errors in the response you can do that as well but that will take additional customization and that would probably be a much more detailed answer

Neo4jClient create node exception

Can anyone point out why I get an exception when the .results point in the code is executed?
-- note the code has been edited after the quested was answered as per Tatham Oddie's comment. ---
public User Create(User user)
{
try
{
// Check if user exists
if (this.Exists(user.EmailAddress))
{
throw new Exception("User already exists");
}
else
{
var q = this._context.Client().Cypher
.Create("(n:User {f}")
.WithParam("f", "Mike")
.Return(n => n.As<User>());
return q.Results.Single();
}
}
catch (Exception e)
{
throw e;
}
}
Please do not write code like this: "(n:User {FirstName: '" + user.FirstName + "'}". It is a major security risk in your application, and a performance constraint.
Follow the example at https://github.com/Readify/Neo4jClient/wiki/cypher-examples#create-a-user which uses a parameter syntax.
It will be secure.
It will be faster.
It will work.
Got it. Syntax error. Missing bracket.

Disposing ObjectResult<T>

I've started using Entity Framework (database first), and I noticed that the methods the tt template generates for the context class (for stored procedures) have a return type ofObjectResult.
This type is IDisposable, but no sample code I can find actually calls the Dispose method. Is there a reason for this?
I currently don't have the "using" on the stored procedure call as I do further IEnumerable related stuff on the result (essentially just projecting the result set), but I could easily refactor that.
My question is, should I be using a pattern like the following if I have no reason to keep the connection to the database open:
using (var context = new DatabaseContext())
{
using (var result = context.spMyStoredProcedure(param1, param2))
{
return result.ToList();
}
}
I've seen some advice that even disposing the DbContext might not be needed, but there seems to be a lot of inconsistencies even on MSDN on what to do.
I decompiled ObjectResult<T> (EF4.) Here's its Dispose() method. It's creating other managed objects, like a DbDataReader. and an internal object called a Shaper that can own a database connection.
If you dispose it, you're trusting it to know what it's doing. If you don't, you trust yourself to know what it's doing, not doing, and why. I'd play it safe and dispose it.
public override void Dispose()
{
DbDataReader reader = this._reader;
this._reader = (DbDataReader) null;
this._nextResultGenerator = (NextResultGenerator) null;
if (reader != null && this._readerOwned)
{
reader.Dispose();
if (this._onReaderDispose != null)
{
this._onReaderDispose((object) this, new EventArgs());
this._onReaderDispose = (Action<object, EventArgs>) null;
}
}
if (this._shaper == null)
return;
if (this._shaper.Context != null && this._readerOwned)
this._shaper.Context.ReleaseConnection();
this._shaper = (Shaper<T>) null;
}

Asp.net MVC3, open connection

I open Database connection in my controller and pass the opened connection to my Model for using that connection.
but since 2nd time calling to the controller(Ajax), it return an error message that say 'Connection must be open.'
I reloaded page, and call the controller again then it works well. but for the 2nd time calling, it keep return that error message.
My controller has the code to open DB Connection, so I believed, it should open database for every processing(Calling). and the (open) code is in using{} block so after using it, it should be closed automatically.
but I think I'm doing wrong :(
here is my code,
public JsonResult myControllerMethod() // Action Controller
{
using (AdsConnection conn = new AdsConnection(connString))
{
conn.Open();
AdsTransaction txn = conn.BeginTransaction(); // Begin Transaction
try
{
MyModel mo = new MyModel();
mo.doProcess(conn); // pass connection to model
txn.Commit();
return Json(new { success = true });
}
catch (Exception e)
{
txn.Rollback();
return Json(new { success = false, message = e.Message });
}
}
}
MyModel
public void doProcess(AdsConncection conn){ // Model
try{
..
//AdsCommand select, update, delete and insert....
..
}catch(Exception e){
throw e;
}
}
Anybody know, what I am doing wrong? please advice me.
Thanks
You shouldn't pass a database connection to your view - your view should accept an object (as a model) that contains "solid" data. A view should have no logic of its own, and a Model's logic should only be concerned with modifying internal state, such as performing validation (not verification) or some internal data transformation. The task of populating a Model from a database should be done by the controller or a separate mapping class (or by some kind of "Populate" method of the model, but this method should be called and contained within the controller's action method).
That said, the problem you're experiencing is because you're using using() blocks. A using() block will always call the IDisposable.Dispose() method of its subject object, in this case a DB connection. SqlConnection.Dispose calls its .Close method, which is why the connection object is closed whenever the method returns.

Replace Sharp Architecture's NHibernate.config with a Fluent Configuration

By default, the solution generated from Sharp Architecture's templify package configures NHibernate using an NHibernate.config file in the {SolutionName}.Web project. I would like to replace it with a fluent configuration of my own and still have the rest of Sharp Architecture work correctly.
Any help will be much appreciated. :)
Solution: Here's how I got it to work:
IPersistenceConfigurer configurer = OracleClientConfiguration.Oracle10
.AdoNetBatchSize(500)
.ShowSql()
.ConnectionString(c => c.FromConnectionStringWithKey("NHibernate.Localhost"))
.DefaultSchema("MySchema")
.ProxyFactoryFactory("NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle")
.UseReflectionOptimizer();
NHibernateSession.Init(
webSessionStorage,
new string[] { Server.MapPath("~/bin/MyProject.Data.dll") },
new AutoPersistenceModelGenerator().Generate(),
null,
null,
null,
configurer);
iirc the NhibernateSession class that is used to configure nhibernate has a bunch of overloads one of them giving you the ability to configure it via code.
Very old post. I'll leave it here in case someone else is interested. On SharpArch 1.9.6.0 you can add two methods to NHibernateSession.cs. This will let you pass-in a FluentConfiguration object.
public static FluentConfiguration Init(ISessionStorage storage, FluentConfiguration fluentConfiguration)
{
InitStorage(storage);
try
{
return AddConfiguration(DefaultFactoryKey, fluentConfiguration);
}
catch
{
// If this NHibernate config throws an exception, null the Storage reference so
// the config can be corrected without having to restart the web application.
Storage = null;
throw;
}
}
private static FluentConfiguration AddConfiguration(string defaultFactoryKey, FluentConfiguration fluentConfiguration)
{
var sessionFactory = fluentConfiguration.BuildSessionFactory();
Check.Require(!sessionFactories.ContainsKey(defaultFactoryKey),
"A session factory has already been configured with the key of " + defaultFactoryKey);
sessionFactories.Add(defaultFactoryKey, sessionFactory);
return fluentConfiguration;
}

Resources