1
votes

Issue: "The CurrentThread needs to have it's ApartmentState set to ApartmentState.STA to be able to automate Internet Explorer."

First of all i have read all the solutions to the problems above and none works for me.May be i am missing something. I have tried adding Execution Thread entry into my app.config, also tried setting STAThread attribute and i am still facing the same exception as stated above.

Tools: Visual Studio 2010, Watin 2.1, c#

Scenario: Trying to run a unit test [watin script in c#] from a web application upon a button click. But the above exception is thrown when the script is about to launch IE on the following line : IE mybrowser = new IE ("SomeURL here");

Any Thoughts ?

4

4 Answers

2
votes

Got it from a friend. We actually dont have to add any app.config entry. Just start the thread in a single state. In my case, i wrote the following code in my button click handler:

System.Threading.Thread th = new Thread(new ThreadStart(Test));
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
        th.Join();

and i moved the call to unit test in the private. TEST method as follows:
 private void Test()
    {
        var som = new Project.ClassName();
        som.MethodToExecute();
}
1
votes

What does your App.Config look like?

  <NUnit>
    <TestRunner>
      <!-- Valid values are STA,MTA. Others ignored. -->
      <add key="ApartmentState" value="STA"/>
    </TestRunner>
  </NUnit>

The above works for me on Win7, IE9 (32bit), and Watin2.1. It also works on WinXP, IE8, WatiN 2.1. I'm 99% sure it worked just fine on previous versions of WatiN as well. No other ApartmentState changes were needed.

1
votes

Simply add [assembly: RequiresSTA] at the top of your file or at the entry point of your project.

1
votes

I had already done the app.config changes

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="NUnit">
      <section name="TestRunner" type="System.Configuration.NameValueSectionHandler" />
    </sectionGroup>
  </configSections>
  <NUnit>
    <TestRunner>
      <add key="ApartmentState" value="STA" />
    </TestRunner>
  </NUnit>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="nunit.framework" publicKeyToken="96d09a1eb7f44a77" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.6.3.13283" newVersion="2.6.3.13283" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

but no dice. I opened AssemblyInfo and added

[assembly: RequiresSTA]

and suddenly, the universe began to function properly again.