InteropServices.COMException when running WatiN tests - nunit

When I run WatiN tests on our build server they all throw this InteropServices.COMException:
MyTestClassName.MyTestMethodName:
System.Runtime.InteropServices.COMException : Creating an instance of the COM component with CLSID {0002DF01-0000-0000-C000-000000000046} from the IClassFactory failed due to the following error: 80004005.
I get the same result wether I run them through TeamCity or I run them manually on the server as an administrator using NUnit GUI (2.5).
This is some sample code:
[TestFixture]
public class MyTestClassName
{
private string pageUrl;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
pageUrl = ConfigurationManager.AppSettings["SiteURL"] + "/Pages/MyPage.aspx";
Settings.MakeNewIeInstanceVisible = false;
}
[Test]
public void MyTestMethodName()
{
using (var ie = new IE(pageUrl))
{
ie.SelectList(new Regex(#"^*DropDownList1*$")).Option("TheOption").Select();
ie.SelectList(new Regex(#"^*DropDownList2*$")).Option("AnOption").Select();
ie.SelectList(new Regex(#"^*DropDownList3*$")).Option("OtherOption").Select();
}
}
}
Any ideas what it can be?
/Joakim

Try running Visual Studio as Administrator.

I also meet the same problem but more strange for me.
I've got a server only for "UI testing" and for many application de WatiN test runs without any problem.
This error only happens for one application and only in CruiseControl (with nant) but not when runing the test with NUnitGUI...
I Finnaly found a solution this morning: I replaced all my call new IE(); to new IE(true) WatiN release note And didn't get the error anymore.

Another fix is to "Enable Protected mode in IE" like described here

Every time IE.Quit was called by WatiN IE would stop responding and then try to recover. Run as admin fixed the problem for me.

Another comment says:
Try running Visual Studio as Administrator
It is actually NUnit that needs to be run as administrator (at least in Windows 7), but the thinking is correct.

I think that the select list is not yet fully loaded and ready, and this is another symptom of the same problem described in this question:
Access denied error ( Visual Studio and WatiN )

Related

Retry attribute is not working as expected - NUnit Framework

We are using C# Selenium and NUnit framework for our test automation. Sometimes some test cases will fail in dev environment during execution due environmental issues. I was trying to re-run the failed ones, by using Retry attribute. But it didn't work ( I have kept assertion failures as well)
Could you please have a look the below code
[TestFixture]
public class UITests : BaseClassProtractor
{
[SetUp]
public void Setup()
{
//**Call chrome driver and open app url set up**//
}
[Test]
[Retry(1)]
public TestMethod1()
{
//** Write test Steps
}
[TearDown]
public void TearDown()
{
Drivers.TryRemove(TestContext.CurrentContext.Test.FullName, out var localDriver);
localDriver?.Quit();
}
}
Thanks,
Khaja Shaik.
[Retry(1)] indicates that the test should only be run once! That is, it won't be retried if it fails. Use [Retry(2)] as a minimum.
If you continue to get failures, we need to see the exact failure message.

EventLog Production

I have a console application that is responsible for saving a record in the Windows Event Viewer, but it does not work on a clean machine, despite having already installed the .Net Framework.
Create an installer which is responsible for creating the route HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\MyLogEvent
When running the installed application, it does the whole process without throwing any errors, but it is not saving anything in the Event Viewer.
A strongname has already been added.
string origen = "ErrorGeneric";
EventLogEntryType severidad = EventLogEntryType.Error
if (!EventLog.SourceExists(origen))
{
EventLog.CreateEventSource(origen, "MyLogEvent");
while (!EventLog.SourceExists(origen))
{
Console.Write(".");
Thread.Sleep(1000);
}
}
EventLog log = new EventLog() { Source = origen };
log.WriteEntry(logString.ToString(), severidad);
I found the error, I needed to add the source to the installation, so that it was created in the windows registry

JavaMail crashes after build/deploy on Glassfish 4

My current project includes using of a JavaMail for confirming an user email. The problem I have is that, using eclipse, every time I build & deploy my web application on the local Glassfish server the JavaMail crashes with the following exception:
Severe: java.lang.SecurityException: Access to default session denied
at javax.mail.Session.getDefaultInstance(Session.java:333)
at utils.MailService.sendEmailSSL(MailService.java:58)
And here the code snipped where I'm obtaining the session and which is throwing the above exception:
Session session = Session.getDefaultInstance(
props,
new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(usr, pwd);
}
});
The workaround I've found so far is restarting Glassfish and after that JavaMail functions properly again. The problem is it is very annoying and time consuming doing a restart even after the smallest change in my code.
My question: Is there a possibility to reset only the JavaMail service and bind this with the build event?
Off course any other suggestions are welcome too :)
If you can avoid using Session.getDefaultInstance. Use Session.getInstance and fix some of the common mistakes.

TFS Server plugin fails after upgrade from TFS2012 to TFS2015 RC

We have just upgraded one of our servers from TFS2012.2 to TFS2015RC. Everything went "smooth", but we are encountering an issue:
A while ago we wrote a server side plugin for TFS, which listens to the WorkitemChangedEvent. It implements the ISubscriber interface. The following piece of code was working fine before the update:
void ITfsService.UpdateState(int workItemId, string newState)
{
var wi = store.GetWorkItem(workItemId);
wi.State = newState;
wi.Save();
}
After the update, and after recompiling against the TFS2015 dlls, the following error occured:
Failed to process notification: TF237124: Work Item is not ready to save.
Note that none of the workitemtypes has changed, it is the same data.
I tried getting more information out of the error by calling Validate() before saving, this is the output:
Status: InvalidListValue
State: "Resolved, To Be Reviewed"
WIT: Task
Id: 5842
Field: State
However, the state "Resolved, To Be Reviewed" does exists in the list of available states. In the GUI it is perfectly possible to change the state of the item to "Resolved, To Be Reviewed":
What is causing the Save() to fail?
Finally found the cause of this:
Apparently, the Validate() call validates against the whole ProcessConfiguration.xml. Because in TFS2012 there were both AgileProcessConfiguration and CommonProcessConfiguration, there were underlying problems with the workitem states.
After resolving those issues in the correct ProcessConfiguration file, the plugin was working again (and, TFS could also upgrade the Backlog\IterationPlanning features.)

Unit testing with Roslyn.Services.Workspace results in a SecurityException while working at x86 target

I'm working on set of constants for my project, and I'd like to use roslyn to verify some of them in source code level. To achieve this, I'm loading entire solution using following snippet into AppDomain with IsFullyTrusted == true and IsHomogenous == true, i.e. remoting is enabled with x86 platform target:
// load workspace, i.e. solution from Visual Studio
var workspace = Roslyn.Services.Workspace.LoadSolution(solutionFile);
Test runners for NCrunch and NUnit with x86 platform with Roslyn
But while using either ncrunch 1.45 or nunit 2.6.2 nunit-console-x86.exe with platform configuration x86 as test runners, I'm constantly getting following System.Security.SecurityException:
System.Security.SecurityException : Type System.Runtime.Remoting.ObjRef and the types derived from it (such as System.Runtime.Remoting.ObjRef) are not permitted to be deserialized at this security level.
Server stack trace:
at System.Runtime.Serialization.FormatterServices.CheckTypeSecurity(Type t, TypeFilterLevel securityLevel)
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.CheckSecurity(ParseRecord pr)
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ParseObject(ParseRecord pr)
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Parse(ParseRecord pr)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Remoting.Channels.CoreChannel.DeserializeBinaryRequestMessage(String objectUri, Stream inputStream, Boolean bStrictBinding, TypeFilterLevel securityLevel)
at System.Runtime.Remoting.Channels.BinaryServerFormatterSink.ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, IMessage& responseMsg, ITransportHeaders& responseHeaders, Stream& responseStream)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Roslyn.Utilities.RemoteServices.Initialize(Int32 clientProcessId)
at Roslyn.Utilities.RemoteServices.StartRemoteServicesProcess()
at Roslyn.Utilities.RemoteServices.get_Instance()
at Roslyn.Utilities.RemoteServices.CreateInstance[T]()
at Roslyn.Services.Host.TemporaryStorageServiceFactory.CreateService(IWorkspaceServiceProvider workspaceServices)
at Roslyn.Services.Host.WorkspaceServiceProviderFactory.<>c__DisplayClass6.<OnImportsSatisfied>b__1(IWorkspaceServiceProvider wsp)
at Roslyn.Services.Host.WorkspaceServiceProvider.ConstructService(Type type)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at Roslyn.Services.Host.WorkspaceServiceProvider.GetService[TWorkspaceService]()
at Roslyn.Services.SolutionServices..ctor(IWorkspaceServiceProvider workspaceServices)
at Roslyn.Services.Solution..ctor(SolutionId id, String filePath, VersionStamp version, VersionStamp latestProjectVersion, IWorkspaceServiceProvider workspaceServices)
at Roslyn.Services.Host.SolutionFactoryServiceFactory.SolutionFactoryService.CreateSolution(SolutionId id)
at Roslyn.Services.Host.TrackingWorkspace.CreateNewSolution(ISolutionFactoryService solutionFactory, SolutionId id)
at Roslyn.Services.Host.TrackingWorkspace..ctor(IWorkspaceServiceProvider workspaceServiceProvider, Boolean enableBackgroundCompilation, Boolean enableInProgressSolutions)
at Roslyn.Services.Host.HostWorkspace..ctor(IWorkspaceServiceProvider workspaceServiceProvider, Boolean enableBackgroundCompilation, Boolean enableInProgressSolutions, Boolean enableFileTracking)
at Roslyn.Services.Host.LoadedWorkspace..ctor(IWorkspaceServiceProvider workspaceServiceProvider, IDictionary`2 globalProperties, Boolean enableBackgroundCompilation, Boolean enableFileTracking)
at Roslyn.Services.Host.LoadedWorkspace.LoadSolution(String solutionFileName, String configuration, String platform, Boolean enableFileTracking)
at Roslyn.Services.Workspace.LoadSolution(String solutionFileName, String configuration, String platform, Boolean enableFileTracking)
There is a discussion on NCrunch forum, but I have tried all following options without success:
Add [assembly: AllowPartiallyTrustedCallers] to AssemblyInfo.cs
Add [assembly: SecurityRules(SecurityRuleSet.Level1)] to AssemblyInfo.cs
Add <NetFx40_LegacySecurityPolicy enabled="true" /> to app.config
Run VS2012 as Administrator
Decorate both unittests and implementation with [SecuritySafeCritical]
Update: create new AppDomain and provide
PermissionState.Unrestricted, SecurityPermissionFlag.AllFlags and DataProtectionPermissionFlags.AllFlags
Add Host Evidence: SecurityZone.MyComputer, System.Security.Policy.Hash and System.Security.Policy.StrongName
Add all assemblies (both mine and Roslyn CTP) to fullTrustAssemblies while creating of AppDomain
Update #2
This exception happens only while I'm running test under x86 configuration, after I had switched to x64 platform configuration, everything seems to work fine
Question
Are there any other attributes or configuration changes to app.config or AppDomain that could help to enable deserialization in .NET Framework remoting for System.Runtime.Remoting.ObjRef while running under x86 configuration?
Temporary solution
Switch to x64 build configuration only for unittest project(s)
Source code
Whole source code is available at github: to reproduce error run following unittest using NCrunch IntrospectionTests.Introspection_SearchForComplexityGt10_ApprovedList
Discussion at NCrunch forum
Additional information
Also I notice...
A lot of instances of Roslyn.Services.dll hang in background, after all tests had been completed.
Lack of Host Evidences for NCrunch: System.Security.Policy.Hash and System.Security.Policy.StrongName with test runner assembly name
resharper MSIL (should be x64 inside) and nunit 2.6.2 nunit-console.exe test runner are working fine, so it looks like Roslyn configuration/remoting/security configuration issue.
It looks like ncrunch is executing the tests in Partial Trust, whereas Resharper is running them in Full Trust.
Roslyn has not been tested in Partial Trust scenarios. There are likely to be accesses to APIs that require Full Trust.
I haven't used ncrunch, but maybe there is a way to configure it to run the tests in Full Trust?
I want to add something!
After upgrading an NUnit instance I manage to run to both 2.6.2 and 2.6.3 of the software, my team ran into similar issues with this exact System.Security exception that Akim was seeing.
We were creating an IpcChannel with some of our custom NUnit logic that wasn't created with the right trust settings, so we had to change something that looked like:
IpcChannel channel = new IpcChannel(string.Format("localhost:{0}", portNum));
To -
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
var properties = new System.Collections.Hashtable();
properties["name"] = "ipc";
properties["priority"] = "20";
properties["portName"] = string.Format("localhost:{0}", portNum);
IpcChannel channel = new IpcChannel(properties, clientProvider, serverProvider);
Just a quick fix I noticed that I figured I would forward to anybody seeing something similar that can't just switch their platform settings. To be fair, it took me about four hours to figure out so I didn't want the knowledge to go to waste.