Commits

Anonymous committed 7105ee9

Add more helpful exception when lacking single-threaded apartment.

Comments (0)

Files changed (3)

LocalPolicy/GroupPolicyObject.cs

 
         protected static LocalPolicy.COM.IGroupPolicyObject getInstance()
         {
-            var concrete = new LocalPolicy.COM.GPClass();
-            return (LocalPolicy.COM.IGroupPolicyObject)concrete;
+            return withSingleThreadedApartmentCheck(() =>
+            {
+                var concrete = new LocalPolicy.COM.GPClass();
+                return (LocalPolicy.COM.IGroupPolicyObject)concrete;
+            });
         }
+        protected static T withSingleThreadedApartmentCheck<T>(Func<T> operation)
+        {
+            try
+            {
+                return operation();
+            }
+            catch (InvalidCastException e)
+            {
+                if (System.Threading.Thread.CurrentThread.GetApartmentState() != System.Threading.ApartmentState.STA)
+                {
+                    throw new RequiresSingleThreadedApartmentException(e);
+                }
+                else
+                {
+                    throw e;
+                }
+            }
+        }
+
         protected static void trycatch(Func<uint> operation, string messageTemplate, params object[] messageArgs)
         {
             uint result = operation();

LocalPolicy/LocalPolicy.csproj

     <Compile Include="GroupPolicySection.cs" />
     <Compile Include="IGroupPolicy.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="RequiresSingleThreadedApartmentException.cs" />
   </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 

LocalPolicy/RequiresSingleThreadedApartmentException.cs

+using System;
+
+namespace LocalPolicy
+{
+    public class RequiresSingleThreadedApartmentException : Exception
+    {
+        const string message = "This library requires use of a single-threaded apartment. Decorate your main method with the [STAThread] attribute. See http://msdn.microsoft.com/en-gb/library/windows/desktop/ms680112(v=vs.85).aspx for more documentation";
+
+        public RequiresSingleThreadedApartmentException(Exception innerException)
+            : base(message, innerException) { }
+    }
+}