using System;
using System.Collections.Generic;
using System.Text;
namespace WmData {
///
/// The WmIntermediateObjectManager keeps a
/// collection of intermediate objects for both
/// WmData and WmDirectData. It is aimed to
/// overcome the drag that comes with the System.Reflection
/// namespace. By creating Intermediate objects, a speed gain
/// of approx. 80% is achieved.
///
public class WmIntermediateObjectManager {
protected List intermediateObjects;
protected WmDataBaseCredentials databaseCredentials;
public WmIntermediateObjectManager(WmDataBaseCredentials databaseCredentials){
intermediateObjects = new List();
this.databaseCredentials = databaseCredentials;
}
///
/// Returns an intermediate object,
/// if it does not exist than a threadsafe operation is carried out to create one.
/// It always returns something safely.
///
public WmIntermediateObject getIntermediateObject(Type objectType, bool createDatabaseTableIfNecessary) {
WmIntermediateObject returnObject = null;
string objectName = objectType.Name;
using (TimedLock.Lock(intermediateObjects)){
for (int i = 0; i < intermediateObjects.Count; i++) {
if (intermediateObjects[i].Name.Equals(objectName)) {
returnObject = intermediateObjects[i];
break; // stop searching, we've got 'm
}
}
if (returnObject == null) {
// It may appear silly, but do search for one more time to be sure that no other thread has created the object int the meanwhile:
for (int i = 0; i < intermediateObjects.Count; i++) {
if (intermediateObjects[i].Name.Equals(objectName)) {
returnObject = intermediateObjects[i];
break; // stop searching, we've got 'm
}
}
if (returnObject == null) { // as a last resort: create the intermediate object
returnObject = new WmIntermediateObject(objectType, databaseCredentials);
// Only check database backend if we're managing such a thing.
if (databaseCredentials != null && createDatabaseTableIfNecessary) {
// also check if the object has a table, otherwise create it:
if (!WmDataBaseCreator.isTableExistent(returnObject.TableName, databaseCredentials)) {
// If not, make a glorious attempt to create the table
WmDataBaseCreator.createTable(objectType, databaseCredentials);
}
}
intermediateObjects.Add(returnObject);
}
}
}
return returnObject;
}
public WmIntermediateObject getExistingIntermediateObjectByTableName(string tableName) {
WmIntermediateObject returnObject = null;
using (TimedLock.Lock(intermediateObjects)){
for (int i = 0; i < intermediateObjects.Count; i++) {
if (intermediateObjects[i].TableName.Equals(tableName)) {
returnObject = intermediateObjects[i];
break;
}
}
}
return returnObject;
}
}
}