Datei: NDODLL/PersistenceManagerBase.cs

Last Commit (8aabfc4)
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 NDOInterfaces;
28 using NDO.Mapping;
29 using NDO.Application;
30 using NDO.SchemaGenerator;
31 using System.Reflection;
32 using Microsoft.Extensions.DependencyInjection;
33 using Microsoft.Extensions.Logging;
34 using NDO.ProviderFactory;
35
36 namespace NDO
37 {
38 ····/// <summary>
39 ····/// Provides base functionality for PersistenceManager classes
40 ····/// </summary>
41 ····public class PersistenceManagerBase : IPersistenceManagerBase
42 ····{
43 ········internal Cache cache = new Cache();
44 ········/// <summary>
45 ········/// The DataSet used as template for DataRows
46 ········/// </summary>
47 ········protected DataSet ds = null;
48 ········/// <summary>
49 ········/// The StateManager instance which will be used for all objects
50 ········/// </summary>
51 ········protected IStateManager sm;
52 ········internal Mappings mappings;··// protected will make the compiler complaining
53 ········private IServiceProvider scopedServiceProvider;
54 ········private IServiceScope scope;
55 ········/// <summary>
56 ········/// Gets or sets the logger for the PersistenceManager instance
57 ········/// </summary>
58 ········protected ILogger Logger { get; set; }
59 ········bool isClosing = false;
60 ········private INDOProviderFactory providerFactory;
61 ········private NDOPersistenceHandlerManager persistenceHandlerManager;
62 ········/// <summary>
63 ········/// Gets the PersistenceHandlerManager instance
64 ········/// </summary>
65 ········public NDOPersistenceHandlerManager PersistenceHandlerManager => persistenceHandlerManager;
66
67 ········/// <summary>
68 ········/// Provides the ProviderFactory to inherited persistence managers;
69 ········/// </summary>
70 ········protected INDOProviderFactory ProviderFactory
71 ········{
72 ············get
73 ············{
74 ················if (this.providerFactory == null)
75 ················{
76 ····················var serviceProvider = NDOApplication.ServiceProvider;
77
78 ····················if (serviceProvider != null)
79 ····················{
80 ························this.providerFactory = serviceProvider.GetService<INDOProviderFactory>();
81 ····················}
82
83 ····················if (this.providerFactory == null)
84 ····················{
85 ························this.providerFactory = NDOProviderFactory.Instance;
86 ····················}
87 ················}
88
89 ················return this.providerFactory;
90 ············}
91 ········}
92
93
94 ········/// <summary>
95 ········/// If set to true, the resultset of each query is stored, so that results of an identical query
96 ········/// can be read from the cache.
97 ········/// </summary>
98 ········/// <remarks>
99 ········/// NDO computes an SHA256 hash for each query including the query parameters. The hash is the key to the query cache.
100 ········/// Do not use the QueryCache in applications, which work with one PersistenceManager
101 ········/// over a long time with multiple transactions.
102 ········/// </remarks>
103 ········public bool UseQueryCache { get; set; }
104
105 ········private Dictionary<string, object> queryCache = new Dictionary<string, object>();
106
107 ········/// <summary>
108 ········/// This is the query cache in which resultsets can be stored.
109 ········/// </summary>
110 ········/// <remarks>Usually you won't have to access the query cache.</remarks>
111 ········public Dictionary<string, object> QueryCache => this.queryCache;
112
113 ········/// <summary>
114 ········/// Register a listener to this event, if you have to provide user generated ids.
115 ········/// This event is usefull for databases, which doesn't provide auto-incremented ids, like the Oracle Db.
116 ········/// The event will be fired if a new id is needed.
117 ········/// </summary>
118 ········public event IdGenerationHandler IdGenerationEvent;
119
120 ········/// <summary>
121 ········/// Constructor
122 ········/// </summary>
123 ········public PersistenceManagerBase( IServiceProvider scopedServiceProvider )
124 ········{
125 ············this.scopedServiceProvider = scopedServiceProvider;
126 ············string baseDir = AppDomain.CurrentDomain.BaseDirectory;
127 ············if (File.Exists( Path.Combine( baseDir, "Web.config" ) ))
128 ················baseDir = Path.Combine( baseDir, "bin" );
129 ············var entryAssemblyName = Assembly.GetEntryAssembly()?.GetName()?.Name;
130 ············List<string> paths = new List<string>();
131 ············if (entryAssemblyName != null)
132 ············paths.Add( Path.Combine( baseDir, $"{entryAssemblyName}.ndo.mapping" ) );
133 ············paths.Add( Path.Combine( baseDir, "NDOMapping.xml" ) );
134 ············
135 ············bool found = false;
136 ············foreach (var path in paths)
137 ············{
138 ················if (File.Exists(path))
139 ················{
140 ····················Init( path );
141 ····················found = true;
142 ····················break;
143 ················}
144 ············}
145 ············if (!found)
146 ················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." );
147 ········}
148
149 ········/// <summary>
150 ········/// Constructs a PersistenceManagerBase object using the path to a mapping file.
151 ········/// </summary>
152 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
153 ········/// <param name="pathToMappingFile"></param>
154 ········public PersistenceManagerBase(string pathToMappingFile, IServiceProvider scopedServiceProvider)
155 ········{
156 ············this.scopedServiceProvider = scopedServiceProvider;
157 ············Init(pathToMappingFile);
158 ········}
159
160 ········/// <summary>
161 ········/// Constructs a PersistenceManagerBase object using the mapping object.
162 ········/// </summary>
163 ········/// <param name="mapping"></param>
164 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
165 ········public PersistenceManagerBase(NDOMapping mapping, IServiceProvider scopedServiceProvider)
166 ········{
167 ············this.scopedServiceProvider = scopedServiceProvider;
168 ············var localMappings = mapping as Mappings;
169 ············if (localMappings == null)
170 ················throw new ArgumentException( "The mapping must be constructed by a PersistenceManager", nameof( mapping ) );
171
172 ············Init( localMappings );
173 ········}
174
175 ········/// <summary>
176 ········/// Initializes a PersistenceManager using the path to a mapping file
177 ········/// </summary>
178 ········/// <param name="mappingPath"></param>
179 ········protected virtual void Init(string mappingPath)
180 ········{
181 ············if (!File.Exists(mappingPath))
182 ················throw new NDOException(45, String.Format("Mapping File {0} doesn't exist.", mappingPath));
183
184 ············Init( new Mappings( mappingPath, ProviderFactory ) );
185 ········}
186
187 ········/// <summary>
188 ········/// Initializes the persistence manager
189 ········/// </summary>
190 ········/// <remarks>
191 ········/// Note: This is the method, which will be called from all different ways to instantiate a PersistenceManagerBase.
192 ········/// </remarks>
193 ········/// <param name="mappings"></param>
194 ········internal virtual void Init( Mappings mappings )
195 ········{
196 ············if (NDOApplication.ServiceProvider == null)
197 ················throw new Exception( "ServiceProvider is not initialized. Please setup a host environment. See BuilderExtensions.AddNdo and .UseNdo." );
198
199 ············Logger = NDOApplication.ServiceProvider.GetService<ILoggerFactory>()?.CreateLogger( GetType() );
200 ············this.mappings = mappings;
201 ············this.persistenceHandlerManager = new NDOPersistenceHandlerManager( this.ServiceProvider, this.mappings );
202 ············this.ds = new NDODataSet( this.mappings, ProviderFactory );··// Each PersistenceManager instance must have it's own DataSet.
203 ········}
204
205 ········/// <summary>
206 ········/// Used by PersistenceManagers, to get an owner supplied id.
207 ········/// </summary>
208 ········/// <param name="t">Type of the object, the id is intended for.</param>
209 ········/// <param name="oid">ObjectId object which will hold the id value.</param>
210 ········protected void FireIdGenerationEvent(Type t, ObjectId oid)
211 ········{
212 ············if (IdGenerationEvent != null)
213 ················IdGenerationEvent(t, oid);
214 ········}
215
216
217 ········Dictionary<string,Class> myClassesName;
218 ········Dictionary<Type, Class> myClassesType;
219
220 ········/// <summary>
221 ········/// Initializes the class mappings
222 ········/// </summary>
223 ········protected void InitClasses()
224 ········{
225 ············int cnt = mappings.Classes.Count();
226 ············myClassesName = new Dictionary<string, Class>(cnt);
227 ············myClassesType = new Dictionary<Type, Class>(cnt);
228 ············foreach(Class cl in mappings.Classes)
229 ············{
230 ················myClassesName.Add(cl.FullName, cl);
231 ················myClassesType.Add(cl.SystemType, cl);
232 ············}
233 ········}
234 ········
235
236 ········internal Class GetClass(string name)
237 ········{
238 ············if (!myClassesName.ContainsKey(name))
239 ················throw new NDOException(17, "Can't find mapping information for class " + name);
240
241 ············return myClassesName[name];
242 ········}
243
244 ········internal Class GetClass(IPersistenceCapable pc)
245 ········{
246 ············return GetClass(pc.GetType());
247 ········}
248
249 ········internal Class GetClass(Type type)
250 ········{
251 ············Type t = type;
252
253 ············if (type.IsGenericType)
254 ················t = type.GetGenericTypeDefinition();
255
256 ············if (! myClassesType.ContainsKey(t))
257 ················throw new NDOException(17, "Can't find mapping information for class " + t.FullName);
258
259 ············return myClassesType[t];
260
261 ········}
262
263 ········internal Field GetField(Class cl, string field)
264 ········{
265 ············Field f = cl.FindField(field);
266 ············if (f == null)
267 ················throw new NDOException(7, "Can't find mapping information for field " + cl.FullName + "." + field);
268 ············return f;
269 ········}
270
271 ········/// <summary>
272 ········/// Hilfsfunktion
273 ········/// Liefert die Tabelle im DataSet ab, in der die DataRows des Datentyps liegen
274 ········/// </summary>
275 ········/// <param name="t">Data type</param>
276 ········/// <returns></returns>
277 ········protected DataTable GetTable(Type t)
278 ········{
279 ············return GetTable(GetClass(t).TableName);
280 ········}
281
282 ········/// <summary>
283 ········/// Hilfsfunktion
284 ········/// Liefert die Tabelle im DataSet ab, in der die DataRow des Objekts liegt
285 ········/// </summary>
286 ········/// <param name="pc"></param>
287 ········/// <returns></returns>
288 ········protected DataTable GetTable(IPersistenceCapable pc)
289 ········{
290 ············return GetTable(GetClass(pc).TableName);
291 ········}
292
293
294 ········/// <summary>
295 ········/// Retrieve a table with the given name
296 ········/// </summary>
297 ········/// <param name="name">Table name</param>
298 ········/// <returns></returns>
299 ········protected DataTable GetTable(string name)
300 ········{
301 ············DataTable dt = ds.Tables[name];
302 ············if (dt == null)
303 ················throw new NDOException(39, "Can't find table '" + name + "' in the schema. Check your mapping file.");
304 ············return dt;
305 ········}
306
307 ········/// <summary>
308 ········/// Gets a DataRow for a given object; if necessary the row will be constructed
309 ········/// </summary>
310 ········/// <param name="pc">Persistence capable object</param>
311 ········/// <returns></returns>
312 ········protected DataRow GetDataRow(IPersistenceCapable pc)
313 ········{
314 ············DataRow row;
315 ············if ((row = this.cache.GetDataRow(pc)) != null)
316 ················return row;
317 ············return null;
318 ········}
319
320 ········/// <summary>
321 ········/// Indicates, if there is a listener registered for the IdGenerationEvent.
322 ········/// </summary>
323 ········public bool HasOwnerCreatedIds
324 ········{
325 ············get { return IdGenerationEvent != null; }
326 ········}
327
328 ········/// <summary>
329 ········/// Gets the IServiceProvider instance of the current scope.
330 ········/// If no ServiceProvider was passed in the constructor, a new scope is created.
331 ········/// </summary>
332 ········internal IServiceProvider ServiceProvider
333 ········{
334 ············get
335 ············{
336 ················if (this.scopedServiceProvider == null)
337 ················{
338 ····················this.scope = NDOApplication.ServiceProvider.CreateScope();
339 ····················this.scopedServiceProvider = scope.ServiceProvider;
340 ················}
341
342 ················return this.scopedServiceProvider;
343 ············}
344 ········}
345 ········
346 ········/// <summary>
347 ········/// Gets the Mapping structure of the application as stored in NDOMapping.xml.
348 ········/// Use it only if you know exactly, what you're doing!
349 ········/// Do not change anything in the mapping structure because it will cause the
350 ········/// NDO Framework to fail.
351 ········/// </summary>
352 ········public NDOMapping NDOMapping
353 ········{
354 ············get { return this.mappings; }
355 ········}
356
357 ········/// <summary>
358 ········/// Gets the DataSet behind the operations of the pm.
359 ········/// </summary>
360 ········/// <remarks>This property should't be used by user code. It exists only for test purposes.</remarks>
361 ········public DataSet DataSet
362 ········{
363 ············get { return this.ds; }
364 ········}
365
366 ········internal NDO.Cache Cache
367 ········{
368 ············get { return this.cache; }
369 ········}
370
371 ········/// <summary>
372 ········/// Checks whether an object is an IPersistenceCapable and converts the object into an IPersistenceCapable.
373 ········/// </summary>
374 ········/// <param name="o"></param>
375 ········/// <returns></returns>
376 ········/// <remarks>Throws an NDOException, if the object can't be converted.</remarks>
377 ········protected internal IPersistenceCapable CheckPc(object o)
378 ········{
379 ············IPersistenceCapable pc = o as IPersistenceCapable;
380 ············if (pc == null && !(o == null))
381 ················throw new NDOException(31, "Parameter should implement IPersistenceCapable. Check, if the type " + o.GetType().FullName + "," + o.GetType().Assembly.FullName + " is enhanced.");
382 ············return pc;
383 ········}
384
385 ········/// <summary>
386 ········/// Determine, if the pm has been closed before.
387 ········/// </summary>
388 ········public bool IsClosed => isClosing || this.ds == null;
389
390 ········/// <summary>
391 ········/// Closes the PersistenceManager and releases all resources.
392 ········/// </summary>
393 ········public virtual void Close()
394 ········{
395 ············if (isClosing)
396 ················return;
397 ············isClosing = true;
398 ············this.ds.Dispose();
399 ············this.ds = null;
400 ············if (this.scope != null)
401 ················this.scope.Dispose();
402 ············this.queryCache.Clear();
403 ········}
404
405 ········/// <summary>
406 ········/// IDisposable implementation.
407 ········/// </summary>
408 ········/// <remarks>Note: The derived classes don't need to override the Dispose methods, since Close() is virtual. Just override Close() and call base.Close() in the overridden version.</remarks>
409 ········/// <param name="disposing"></param>
410 ········protected virtual void Dispose(bool disposing)
411 ········{
412 ············if (disposing)
413 ················Close();
414 ········}
415
416 ········/// <summary>
417 ········/// Disposes any Resources which might be held by the PersistenceManager implementation.
418 ········/// </summary>
419 ········public virtual void Dispose()
420 ········{
421 ············Dispose( true );
422 ············GC.SuppressFinalize( this );
423 ········}
424
425 ········/// <summary>
426 ········/// Finalizer.
427 ········/// </summary>
428 ········~PersistenceManagerBase()
429 ········{
430 ············Dispose( false );
431 ········}
432 ····}
433 }
434
New Commit (21ade13)
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 NDOInterfaces;
28 using NDO.Mapping;
29 using NDO.Application;
30 using NDO.SchemaGenerator;
31 using System.Reflection;
32 using Microsoft.Extensions.DependencyInjection;
33 using Microsoft.Extensions.Logging;
34 using NDO.ProviderFactory;
35
36 namespace NDO
37 {
38 ····/// <summary>
39 ····/// Provides base functionality for PersistenceManager classes
40 ····/// </summary>
41 ····public class PersistenceManagerBase : IPersistenceManagerBase
42 ····{
43 ········internal Cache cache = new Cache();
44 ········/// <summary>
45 ········/// The DataSet used as template for DataRows
46 ········/// </summary>
47 ········protected DataSet ds = null;
48 ········/// <summary>
49 ········/// The StateManager instance which will be used for all objects
50 ········/// </summary>
51 ········protected IStateManager sm;
52 ········internal Mappings mappings;··// protected will make the compiler complaining
53 ········private IServiceProvider scopedServiceProvider;
54 ········private IServiceScope scope;
55 ········/// <summary>
56 ········/// Gets or sets the logger for the PersistenceManager instance
57 ········/// </summary>
58 ········protected ILogger Logger { get; set; }
59 ········bool isClosing = false;
60 ········private INDOProviderFactory providerFactory;
61 ········private NDOPersistenceHandlerManager persistenceHandlerManager;
62 ········/// <summary>
63 ········/// Gets the PersistenceHandlerManager instance
64 ········/// </summary>
65 ········public NDOPersistenceHandlerManager PersistenceHandlerManager => persistenceHandlerManager;
66
67 ········/// <summary>
68 ········/// Provides the ProviderFactory to inherited persistence managers;
69 ········/// </summary>
70 ········protected INDOProviderFactory ProviderFactory
71 ········{
72 ············get
73 ············{
74 ················if (this.providerFactory == null)
75 ················{
76 ····················var serviceProvider = NDOApplication.ServiceProvider;
77
78 ····················if (serviceProvider != null)
79 ····················{
80 ························this.providerFactory = serviceProvider.GetService<INDOProviderFactory>();
81 ····················}
82
83 ····················if (this.providerFactory == null)
84 ····················{
85 ························this.providerFactory = NDOProviderFactory.Instance;
86 ····················}
87 ················}
88
89 ················return this.providerFactory;
90 ············}
91 ········}
92
93
94 ········/// <summary>
95 ········/// If set to true, the resultset of each query is stored, so that results of an identical query
96 ········/// can be read from the cache.
97 ········/// </summary>
98 ········/// <remarks>
99 ········/// NDO computes an SHA256 hash for each query including the query parameters. The hash is the key to the query cache.
100 ········/// Do not use the QueryCache in applications, which work with one PersistenceManager
101 ········/// over a long time with multiple transactions.
102 ········/// </remarks>
103 ········public bool UseQueryCache { get; set; }
104
105 ········private Dictionary<string, object> queryCache = new Dictionary<string, object>();
106
107 ········/// <summary>
108 ········/// This is the query cache in which resultsets can be stored.
109 ········/// </summary>
110 ········/// <remarks>Usually you won't have to access the query cache.</remarks>
111 ········public Dictionary<string, object> QueryCache => this.queryCache;
112
113 ········/// <summary>
114 ········/// Register a listener to this event, if you have to provide user generated ids.
115 ········/// This event is usefull for databases, which doesn't provide auto-incremented ids, like the Oracle Db.
116 ········/// The event will be fired if a new id is needed.
117 ········/// </summary>
118 ········public event IdGenerationHandler IdGenerationEvent;
119
120 ········/// <summary>
121 ········/// Constructor
122 ········/// </summary>
123 ········public PersistenceManagerBase( IServiceProvider scopedServiceProvider )
124 ········{
125 ············this.scopedServiceProvider = scopedServiceProvider;
126 ············string baseDir = AppDomain.CurrentDomain.BaseDirectory;
127 ············if (File.Exists( Path.Combine( baseDir, "Web.config" ) ))
128 ················baseDir = Path.Combine( baseDir, "bin" );
129 ············var entryAssemblyName = Assembly.GetEntryAssembly()?.GetName()?.Name;
130 ············List<string> paths = new List<string>();
131 ············if (entryAssemblyName != null)
132 ············paths.Add( Path.Combine( baseDir, $"{entryAssemblyName}.ndo.mapping" ) );
133 ············paths.Add( Path.Combine( baseDir, "NDOMapping.xml" ) );
134 ············
135 ············bool found = false;
136 ············foreach (var path in paths)
137 ············{
138 ················if (File.Exists(path))
139 ················{
140 ····················Init( path );
141 ····················found = true;
142 ····················break;
143 ················}
144 ············}
145 ············if (!found)
146 ················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." );
147 ········}
148
149 ········/// <summary>
150 ········/// Constructs a PersistenceManagerBase object using the path to a mapping file.
151 ········/// </summary>
152 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
153 ········/// <param name="pathToMappingFile"></param>
154 ········public PersistenceManagerBase(string pathToMappingFile, IServiceProvider scopedServiceProvider)
155 ········{
156 ············this.scopedServiceProvider = scopedServiceProvider;
157 ············Init(pathToMappingFile);
158 ········}
159
160 ········/// <summary>
161 ········/// Constructs a PersistenceManagerBase object using the mapping object.
162 ········/// </summary>
163 ········/// <param name="mapping"></param>
164 ········/// <param name="scopedServiceProvider">An IServiceProvider instance, which represents a scope (e.g. a request in an AspNet application)</param>
165 ········public PersistenceManagerBase(NDOMapping mapping, IServiceProvider scopedServiceProvider)
166 ········{
167 ············this.scopedServiceProvider = scopedServiceProvider;
168 ············var localMappings = mapping as Mappings;
169 ············if (localMappings == null)
170 ················throw new ArgumentException( "The mapping must be constructed by a PersistenceManager", nameof( mapping ) );
171
172 ············Init( localMappings );
173 ········}
174
175 ········/// <summary>
176 ········/// Initializes a PersistenceManager using the path to a mapping file
177 ········/// </summary>
178 ········/// <param name="mappingPath"></param>
179 ········protected virtual void Init(string mappingPath)
180 ········{
181 ············if (!File.Exists(mappingPath))
182 ················throw new NDOException(45, String.Format("Mapping File {0} doesn't exist.", mappingPath));
183
184 ············Init( new Mappings( mappingPath, ProviderFactory ) );
185 ········}
186
187 ········/// <summary>
188 ········/// Initializes the persistence manager
189 ········/// </summary>
190 ········/// <remarks>
191 ········/// Note: This is the method, which will be called from all different ways to instantiate a PersistenceManagerBase.
192 ········/// </remarks>
193 ········/// <param name="mappings"></param>
194 ········internal virtual void Init( Mappings mappings )
195 ········{
 
 
 
196 ············Logger = NDOApplication.ServiceProvider.GetService<ILoggerFactory>()?.CreateLogger( GetType() );
197 ············this.mappings = mappings;
198 ············this.persistenceHandlerManager = new NDOPersistenceHandlerManager( this.ServiceProvider, this.mappings );
199 ············this.ds = new NDODataSet( this.mappings, ProviderFactory );··// Each PersistenceManager instance must have it's own DataSet.
200 ········}
201
202 ········/// <summary>
203 ········/// Used by PersistenceManagers, to get an owner supplied id.
204 ········/// </summary>
205 ········/// <param name="t">Type of the object, the id is intended for.</param>
206 ········/// <param name="oid">ObjectId object which will hold the id value.</param>
207 ········protected void FireIdGenerationEvent(Type t, ObjectId oid)
208 ········{
209 ············if (IdGenerationEvent != null)
210 ················IdGenerationEvent(t, oid);
211 ········}
212
213
214 ········Dictionary<string,Class> myClassesName;
215 ········Dictionary<Type, Class> myClassesType;
216
217 ········/// <summary>
218 ········/// Initializes the class mappings
219 ········/// </summary>
220 ········protected void InitClasses()
221 ········{
222 ············int cnt = mappings.Classes.Count();
223 ············myClassesName = new Dictionary<string, Class>(cnt);
224 ············myClassesType = new Dictionary<Type, Class>(cnt);
225 ············foreach(Class cl in mappings.Classes)
226 ············{
227 ················myClassesName.Add(cl.FullName, cl);
228 ················myClassesType.Add(cl.SystemType, cl);
229 ············}
230 ········}
231 ········
232
233 ········internal Class GetClass(string name)
234 ········{
235 ············if (!myClassesName.ContainsKey(name))
236 ················throw new NDOException(17, "Can't find mapping information for class " + name);
237
238 ············return myClassesName[name];
239 ········}
240
241 ········internal Class GetClass(IPersistenceCapable pc)
242 ········{
243 ············return GetClass(pc.GetType());
244 ········}
245
246 ········internal Class GetClass(Type type)
247 ········{
248 ············Type t = type;
249
250 ············if (type.IsGenericType)
251 ················t = type.GetGenericTypeDefinition();
252
253 ············if (! myClassesType.ContainsKey(t))
254 ················throw new NDOException(17, "Can't find mapping information for class " + t.FullName);
255
256 ············return myClassesType[t];
257
258 ········}
259
260 ········internal Field GetField(Class cl, string field)
261 ········{
262 ············Field f = cl.FindField(field);
263 ············if (f == null)
264 ················throw new NDOException(7, "Can't find mapping information for field " + cl.FullName + "." + field);
265 ············return f;
266 ········}
267
268 ········/// <summary>
269 ········/// Hilfsfunktion
270 ········/// Liefert die Tabelle im DataSet ab, in der die DataRows des Datentyps liegen
271 ········/// </summary>
272 ········/// <param name="t">Data type</param>
273 ········/// <returns></returns>
274 ········protected DataTable GetTable(Type t)
275 ········{
276 ············return GetTable(GetClass(t).TableName);
277 ········}
278
279 ········/// <summary>
280 ········/// Hilfsfunktion
281 ········/// Liefert die Tabelle im DataSet ab, in der die DataRow des Objekts liegt
282 ········/// </summary>
283 ········/// <param name="pc"></param>
284 ········/// <returns></returns>
285 ········protected DataTable GetTable(IPersistenceCapable pc)
286 ········{
287 ············return GetTable(GetClass(pc).TableName);
288 ········}
289
290
291 ········/// <summary>
292 ········/// Retrieve a table with the given name
293 ········/// </summary>
294 ········/// <param name="name">Table name</param>
295 ········/// <returns></returns>
296 ········protected DataTable GetTable(string name)
297 ········{
298 ············DataTable dt = ds.Tables[name];
299 ············if (dt == null)
300 ················throw new NDOException(39, "Can't find table '" + name + "' in the schema. Check your mapping file.");
301 ············return dt;
302 ········}
303
304 ········/// <summary>
305 ········/// Gets a DataRow for a given object; if necessary the row will be constructed
306 ········/// </summary>
307 ········/// <param name="pc">Persistence capable object</param>
308 ········/// <returns></returns>
309 ········protected DataRow GetDataRow(IPersistenceCapable pc)
310 ········{
311 ············DataRow row;
312 ············if ((row = this.cache.GetDataRow(pc)) != null)
313 ················return row;
314 ············return null;
315 ········}
316
317 ········/// <summary>
318 ········/// Indicates, if there is a listener registered for the IdGenerationEvent.
319 ········/// </summary>
320 ········public bool HasOwnerCreatedIds
321 ········{
322 ············get { return IdGenerationEvent != null; }
323 ········}
324
325 ········/// <summary>
326 ········/// Gets the IServiceProvider instance of the current scope.
327 ········/// If no ServiceProvider was passed in the constructor, a new scope is created.
328 ········/// </summary>
329 ········internal IServiceProvider ServiceProvider
330 ········{
331 ············get
332 ············{
333 ················if (this.scopedServiceProvider == null)
334 ················{
335 ····················this.scope = NDOApplication.ServiceProvider.CreateScope();
336 ····················this.scopedServiceProvider = scope.ServiceProvider;
337 ················}
338
339 ················return this.scopedServiceProvider;
340 ············}
341 ········}
342 ········
343 ········/// <summary>
344 ········/// Gets the Mapping structure of the application as stored in NDOMapping.xml.
345 ········/// Use it only if you know exactly, what you're doing!
346 ········/// Do not change anything in the mapping structure because it will cause the
347 ········/// NDO Framework to fail.
348 ········/// </summary>
349 ········public NDOMapping NDOMapping
350 ········{
351 ············get { return this.mappings; }
352 ········}
353
354 ········/// <summary>
355 ········/// Gets the DataSet behind the operations of the pm.
356 ········/// </summary>
357 ········/// <remarks>This property should't be used by user code. It exists only for test purposes.</remarks>
358 ········public DataSet DataSet
359 ········{
360 ············get { return this.ds; }
361 ········}
362
363 ········internal NDO.Cache Cache
364 ········{
365 ············get { return this.cache; }
366 ········}
367
368 ········/// <summary>
369 ········/// Checks whether an object is an IPersistenceCapable and converts the object into an IPersistenceCapable.
370 ········/// </summary>
371 ········/// <param name="o"></param>
372 ········/// <returns></returns>
373 ········/// <remarks>Throws an NDOException, if the object can't be converted.</remarks>
374 ········protected internal IPersistenceCapable CheckPc(object o)
375 ········{
376 ············IPersistenceCapable pc = o as IPersistenceCapable;
377 ············if (pc == null && !(o == null))
378 ················throw new NDOException(31, "Parameter should implement IPersistenceCapable. Check, if the type " + o.GetType().FullName + "," + o.GetType().Assembly.FullName + " is enhanced.");
379 ············return pc;
380 ········}
381
382 ········/// <summary>
383 ········/// Determine, if the pm has been closed before.
384 ········/// </summary>
385 ········public bool IsClosed => isClosing || this.ds == null;
386
387 ········/// <summary>
388 ········/// Closes the PersistenceManager and releases all resources.
389 ········/// </summary>
390 ········public virtual void Close()
391 ········{
392 ············if (isClosing)
393 ················return;
394 ············isClosing = true;
395 ············this.ds.Dispose();
396 ············this.ds = null;
397 ············if (this.scope != null)
398 ················this.scope.Dispose();
399 ············this.queryCache.Clear();
400 ········}
401
402 ········/// <summary>
403 ········/// IDisposable implementation.
404 ········/// </summary>
405 ········/// <remarks>Note: The derived classes don't need to override the Dispose methods, since Close() is virtual. Just override Close() and call base.Close() in the overridden version.</remarks>
406 ········/// <param name="disposing"></param>
407 ········protected virtual void Dispose(bool disposing)
408 ········{
409 ············if (disposing)
410 ················Close();
411 ········}
412
413 ········/// <summary>
414 ········/// Disposes any Resources which might be held by the PersistenceManager implementation.
415 ········/// </summary>
416 ········public virtual void Dispose()
417 ········{
418 ············Dispose( true );
419 ············GC.SuppressFinalize( this );
420 ········}
421
422 ········/// <summary>
423 ········/// Finalizer.
424 ········/// </summary>
425 ········~PersistenceManagerBase()
426 ········{
427 ············Dispose( false );
428 ········}
429 ····}
430 }
431