PageRenderTime 51ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/Spss/SpssSafeHandle.cs

#
C# | 59 lines | 35 code | 7 blank | 17 comment | 8 complexity | eac1afb4d3520532ed2e2a116df44e53 MD5 | raw file
Possible License(s): LGPL-2.1
  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. namespace Spss {
  8. using System;
  9. using Microsoft.Win32.SafeHandles;
  10. public class SpssSafeHandle : SafeHandleMinusOneIsInvalid {
  11. private SpssFileAccess accessMode;
  12. /// <summary>
  13. /// Initializes a new instance of the <see cref="SpssSafeHandle"/> class.
  14. /// </summary>
  15. /// <param name="handle">The SPSS handle.</param>
  16. /// <param name="accessMode">The access mode the handle was opened with.</param>
  17. public SpssSafeHandle(int handle, SpssFileAccess accessMode) : base(true) {
  18. this.accessMode = accessMode;
  19. this.SetHandle(new IntPtr(handle));
  20. }
  21. public static implicit operator int(SpssSafeHandle handle) {
  22. if (handle.IsInvalid) {
  23. throw new InvalidOperationException("Invalid SPSS handle.");
  24. }
  25. if (handle.IsClosed) {
  26. throw new InvalidOperationException("SPSS handle has been closed.");
  27. }
  28. return handle.handle.ToInt32();
  29. }
  30. /// <summary>
  31. /// When overridden in a derived class, executes the code required to free the handle.
  32. /// </summary>
  33. /// <returns>
  34. /// 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.
  35. /// </returns>
  36. protected override bool ReleaseHandle() {
  37. switch (this.accessMode) {
  38. case SpssFileAccess.Read:
  39. ReturnCode result = SpssSafeWrapper.spssCloseReadImpl(handle.ToInt32());
  40. return result == ReturnCode.SPSS_OK;
  41. case SpssFileAccess.Append:
  42. result = SpssSafeWrapper.spssCloseAppendImpl(handle.ToInt32());
  43. return result == ReturnCode.SPSS_OK;
  44. case SpssFileAccess.Create:
  45. result = SpssSafeWrapper.spssCloseWriteImpl(handle.ToInt32());
  46. return result == ReturnCode.SPSS_OK || result == ReturnCode.SPSS_DICT_NOTCOMMIT;
  47. default:
  48. return false;
  49. }
  50. }
  51. }
  52. }