bovender framework
C# framework that implements MVVM and more
ComHelpers.cs
1 /* ComHelpers.cs
2  * part of Bovender framework
3  *
4  * Copyright 2014-2018 Daniel Kraus
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 using System;
19 using System.Collections.Generic;
20 using System.Linq;
21 using System.Runtime.InteropServices;
22 using System.Text;
23 
24 namespace Bovender
25 {
26  public static class ComHelpers
27  {
28  public static object ReleaseComObject(object obj)
29  {
30  if (obj != null && Marshal.IsComObject(obj))
31  {
32  int count = Marshal.ReleaseComObject(obj);
33  Logger.Debug("ReleaseComObject: Ref count after release is {0}", count);
34  if (count < 0)
35  {
36  string caller = new System.Diagnostics.StackFrame(1).GetMethod().Name;
37  Logger.Warn("ReleaseComObject: Caller: {0}", caller);
38  }
39  return null;
40  }
41  else
42  {
43  Logger.Warn("ReleaseComObject: Obj is null or not a COM object (@ {0})",
44  new System.Diagnostics.StackFrame(1).GetMethod().Name);
45  return obj;
46  }
47  }
48 
60  public static bool HasMethod(dynamic obj, string method)
61  {
62  try
63  {
64  return obj.GetType().GetMethod(method) != null;
65  }
66  catch (System.Reflection.AmbiguousMatchException)
67  {
68  // If there is more than one method with this name, an
69  // AmbiguousMatchException is thrown, and we can return true.
70  Logger.Debug("HasMethod: Ambiguous match for {0}, returning true", method);
71  return true;
72  }
73  }
74 
75  #region Class logger
76 
77  private static NLog.Logger Logger { get { return _logger.Value; } }
78 
79  private static readonly Lazy<NLog.Logger> _logger = new Lazy<NLog.Logger>(() => NLog.LogManager.GetCurrentClassLogger());
80 
81  #endregion
82  }
83 }
static bool HasMethod(dynamic obj, string method)
Tests whether a given object responds to a given method.
Definition: ComHelpers.cs:60