Datei: NDODLL/PersistenceManagerBase.cs
Last Commit (6e13ce2)
| 1 | // |
| 2 | // Copyright (c) 2002-2024 Mirko Matytschak |
| 3 | // (www.netdataobjects.de) |
| 4 | // |
| 5 | // Author: Mirko Matytschak |
| 6 | // |
| 7 | // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated |
| 8 | // documentation files (the "Software"), to deal in the Software without restriction, including without limitation |
| 9 | // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the |
| 10 | // Software, and to permit persons to whom the Software is furnished to do so, subject to the following |
| 11 | // conditions: |
| 12 | |
| 13 | // The above copyright notice and this permission notice shall be included in all copies or substantial portions |
| 14 | // of the Software. |
| 15 | // |
| 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED |
| 17 | // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL |
| 18 | // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF |
| 19 | // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
| 20 | // DEALINGS IN THE SOFTWARE. |
| 21 | |
| 22 | using System; |
| 23 | using System.Collections.Generic; |
| 24 | using System.Linq; |
| 25 | using System.IO; |
| 26 | using System.Data; |
| 27 | using System.Threading.Tasks; |
| 28 | using NDOInterfaces; |
| 29 | using NDO.Mapping; |
| 30 | using NDO.Application; |
| 31 | using NDO.SchemaGenerator; |
| 32 | using System.Reflection; |
| 33 | using Microsoft.Extensions.DependencyInjection; |
| 34 | using Microsoft.Extensions.Logging; |
| 35 | using NDO.ProviderFactory; |
| 36 | |
| 37 | namespace NDO |
| 38 | { |
| 39 | ····/// <summary> |
| 40 | ····/// Provides base functionality for PersistenceManager classes |
| 41 | ····/// </summary> |
| 42 | ····public class PersistenceManagerBase : IPersistenceManagerBase |
| 43 | ····{ |
| 44 | ········internal Cache cache = new Cache(); |
| 45 | ········/// <summary> |
| 46 | ········/// The DataSet used as template for DataRows |
| 47 | ········/// </summary> |
| 48 | ········protected DataSet ds = null; |
| 49 | ········/// <summary> |
| 50 | ········/// The StateManager instance which will be used for all objects |
| 51 | ········/// </summary> |
| 52 | ········protected IStateManager sm; |
| 53 | ········internal Mappings mappings;··// protected will make the compiler complaining |
| 54 | ········private IServiceProvider scopedServiceProvider; |
| 55 | ········private IServiceScope scope; |
| 56 | ········/// <summary> |
| 57 | ········/// Gets or sets the logger for the PersistenceManager instance |
| 58 | ········/// </summary> |
| 59 | ········protected ILogger Logger { get; set; } |
| 60 | ········bool isClosing = false; |
| 61 | ········private INDOProviderFactory providerFactory; |
| 62 | ········private NDOPersistenceHandlerManager persistenceHandlerManager; |
| 63 | ········/// <summary> |
| 64 | ········/// Gets the PersistenceHandlerManager instance |
| 65 | ········/// </summary> |
| 66 | ········public NDOPersistenceHandlerManager PersistenceHandlerManager => persistenceHandlerManager; |
| 67 | |
| 68 | ········/// <summary> |
| 69 | ········/// Provides the ProviderFactory to inherited persistence managers; |
| 70 | ········/// </summary> |
| 71 | ········protected INDOProviderFactory ProviderFactory |
| 72 | ········{ |
| 73 | ············get |
| 74 | ············{ |
| 75 | ················if (this.providerFactory == null) |
| 76 | ················{ |
| 77 | ····················var serviceProvider = NDOApplication.ServiceProvider; |
| 78 | |
| 79 | ····················if (serviceProvider != null) |
| 80 | ····················{ |
| 81 | ························this.providerFactory = serviceProvider.GetService<INDOProviderFactory>(); |
| 82 | ····················} |
| 83 | |
| 84 | ····················if (this.providerFactory == null) |
| 85 | ····················{ |
| 86 | ························this.providerFactory = NDOProviderFactory.Instance; |
| 87 | ····················} |
| 88 | ················} |
| 89 | |
| 90 | ················return this.providerFactory; |
| 91 | ············} |
| 92 | ········} |
| 93 | |
| 94 | |
| 95 | ········/// <summary> |
| 96 | ········/// If set to true, the resultset of each query is stored, so that results of an identical query |
| 97 | ········/// can be read from the cache. |
| 98 | ········/// </summary> |
| 99 | ········/// <remarks> |
| 100 | ········/// NDO computes an SHA256 hash for each query including the query parameters. The hash is the key to the query cache. |
| 101 | ········/// Do not use the QueryCache in applications, which work with one PersistenceManager |
| 102 | ········/// over a long time with multiple transactions. |
| 103 | ········/// </remarks> |
| 104 | ········public bool UseQueryCache { get; set; } |
| 105 | |
| 106 | ········private Dictionary<string, object> queryCache = new Dictionary<string, object>(); |
| 107 | |
| 108 | ········/// <summary> |
| 109 | ········/// This is the query cache in which resultsets can be stored. |
| 110 | ········/// </summary> |
| 111 | ········/// <remarks>Usually you won't have to access the query cache.</remarks> |
| 112 | ········public Dictionary<string, object> QueryCache => this.queryCache; |
| 113 | |
| 114 | ········/// <summary> |
| 115 | ········/// Register a listener to this event, if you have to provide user generated ids. |
| 116 | ········/// This event is usefull for databases, which doesn't provide auto-incremented ids, like the Oracle Db. |
| 117 | ········/// The event will be fired if a new id is needed. |
| 118 | ········/// </summary> |
| 119 | ········public event IdGenerationHandler IdGenerationEvent; |
| 120 | |
| 121 | ········/// <summary> |
| 122 | ········/// Constructor |
| 123 | ········/// </summary> |
| 124 | ········public PersistenceManagerBase( IServiceProvider scopedServiceProvider ) |
| 125 | ········{ |
| 126 | ············this.scopedServiceProvider = scopedServiceProvider; |
| 127 | ············string baseDir = AppDomain.CurrentDomain.BaseDirectory; |
| 128 | ············if (File.Exists( Path.Combine( baseDir, "Web.config" ) )) |
| 129 | ················baseDir = Path.Combine( baseDir, "bin" ); |
| 130 | ············var entryAssemblyName = Assembly.GetEntryAssembly()?.GetName()?.Name; |
| 131 | ············List<string> paths = new List<string>(); |
| 132 | ············if (entryAssemblyName != null) |
| 133 | ············paths.Add( Path.Combine( baseDir, $"{entryAssemblyName}.ndo.mapping" ) ); |
| 134 | ············paths.Add( Path.Combine( baseDir, "NDOMapping.xml" ) ); |
| 135 | ············ |
| 136 | ············bool found = false; |
| 137 | ············foreach (var path in paths) |
| 138 | ············{ |
| 139 | ················if (File.Exists(path)) |
| 140 | ················{ |
| 141 | ····················Init( path ); |
| 142 | ····················found = true; |
| 143 | ····················break; |
| 144 | ················} |
| 145 | ············} |
| 146 | ············if (!found) |
| 147 | ················throw new NDOException( 49, $"Can't determine the path to the mapping file. Tried the following locations:\n{string.Join("\n", paths)}\nPlease provide a mapping file path as argument to the PersistenceManager ctor." ); |
| 148 | ········} |
| 149 | |
| 150 | ········/// <summary> |
| 151 | ········/// Constructs a PersistenceManagerBase object using the path to a mapping file. |
| 152 | ········/// </summary> |
| 153 | ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param> |
| 154 | ········/// <param name="pathToMappingFile"></param> |
| 155 | ········public PersistenceManagerBase(string pathToMappingFile, IServiceProvider scopedServiceProvider) |
| 156 | ········{ |
| 157 | ············this.scopedServiceProvider = scopedServiceProvider; |
| 158 | ············Init(pathToMappingFile); |
| 159 | ········} |
| 160 | |
| 161 | ········/// <summary> |
| 162 | ········/// Constructs a PersistenceManagerBase object using the mapping object. |
| 163 | ········/// </summary> |
| 164 | ········/// <param name="mapping"></param> |
| 165 | ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param> |
| 166 | ········public PersistenceManagerBase(NDOMapping mapping, IServiceProvider scopedServiceProvider) |
| 167 | ········{ |
| 168 | ············this.scopedServiceProvider = scopedServiceProvider; |
| 169 | ············var localMappings = mapping as Mappings; |
| 170 | ············if (localMappings == null) |
| 171 | ················throw new ArgumentException( "The mapping must be constructed by a PersistenceManager", nameof( mapping ) ); |
| 172 | |
| 173 | ············Init( localMappings ); |
| 174 | ········} |
| 175 | |
| 176 | ········/// <summary> |
| 177 | ········/// Initializes a PersistenceManager using the path to a mapping file |
| 178 | ········/// </summary> |
| 179 | ········/// <param name="mappingPath"></param> |
| 180 | ········protected virtual void Init(string mappingPath) |
| 181 | ········{ |
| 182 | ············if (!File.Exists(mappingPath)) |
| 183 | ················throw new NDOException(45, String.Format("Mapping File {0} doesn't exist.", mappingPath)); |
| 184 | |
| 185 | ············Init( new Mappings( mappingPath, ProviderFactory ) ); |
| 186 | ········} |
| 187 | |
| 188 | ········/// <summary> |
| 189 | ········/// Initializes the persistence manager |
| 190 | ········/// </summary> |
| 191 | ········/// <remarks> |
| 192 | ········/// Note: This is the method, which will be called from all different ways to instantiate a PersistenceManagerBase. |
| 193 | ········/// </remarks> |
| 194 | ········/// <param name="mappings"></param> |
| 195 | ········internal virtual void Init( Mappings mappings ) |
| 196 | ········{ |
| 197 | ············Logger = NDOApplication.ServiceProvider.GetService<ILoggerFactory>()?.CreateLogger( GetType() ); |
| 198 | ············this.mappings = mappings; |
| 199 | ············this.persistenceHandlerManager = new NDOPersistenceHandlerManager( this.ServiceProvider, this.mappings ); |
| 200 | ············this.ds = new NDODataSet( this.mappings, ProviderFactory );··// Each PersistenceManager instance must have it's own DataSet. |
| 201 | ········} |
| 202 | |
| 203 | ········/// <summary> |
| 204 | ········/// Used by PersistenceManagers, to get an owner supplied id. |
| 205 | ········/// </summary> |
| 206 | ········/// <param name="t">Type of the object, the id is intended for.</param> |
| 207 | ········/// <param name="oid">ObjectId object which will hold the id value.</param> |
| 208 | ········protected void FireIdGenerationEvent(Type t, ObjectId oid) |
| 209 | ········{ |
| 210 | ············if (IdGenerationEvent != null) |
| 211 | ················IdGenerationEvent(t, oid); |
| 212 | ········} |
| 213 | |
| 214 | |
| 215 | ········Dictionary<string,Class> myClassesName; |
| 216 | ········Dictionary<Type, Class> myClassesType; |
| 217 | |
| 218 | ········/// <summary> |
| 219 | ········/// Initializes the class mappings |
| 220 | ········/// </summary> |
| 221 | ········protected void InitClasses() |
| 222 | ········{ |
| 223 | ············int cnt = mappings.Classes.Count(); |
| 224 | ············myClassesName = new Dictionary<string, Class>(cnt); |
| 225 | ············myClassesType = new Dictionary<Type, Class>(cnt); |
| 226 | ············foreach(Class cl in mappings.Classes) |
| 227 | ············{ |
| 228 | ················myClassesName.Add(cl.FullName, cl); |
| 229 | ················myClassesType.Add(cl.SystemType, cl); |
| 230 | ············} |
| 231 | ········} |
| 232 | ········ |
| 233 | |
| 234 | ········internal Class GetClass(string name) |
| 235 | ········{ |
| 236 | ············if (!myClassesName.ContainsKey(name)) |
| 237 | ················throw new NDOException(17, "Can't find mapping information for class " + name); |
| 238 | |
| 239 | ············return myClassesName[name]; |
| 240 | ········} |
| 241 | |
| 242 | ········internal Class GetClass(IPersistenceCapable pc) |
| 243 | ········{ |
| 244 | ············return GetClass(pc.GetType()); |
| 245 | ········} |
| 246 | |
| 247 | ········internal Class GetClass(Type type) |
| 248 | ········{ |
| 249 | ············Type t = type; |
| 250 | |
| 251 | ············if (type.IsGenericType) |
| 252 | ················t = type.GetGenericTypeDefinition(); |
| 253 | |
| 254 | ············if (! myClassesType.ContainsKey(t)) |
| 255 | ················throw new NDOException(17, "Can't find mapping information for class " + t.FullName); |
| 256 | |
| 257 | ············return myClassesType[t]; |
| 258 | |
| 259 | ········} |
| 260 | |
| 261 | ········internal Field GetField(Class cl, string field) |
| 262 | ········{ |
| 263 | ············Field f = cl.FindField(field); |
| 264 | ············if (f == null) |
| 265 | ················throw new NDOException(7, "Can't find mapping information for field " + cl.FullName + "." + field); |
| 266 | ············return f; |
| 267 | ········} |
| 268 | |
| 269 | ········/// <summary> |
| 270 | ········/// Hilfsfunktion |
| 271 | ········/// Liefert die Tabelle im DataSet ab, in der die DataRows des Datentyps liegen |
| 272 | ········/// </summary> |
| 273 | ········/// <param name="t">Data type</param> |
| 274 | ········/// <returns></returns> |
| 275 | ········protected DataTable GetTable(Type t) |
| 276 | ········{ |
| 277 | ············return GetTable(GetClass(t).TableName); |
| 278 | ········} |
| 279 | |
| 280 | ········/// <summary> |
| 281 | ········/// Hilfsfunktion |
| 282 | ········/// Liefert die Tabelle im DataSet ab, in der die DataRow des Objekts liegt |
| 283 | ········/// </summary> |
| 284 | ········/// <param name="pc"></param> |
| 285 | ········/// <returns></returns> |
| 286 | ········protected DataTable GetTable(IPersistenceCapable pc) |
| 287 | ········{ |
| 288 | ············return GetTable(GetClass(pc).TableName); |
| 289 | ········} |
| 290 | |
| 291 | |
| 292 | ········/// <summary> |
| 293 | ········/// Retrieve a table with the given name |
| 294 | ········/// </summary> |
| 295 | ········/// <param name="name">Table name</param> |
| 296 | ········/// <returns></returns> |
| 297 | ········protected DataTable GetTable(string name) |
| 298 | ········{ |
| 299 | ············DataTable dt = ds.Tables[name]; |
| 300 | ············if (dt == null) |
| 301 | ················throw new NDOException(39, "Can't find table '" + name + "' in the schema. Check your mapping file."); |
| 302 | ············return dt; |
| 303 | ········} |
| 304 | |
| 305 | ········/// <summary> |
| 306 | ········/// Gets a DataRow for a given object; if necessary the row will be constructed |
| 307 | ········/// </summary> |
| 308 | ········/// <param name="pc">Persistence capable object</param> |
| 309 | ········/// <returns></returns> |
| 310 | ········protected DataRow GetDataRow(IPersistenceCapable pc) |
| 311 | ········{ |
| 312 | ············DataRow row; |
| 313 | ············if ((row = this.cache.GetDataRow(pc)) != null) |
| 314 | ················return row; |
| 315 | ············return null; |
| 316 | ········} |
| 317 | |
| 318 | ········/// <summary> |
| 319 | ········/// Indicates, if there is a listener registered for the IdGenerationEvent. |
| 320 | ········/// </summary> |
| 321 | ········public bool HasOwnerCreatedIds |
| 322 | ········{ |
| 323 | ············get { return IdGenerationEvent != null; } |
| 324 | ········} |
| 325 | |
| 326 | ········/// <summary> |
| 327 | ········/// Gets the IServiceProvider instance of the current scope. |
| 328 | ········/// If no ServiceProvider was passed in the constructor, a new scope is created. |
| 329 | ········/// </summary> |
| 330 | ········internal IServiceProvider ServiceProvider |
| 331 | ········{ |
| 332 | ············get |
| 333 | ············{ |
| 334 | ················if (this.scopedServiceProvider == null) |
| 335 | ················{ |
| 336 | ····················this.scope = NDOApplication.ServiceProvider.CreateScope(); |
| 337 | ····················this.scopedServiceProvider = scope.ServiceProvider; |
| 338 | ················} |
| 339 | |
| 340 | ················return this.scopedServiceProvider; |
| 341 | ············} |
| 342 | ········} |
| 343 | ········ |
| 344 | ········/// <summary> |
| 345 | ········/// Gets the Mapping structure of the application as stored in NDOMapping.xml. |
| 346 | ········/// Use it only if you know exactly, what you're doing! |
| 347 | ········/// Do not change anything in the mapping structure because it will cause the |
| 348 | ········/// NDO Framework to fail. |
| 349 | ········/// </summary> |
| 350 | ········public NDOMapping NDOMapping |
| 351 | ········{ |
| 352 | ············get { return this.mappings; } |
| 353 | ········} |
| 354 | |
| 355 | ········/// <summary> |
| 356 | ········/// Gets the DataSet behind the operations of the pm. |
| 357 | ········/// </summary> |
| 358 | ········/// <remarks>This property should't be used by user code. It exists only for test purposes.</remarks> |
| 359 | ········public DataSet DataSet |
| 360 | ········{ |
| 361 | ············get { return this.ds; } |
| 362 | ········} |
| 363 | |
| 364 | ········internal NDO.Cache Cache |
| 365 | ········{ |
| 366 | ············get { return this.cache; } |
| 367 | ········} |
| 368 | |
| 369 | ········/// <summary> |
| 370 | ········/// Checks whether an object is an IPersistenceCapable and converts the object into an IPersistenceCapable. |
| 371 | ········/// </summary> |
| 372 | ········/// <param name="o"></param> |
| 373 | ········/// <returns></returns> |
| 374 | ········/// <remarks>Throws an NDOException, if the object can't be converted.</remarks> |
| 375 | ········protected internal IPersistenceCapable CheckPc(object o) |
| 376 | ········{ |
| 377 | ············IPersistenceCapable pc = o as IPersistenceCapable; |
| 378 | ············if (pc == null && !(o == null)) |
| 379 | ················throw new NDOException(31, "Parameter should implement IPersistenceCapable. Check, if the type " + o.GetType().FullName + "," + o.GetType().Assembly.FullName + " is enhanced."); |
| 380 | ············return pc; |
| 381 | ········} |
| 382 | |
| 383 | ········/// <summary> |
| 384 | ········/// Determine, if the pm has been closed before. |
| 385 | ········/// </summary> |
| 386 | ········public bool IsClosed => isClosing || this.ds == null; |
| 387 | |
| 388 | ········/// <summary> |
| 389 | ········/// Closes the PersistenceManager and releases all resources. |
| 390 | ········/// </summary> |
| 391 | ········public void Close() |
| 392 | ········{ |
| 393 | ············CloseAsync().ConfigureAwait( false ).GetAwaiter().GetResult(); |
| 394 | ········} |
| 395 | |
| 396 | ········/// <summary> |
| 397 | ········/// Closes the PersistenceManager and releases all resources asynchronously. |
| 398 | ········/// </summary> |
| 399 | ········/// <remarks>This is the method to override in derived classes. Call base.CloseAsync() in the overridden version.</remarks> |
| 400 | ········public virtual async Task CloseAsync() |
| 401 | ········{ |
| 402 | ············if (isClosing) |
| 403 | ················return; |
| 404 | ············isClosing = true; |
| 405 | ············this.ds.Dispose(); |
| 406 | ············this.ds = null; |
| 407 | ············if (this.scope is IAsyncDisposable asyncScope) |
| 408 | ················await asyncScope.DisposeAsync().ConfigureAwait( false ); |
| 409 | ············else if (this.scope != null) |
| 410 | ················this.scope.Dispose(); |
| 411 | ············this.queryCache.Clear(); |
| 412 | ········} |
| 413 | |
| 414 | ········/// <summary> |
| 415 | ········/// IDisposable implementation. |
| 416 | ········/// </summary> |
| 417 | ········/// <remarks>Note: The derived classes don't need to override the Dispose methods. Just override CloseAsync() and call base.CloseAsync() in the overridden version.</remarks> |
| 418 | ········/// <param name="disposing"></param> |
| 419 | ········protected virtual void Dispose(bool disposing) |
| 420 | ········{ |
| 421 | ············if (disposing) |
| 422 | ················Close(); |
| 423 | ········} |
| 424 | |
| 425 | ········/// <summary> |
| 426 | ········/// Disposes any Resources which might be held by the PersistenceManager implementation. |
| 427 | ········/// </summary> |
| 428 | ········public void Dispose() |
| 429 | ········{ |
| 430 | ············Dispose( true ); |
| 431 | ············GC.SuppressFinalize( this ); |
| 432 | ········} |
| 433 | |
| 434 | ········/// <summary> |
| 435 | ········/// Disposes any Resources which might be held by the PersistenceManager implementation asynchronously. |
| 436 | ········/// </summary> |
| 437 | ········public async ValueTask DisposeAsync() |
| 438 | ········{ |
| 439 | ············await CloseAsync().ConfigureAwait( false ); |
| 440 | ············GC.SuppressFinalize( this ); |
| 441 | ········} |
| 442 | |
| 443 | ········/// <summary> |
| 444 | ········/// Finalizer. |
| 445 | ········/// </summary> |
| 446 | ········~PersistenceManagerBase() |
| 447 | ········{ |
| 448 | ············Dispose( false ); |
| 449 | ········} |
| 450 | ····} |
| 451 | } |
| 452 |
New Commit (9daec7b)
| 1 | // |
| 2 | // Copyright (c) 2002-2024 Mirko Matytschak |
| 3 | // (www.netdataobjects.de) |
| 4 | // |
| 5 | // Author: Mirko Matytschak |
| 6 | // |
| 7 | // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated |
| 8 | // documentation files (the "Software"), to deal in the Software without restriction, including without limitation |
| 9 | // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the |
| 10 | // Software, and to permit persons to whom the Software is furnished to do so, subject to the following |
| 11 | // conditions: |
| 12 | |
| 13 | // The above copyright notice and this permission notice shall be included in all copies or substantial portions |
| 14 | // of the Software. |
| 15 | // |
| 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED |
| 17 | // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL |
| 18 | // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF |
| 19 | // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
| 20 | // DEALINGS IN THE SOFTWARE. |
| 21 | |
| 22 | using System; |
| 23 | using System.Collections.Generic; |
| 24 | using System.Linq; |
| 25 | using System.IO; |
| 26 | using System.Data; |
| 27 | using System.Threading.Tasks; |
| 28 | using NDOInterfaces; |
| 29 | using NDO.Mapping; |
| 30 | using NDO.Application; |
| 31 | using NDO.SchemaGenerator; |
| 32 | using System.Reflection; |
| 33 | using Microsoft.Extensions.DependencyInjection; |
| 34 | using Microsoft.Extensions.Logging; |
| 35 | using NDO.ProviderFactory; |
| 36 | |
| 37 | namespace NDO |
| 38 | { |
| 39 | ····/// <summary> |
| 40 | ····/// Provides base functionality for PersistenceManager classes |
| 41 | ····/// </summary> |
| 42 | ····public class PersistenceManagerBase : IPersistenceManagerBase |
| 43 | ····{ |
| 44 | ········internal Cache cache = new Cache(); |
| 45 | ········/// <summary> |
| 46 | ········/// The DataSet used as template for DataRows |
| 47 | ········/// </summary> |
| 48 | ········protected DataSet ds = null; |
| 49 | ········/// <summary> |
| 50 | ········/// The StateManager instance which will be used for all objects |
| 51 | ········/// </summary> |
| 52 | ········protected IStateManager sm; |
| 53 | ········internal Mappings mappings;··// protected will make the compiler complaining |
| 54 | ········private IServiceProvider scopedServiceProvider; |
| 55 | ········private IServiceScope scope; |
| 56 | ········/// <summary> |
| 57 | ········/// Gets or sets the logger for the PersistenceManager instance |
| 58 | ········/// </summary> |
| 59 | ········protected ILogger Logger { get; set; } |
| 60 | ········bool isClosing = false; |
| 61 | ········private INDOProviderFactory providerFactory; |
| 62 | ········private NDOPersistenceHandlerManager persistenceHandlerManager; |
| 63 | ········/// <summary> |
| 64 | ········/// Gets the PersistenceHandlerManager instance |
| 65 | ········/// </summary> |
| 66 | ········public NDOPersistenceHandlerManager PersistenceHandlerManager => persistenceHandlerManager; |
| 67 | |
| 68 | ········/// <summary> |
| 69 | ········/// Creates an NDOMapping instance to be used as parameter for PersistenceManager constructors. |
| 70 | ········/// </summary> |
| 71 | ········/// <param name="mappingFile"></param> |
| 72 | ········/// <param name="serviceProvider"></param> |
| 73 | ········/// <returns></returns> |
| 74 | ········/// <exception cref="ArgumentNullException"></exception> |
| 75 | ········/// <exception cref="Exception"></exception> |
| 76 | ········/// <remarks> |
| 77 | ········/// This can only be used in settings, where a host and a service provider for dependency injection exists. |
| 78 | ········/// You should call AddNdo while building the host to have an INDOProviderFactory instance available. |
| 79 | ········/// </remarks> |
| 80 | ········public static NDOMapping CreateNDOMapping(string mappingFile, IServiceProvider serviceProvider) |
| 81 | ········{ |
| 82 | ············if (serviceProvider == null) |
| 83 | ················throw new ArgumentNullException(nameof(serviceProvider)); |
| 84 | ············var providerFactory = serviceProvider.GetService<INDOProviderFactory>(); |
| 85 | ············if (providerFactory == null) |
| 86 | ················throw new Exception("Can't get an INDOProviderFactory instance"); |
| 87 | ············return new Mappings(mappingFile, providerFactory); |
| 88 | ········} |
| 89 | |
| 90 | ········/// <summary> |
| 91 | ········/// Provides the ProviderFactory to inherited persistence managers; |
| 92 | ········/// </summary> |
| 93 | ········protected INDOProviderFactory ProviderFactory |
| 94 | ········{ |
| 95 | ············get |
| 96 | ············{ |
| 97 | ················if (this.providerFactory == null) |
| 98 | ················{ |
| 99 | ····················var serviceProvider = NDOApplication.ServiceProvider; |
| 100 | |
| 101 | ····················if (serviceProvider != null) |
| 102 | ····················{ |
| 103 | ························this.providerFactory = serviceProvider.GetService<INDOProviderFactory>(); |
| 104 | ····················} |
| 105 | |
| 106 | ····················if (this.providerFactory == null) |
| 107 | ····················{ |
| 108 | ························this.providerFactory = NDOProviderFactory.Instance; |
| 109 | ····················} |
| 110 | ················} |
| 111 | |
| 112 | ················return this.providerFactory; |
| 113 | ············} |
| 114 | ········} |
| 115 | |
| 116 | |
| 117 | ········/// <summary> |
| 118 | ········/// If set to true, the resultset of each query is stored, so that results of an identical query |
| 119 | ········/// can be read from the cache. |
| 120 | ········/// </summary> |
| 121 | ········/// <remarks> |
| 122 | ········/// NDO computes an SHA256 hash for each query including the query parameters. The hash is the key to the query cache. |
| 123 | ········/// Do not use the QueryCache in applications, which work with one PersistenceManager |
| 124 | ········/// over a long time with multiple transactions. |
| 125 | ········/// </remarks> |
| 126 | ········public bool UseQueryCache { get; set; } |
| 127 | |
| 128 | ········private Dictionary<string, object> queryCache = new Dictionary<string, object>(); |
| 129 | |
| 130 | ········/// <summary> |
| 131 | ········/// This is the query cache in which resultsets can be stored. |
| 132 | ········/// </summary> |
| 133 | ········/// <remarks>Usually you won't have to access the query cache.</remarks> |
| 134 | ········public Dictionary<string, object> QueryCache => this.queryCache; |
| 135 | |
| 136 | ········/// <summary> |
| 137 | ········/// Register a listener to this event, if you have to provide user generated ids. |
| 138 | ········/// This event is usefull for databases, which doesn't provide auto-incremented ids, like the Oracle Db. |
| 139 | ········/// The event will be fired if a new id is needed. |
| 140 | ········/// </summary> |
| 141 | ········public event IdGenerationHandler IdGenerationEvent; |
| 142 | |
| 143 | ········/// <summary> |
| 144 | ········/// Constructor |
| 145 | ········/// </summary> |
| 146 | ········public PersistenceManagerBase( IServiceProvider scopedServiceProvider ) |
| 147 | ········{ |
| 148 | ············this.scopedServiceProvider = scopedServiceProvider; |
| 149 | ············string baseDir = AppDomain.CurrentDomain.BaseDirectory; |
| 150 | ············if (File.Exists( Path.Combine( baseDir, "Web.config" ) )) |
| 151 | ················baseDir = Path.Combine( baseDir, "bin" ); |
| 152 | ············var entryAssemblyName = Assembly.GetEntryAssembly()?.GetName()?.Name; |
| 153 | ············List<string> paths = new List<string>(); |
| 154 | ············if (entryAssemblyName != null) |
| 155 | ············paths.Add( Path.Combine( baseDir, $"{entryAssemblyName}.ndo.mapping" ) ); |
| 156 | ············paths.Add( Path.Combine( baseDir, "NDOMapping.xml" ) ); |
| 157 | ············ |
| 158 | ············bool found = false; |
| 159 | ············foreach (var path in paths) |
| 160 | ············{ |
| 161 | ················if (File.Exists(path)) |
| 162 | ················{ |
| 163 | ····················Init( path ); |
| 164 | ····················found = true; |
| 165 | ····················break; |
| 166 | ················} |
| 167 | ············} |
| 168 | ············if (!found) |
| 169 | ················throw new NDOException( 49, $"Can't determine the path to the mapping file. Tried the following locations:\n{string.Join("\n", paths)}\nPlease provide a mapping file path as argument to the PersistenceManager ctor." ); |
| 170 | ········} |
| 171 | |
| 172 | ········/// <summary> |
| 173 | ········/// Constructs a PersistenceManagerBase object using the path to a mapping file. |
| 174 | ········/// </summary> |
| 175 | ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param> |
| 176 | ········/// <param name="pathToMappingFile"></param> |
| 177 | ········public PersistenceManagerBase(string pathToMappingFile, IServiceProvider scopedServiceProvider) |
| 178 | ········{ |
| 179 | ············this.scopedServiceProvider = scopedServiceProvider; |
| 180 | ············Init(pathToMappingFile); |
| 181 | ········} |
| 182 | |
| 183 | ········/// <summary> |
| 184 | ········/// Constructs a PersistenceManagerBase object using the mapping object. |
| 185 | ········/// </summary> |
| 186 | ········/// <param name="mapping"></param> |
| 187 | ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param> |
| 188 | ········public PersistenceManagerBase(NDOMapping mapping, IServiceProvider scopedServiceProvider) |
| 189 | ········{ |
| 190 | ············this.scopedServiceProvider = scopedServiceProvider; |
| 191 | ············var localMappings = mapping as Mappings; |
| 192 | ············if (localMappings == null) |
| 193 | ················throw new ArgumentException( "The mapping must be constructed by a PersistenceManager", nameof( mapping ) ); |
| 194 | |
| 195 | ············Init( localMappings ); |
| 196 | ········} |
| 197 | |
| 198 | ········/// <summary> |
| 199 | ········/// Initializes a PersistenceManager using the path to a mapping file |
| 200 | ········/// </summary> |
| 201 | ········/// <param name="mappingPath"></param> |
| 202 | ········protected virtual void Init(string mappingPath) |
| 203 | ········{ |
| 204 | ············if (!File.Exists(mappingPath)) |
| 205 | ················throw new NDOException(45, String.Format("Mapping File {0} doesn't exist.", mappingPath)); |
| 206 | |
| 207 | ············Init( new Mappings( mappingPath, ProviderFactory ) ); |
| 208 | ········} |
| 209 | |
| 210 | ········/// <summary> |
| 211 | ········/// Initializes the persistence manager |
| 212 | ········/// </summary> |
| 213 | ········/// <remarks> |
| 214 | ········/// Note: This is the method, which will be called from all different ways to instantiate a PersistenceManagerBase. |
| 215 | ········/// </remarks> |
| 216 | ········/// <param name="mappings"></param> |
| 217 | ········internal virtual void Init( Mappings mappings ) |
| 218 | ········{ |
| 219 | ············Logger = NDOApplication.ServiceProvider.GetService<ILoggerFactory>()?.CreateLogger( GetType() ); |
| 220 | ············this.mappings = mappings; |
| 221 | ············this.persistenceHandlerManager = new NDOPersistenceHandlerManager( this.ServiceProvider, this.mappings ); |
| 222 | ············this.ds = new NDODataSet( this.mappings, ProviderFactory );··// Each PersistenceManager instance must have it's own DataSet. |
| 223 | ········} |
| 224 | |
| 225 | ········/// <summary> |
| 226 | ········/// Used by PersistenceManagers, to get an owner supplied id. |
| 227 | ········/// </summary> |
| 228 | ········/// <param name="t">Type of the object, the id is intended for.</param> |
| 229 | ········/// <param name="oid">ObjectId object which will hold the id value.</param> |
| 230 | ········protected void FireIdGenerationEvent(Type t, ObjectId oid) |
| 231 | ········{ |
| 232 | ············if (IdGenerationEvent != null) |
| 233 | ················IdGenerationEvent(t, oid); |
| 234 | ········} |
| 235 | |
| 236 | |
| 237 | ········Dictionary<string,Class> myClassesName; |
| 238 | ········Dictionary<Type, Class> myClassesType; |
| 239 | |
| 240 | ········/// <summary> |
| 241 | ········/// Initializes the class mappings |
| 242 | ········/// </summary> |
| 243 | ········protected void InitClasses() |
| 244 | ········{ |
| 245 | ············int cnt = mappings.Classes.Count(); |
| 246 | ············myClassesName = new Dictionary<string, Class>(cnt); |
| 247 | ············myClassesType = new Dictionary<Type, Class>(cnt); |
| 248 | ············foreach(Class cl in mappings.Classes) |
| 249 | ············{ |
| 250 | ················myClassesName.Add(cl.FullName, cl); |
| 251 | ················myClassesType.Add(cl.SystemType, cl); |
| 252 | ············} |
| 253 | ········} |
| 254 | ········ |
| 255 | |
| 256 | ········internal Class GetClass(string name) |
| 257 | ········{ |
| 258 | ············if (!myClassesName.ContainsKey(name)) |
| 259 | ················throw new NDOException(17, "Can't find mapping information for class " + name); |
| 260 | |
| 261 | ············return myClassesName[name]; |
| 262 | ········} |
| 263 | |
| 264 | ········internal Class GetClass(IPersistenceCapable pc) |
| 265 | ········{ |
| 266 | ············return GetClass(pc.GetType()); |
| 267 | ········} |
| 268 | |
| 269 | ········internal Class GetClass(Type type) |
| 270 | ········{ |
| 271 | ············Type t = type; |
| 272 | |
| 273 | ············if (type.IsGenericType) |
| 274 | ················t = type.GetGenericTypeDefinition(); |
| 275 | |
| 276 | ············if (! myClassesType.ContainsKey(t)) |
| 277 | ················throw new NDOException(17, "Can't find mapping information for class " + t.FullName); |
| 278 | |
| 279 | ············return myClassesType[t]; |
| 280 | |
| 281 | ········} |
| 282 | |
| 283 | ········internal Field GetField(Class cl, string field) |
| 284 | ········{ |
| 285 | ············Field f = cl.FindField(field); |
| 286 | ············if (f == null) |
| 287 | ················throw new NDOException(7, "Can't find mapping information for field " + cl.FullName + "." + field); |
| 288 | ············return f; |
| 289 | ········} |
| 290 | |
| 291 | ········/// <summary> |
| 292 | ········/// Hilfsfunktion |
| 293 | ········/// Liefert die Tabelle im DataSet ab, in der die DataRows des Datentyps liegen |
| 294 | ········/// </summary> |
| 295 | ········/// <param name="t">Data type</param> |
| 296 | ········/// <returns></returns> |
| 297 | ········protected DataTable GetTable(Type t) |
| 298 | ········{ |
| 299 | ············return GetTable(GetClass(t).TableName); |
| 300 | ········} |
| 301 | |
| 302 | ········/// <summary> |
| 303 | ········/// Hilfsfunktion |
| 304 | ········/// Liefert die Tabelle im DataSet ab, in der die DataRow des Objekts liegt |
| 305 | ········/// </summary> |
| 306 | ········/// <param name="pc"></param> |
| 307 | ········/// <returns></returns> |
| 308 | ········protected DataTable GetTable(IPersistenceCapable pc) |
| 309 | ········{ |
| 310 | ············return GetTable(GetClass(pc).TableName); |
| 311 | ········} |
| 312 | |
| 313 | |
| 314 | ········/// <summary> |
| 315 | ········/// Retrieve a table with the given name |
| 316 | ········/// </summary> |
| 317 | ········/// <param name="name">Table name</param> |
| 318 | ········/// <returns></returns> |
| 319 | ········protected DataTable GetTable(string name) |
| 320 | ········{ |
| 321 | ············DataTable dt = ds.Tables[name]; |
| 322 | ············if (dt == null) |
| 323 | ················throw new NDOException(39, "Can't find table '" + name + "' in the schema. Check your mapping file."); |
| 324 | ············return dt; |
| 325 | ········} |
| 326 | |
| 327 | ········/// <summary> |
| 328 | ········/// Gets a DataRow for a given object; if necessary the row will be constructed |
| 329 | ········/// </summary> |
| 330 | ········/// <param name="pc">Persistence capable object</param> |
| 331 | ········/// <returns></returns> |
| 332 | ········protected DataRow GetDataRow(IPersistenceCapable pc) |
| 333 | ········{ |
| 334 | ············DataRow row; |
| 335 | ············if ((row = this.cache.GetDataRow(pc)) != null) |
| 336 | ················return row; |
| 337 | ············return null; |
| 338 | ········} |
| 339 | |
| 340 | ········/// <summary> |
| 341 | ········/// Indicates, if there is a listener registered for the IdGenerationEvent. |
| 342 | ········/// </summary> |
| 343 | ········public bool HasOwnerCreatedIds |
| 344 | ········{ |
| 345 | ············get { return IdGenerationEvent != null; } |
| 346 | ········} |
| 347 | |
| 348 | ········/// <summary> |
| 349 | ········/// Gets the IServiceProvider instance of the current scope. |
| 350 | ········/// If no ServiceProvider was passed in the constructor, a new scope is created. |
| 351 | ········/// </summary> |
| 352 | ········internal IServiceProvider ServiceProvider |
| 353 | ········{ |
| 354 | ············get |
| 355 | ············{ |
| 356 | ················if (this.scopedServiceProvider == null) |
| 357 | ················{ |
| 358 | ····················this.scope = NDOApplication.ServiceProvider.CreateScope(); |
| 359 | ····················this.scopedServiceProvider = scope.ServiceProvider; |
| 360 | ················} |
| 361 | |
| 362 | ················return this.scopedServiceProvider; |
| 363 | ············} |
| 364 | ········} |
| 365 | ········ |
| 366 | ········/// <summary> |
| 367 | ········/// Gets the Mapping structure of the application as stored in NDOMapping.xml. |
| 368 | ········/// Use it only if you know exactly, what you're doing! |
| 369 | ········/// Do not change anything in the mapping structure because it will cause the |
| 370 | ········/// NDO Framework to fail. |
| 371 | ········/// </summary> |
| 372 | ········public NDOMapping NDOMapping |
| 373 | ········{ |
| 374 | ············get { return this.mappings; } |
| 375 | ········} |
| 376 | |
| 377 | ········/// <summary> |
| 378 | ········/// Gets the DataSet behind the operations of the pm. |
| 379 | ········/// </summary> |
| 380 | ········/// <remarks>This property should't be used by user code. It exists only for test purposes.</remarks> |
| 381 | ········public DataSet DataSet |
| 382 | ········{ |
| 383 | ············get { return this.ds; } |
| 384 | ········} |
| 385 | |
| 386 | ········internal NDO.Cache Cache |
| 387 | ········{ |
| 388 | ············get { return this.cache; } |
| 389 | ········} |
| 390 | |
| 391 | ········/// <summary> |
| 392 | ········/// Checks whether an object is an IPersistenceCapable and converts the object into an IPersistenceCapable. |
| 393 | ········/// </summary> |
| 394 | ········/// <param name="o"></param> |
| 395 | ········/// <returns></returns> |
| 396 | ········/// <remarks>Throws an NDOException, if the object can't be converted.</remarks> |
| 397 | ········protected internal IPersistenceCapable CheckPc(object o) |
| 398 | ········{ |
| 399 | ············IPersistenceCapable pc = o as IPersistenceCapable; |
| 400 | ············if (pc == null && !(o == null)) |
| 401 | ················throw new NDOException(31, "Parameter should implement IPersistenceCapable. Check, if the type " + o.GetType().FullName + "," + o.GetType().Assembly.FullName + " is enhanced."); |
| 402 | ············return pc; |
| 403 | ········} |
| 404 | |
| 405 | ········/// <summary> |
| 406 | ········/// Determine, if the pm has been closed before. |
| 407 | ········/// </summary> |
| 408 | ········public bool IsClosed => isClosing || this.ds == null; |
| 409 | |
| 410 | ········/// <summary> |
| 411 | ········/// Closes the PersistenceManager and releases all resources. |
| 412 | ········/// </summary> |
| 413 | ········public void Close() |
| 414 | ········{ |
| 415 | ············CloseAsync().ConfigureAwait( false ).GetAwaiter().GetResult(); |
| 416 | ········} |
| 417 | |
| 418 | ········/// <summary> |
| 419 | ········/// Closes the PersistenceManager and releases all resources asynchronously. |
| 420 | ········/// </summary> |
| 421 | ········/// <remarks>This is the method to override in derived classes. Call base.CloseAsync() in the overridden version.</remarks> |
| 422 | ········public virtual async Task CloseAsync() |
| 423 | ········{ |
| 424 | ············if (isClosing) |
| 425 | ················return; |
| 426 | ············isClosing = true; |
| 427 | ············this.ds.Dispose(); |
| 428 | ············this.ds = null; |
| 429 | ············if (this.scope is IAsyncDisposable asyncScope) |
| 430 | ················await asyncScope.DisposeAsync().ConfigureAwait( false ); |
| 431 | ············else if (this.scope != null) |
| 432 | ················this.scope.Dispose(); |
| 433 | ············this.queryCache.Clear(); |
| 434 | ········} |
| 435 | |
| 436 | ········/// <summary> |
| 437 | ········/// IDisposable implementation. |
| 438 | ········/// </summary> |
| 439 | ········/// <remarks>Note: The derived classes don't need to override the Dispose methods. Just override CloseAsync() and call base.CloseAsync() in the overridden version.</remarks> |
| 440 | ········/// <param name="disposing"></param> |
| 441 | ········protected virtual void Dispose(bool disposing) |
| 442 | ········{ |
| 443 | ············if (disposing) |
| 444 | ················Close(); |
| 445 | ········} |
| 446 | |
| 447 | ········/// <summary> |
| 448 | ········/// Disposes any Resources which might be held by the PersistenceManager implementation. |
| 449 | ········/// </summary> |
| 450 | ········public void Dispose() |
| 451 | ········{ |
| 452 | ············Dispose( true ); |
| 453 | ············GC.SuppressFinalize( this ); |
| 454 | ········} |
| 455 | |
| 456 | ········/// <summary> |
| 457 | ········/// Disposes any Resources which might be held by the PersistenceManager implementation asynchronously. |
| 458 | ········/// </summary> |
| 459 | ········public async ValueTask DisposeAsync() |
| 460 | ········{ |
| 461 | ············await CloseAsync().ConfigureAwait( false ); |
| 462 | ············GC.SuppressFinalize( this ); |
| 463 | ········} |
| 464 | |
| 465 | ········/// <summary> |
| 466 | ········/// Finalizer. |
| 467 | ········/// </summary> |
| 468 | ········~PersistenceManagerBase() |
| 469 | ········{ |
| 470 | ············Dispose( false ); |
| 471 | ········} |
| 472 | ····} |
| 473 | } |
| 474 |