PageRenderTime 20ms CodeModel.GetById 13ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/Spss/SpssSafeHandle.cs

#
C# | 59 lines | 35 code | 7 blank | 17 comment | 8 complexity | eac1afb4d3520532ed2e2a116df44e53 MD5 | raw file
 1//-----------------------------------------------------------------------
 2// <copyright file="SpssSafeHandle.cs" company="Andrew Arnott">
 3//     Copyright (c) Andrew Arnott. All rights reserved.
 4//     Copyright (c) Brigham Young University
 5// </copyright>
 6//-----------------------------------------------------------------------
 7
 8namespace Spss {
 9	using System;
10	using Microsoft.Win32.SafeHandles;
11
12	public class SpssSafeHandle : SafeHandleMinusOneIsInvalid {
13		private SpssFileAccess accessMode;
14
15		/// <summary>
16		/// Initializes a new instance of the <see cref="SpssSafeHandle"/> class.
17		/// </summary>
18		/// <param name="handle">The SPSS handle.</param>
19		/// <param name="accessMode">The access mode the handle was opened with.</param>
20		public SpssSafeHandle(int handle, SpssFileAccess accessMode) : base(true) {
21			this.accessMode = accessMode;
22			this.SetHandle(new IntPtr(handle));
23		}
24
25		public static implicit operator int(SpssSafeHandle handle) {
26			if (handle.IsInvalid) {
27				throw new InvalidOperationException("Invalid SPSS handle.");
28			}
29
30			if (handle.IsClosed) {
31				throw new InvalidOperationException("SPSS handle has been closed.");
32			}
33
34			return handle.handle.ToInt32();
35		}
36
37		/// <summary>
38		/// When overridden in a derived class, executes the code required to free the handle.
39		/// </summary>
40		/// <returns>
41		/// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, false. In this case, it generates a releaseHandleFailed MDA Managed Debugging Assistant.
42		/// </returns>
43		protected override bool ReleaseHandle() {
44			switch (this.accessMode) {
45				case SpssFileAccess.Read:
46					ReturnCode result = SpssSafeWrapper.spssCloseReadImpl(handle.ToInt32());
47					return result == ReturnCode.SPSS_OK;
48				case SpssFileAccess.Append:
49					result = SpssSafeWrapper.spssCloseAppendImpl(handle.ToInt32());
50					return result == ReturnCode.SPSS_OK;
51				case SpssFileAccess.Create:
52					result = SpssSafeWrapper.spssCloseWriteImpl(handle.ToInt32());
53					return result == ReturnCode.SPSS_OK || result == ReturnCode.SPSS_DICT_NOTCOMMIT;
54				default:
55					return false;
56			}
57		}
58	}
59}