Selenium ChromeDriver gives me SerializationException every time I try to run it - selenium

I have created NUnit suite that initialises Chrome Webdriver in Selenium. This works fine with InternetExplorer driver and Firefox driver however fails with SerializationException every time I try to run it with Chrome driver.
Anyone can point me in right direction?
namespace TestNamespace
{
using System;
using NUnit.Framework;
using NUnit.Core;
using SeleniumTests;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
class AllInOne
{
public static IWebDriver WebDriver { get; private set; }
[Suite]
public static TestSuite Suite
{
get
{
TestSuite suite = new TestSuite("All Tests");
SetupChrome();
suite.Add(new FlashLoadedTest { Driver = WebDriver });
return suite;
}
}
private static void SetupChrome()
{
WebDriver = new ChromeDriver(#"C:\Users\<username>\AppData\Local\Google\Chrome\Application");
}
}
}
This is error I get:
Unhandled Exception:
System.Runtime.Serialization.SerializationException: Unable to find assembly 'WebDriver, Version=2.15.0.0, Culture=neutral, PublicKeyToken=1c2bd1631853048f'.
Server stack trace:
at System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo assemblyInfo, String name)
at System.Runtime.Serialization.Formatters.Binary.ObjectMap..ctor(String objectName, String[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, Object[] typeInformationA, Int32[] memberAssemIds, ObjectReader objectReader, Int32 objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
at System.Runtime.Serialization.Formatters.Binary.ObjectMap.Create(String name, String[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, Object[] typeInformationA, Int32[] memberAssemIds, ObjectReader objectReader, Int32 objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
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.CrossAppDomainSerializer.DeserializeObject(MemoryStream stm)
at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.DeserializeMessageParts(MemoryStream stm)
at System.Runtime.Remoting.Messaging.SmuggledMethodReturnMessage.FixupForNewAppDomain()
at System.Runtime.Remoting.Channels.CrossAppDomainSink.SyncProcessMessage(IMessage reqMsg)
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 NUnit.Core.TestRunner.Load(TestPackage package)
at NUnit.Util.TestDomain.Load(TestPackage package)
at NUnit.ConsoleRunner.ConsoleUi.Execute(ConsoleOptions options)
at NUnit.ConsoleRunner.Runner.Main(String[] args)

I am not into NUnit, but I believe that IWebDriver class is for Internet Explorer only - but that applies to Java
Do you have class WebDriver also? If yes, try using it.

Related

Selenium 4.X : EventFiringDecorator throws error when using JavascriptExecutor to click webelement

public class DummyClass {
WebDriver driver;
#Test(priority = 1)
public void testNewFeature() {
WebDriverManager.chromedriver().setup();
System.setProperty("webdriver.chrome.silentOutput", "true");
WebDriverListener customListener = new DriverEventListener();
driver = new EventFiringDecorator(customListener).decorate(new ChromeDriver());
driver.get("http://www.google.com");
WebElement button = driver.findElement(By.xpath(".//a[text()='Sign in']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", button);
}
}
public class DriverEventListener implements WebDriverListener {
public void beforeExecuteScript(WebDriver driver, String script, Object[] args) {
System.out.println("beforeExecuteScript ");
}
public void afterExecuteScript(WebDriver driver, String script, Object[] args, Object result) {
System.out.println("afterExecuteScript ");
}
}
Throws error as
java.lang.IllegalArgumentException: Argument is of an illegal type:
com.sun.proxy.$Proxy15 at
org.openqa.selenium.remote.internal.WebElementToJsonConverter.apply(WebElementToJsonConverter.java:85)
at
java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at
java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at
java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at
java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at
java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
at
java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at
java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
at
org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:550)
at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564) at
org.openqa.selenium.support.decorators.WebDriverDecorator.call(WebDriverDecorator.java:228)
at
org.openqa.selenium.support.decorators.DefaultDecorated.call(DefaultDecorated.java:48)
at
org.openqa.selenium.support.decorators.WebDriverDecorator.lambda$createProxy$0(WebDriverDecorator.java:287)
at com.sun.proxy.$Proxy14.executeScript(Unknown Source)
I had the same issue, it is stated that it will be fixed with the next version. Ticket - https://github.com/SeleniumHQ/selenium/issues/9483
I encountered this issue with selenium 4.0.0-beta-3

WCF - communication object cannot be used for communication

I am new to this WCF stuff and I need to get the project involving WCF at work. So, I am testing the water by creating a very simple wcf using NetTcpBinding hardcoding the ip address to simplify the configuration but I was not able to get it to work. Please take a look and see if there is something that jumps at you, I would appreciate it if you could point me to something I have done incorrectly.
I have a WCFLib, WCFHost and WCFClient. If everything is on the same machine, it is fine and dandy and the client and host worked perfect and the result was correct. However, If the host is on one machine and the client on a different one in the same subnet no firewall (the client could ping the host successfully) and I tried to run the client then click the "=" button in the application, I got this error:
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.ServiceModel.CommunicationObjectFaultedException: The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.
Server stack trace:
at System.ServiceModel.Channels.CommunicationObject.ThrowIfDisposedOrNotOpen()
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
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 WCFLib.ICalculator.Add(Int32 arg1, Int32 arg2)
at WCFClient.CalculatorClient.bResult_Click(Object sender, EventArgs e) in c:\Frank\Testing\WCFClient\CalculatorClient.cs:line 37
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
************** Loaded Assemblies **************
mscorlib
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.18033 built by: FX45RTMGDR
CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
WCFClient
Assembly Version: 1.0.0.0
Win32 Version: 1.0.0.0
CodeBase: file:///C:/xxx/WCFClient/bin/Debug/WCFClient.exe
----------------------------------------
System.Windows.Forms
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.18037 built by: FX45RTMGDR
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
Assembly Version: 4.0.0.0
This following are my WCFClient, WCFHost and WCFLib codes: The codes compiled and run successfully when the host and the client were on the same machine. Error occurred only when they were on separate machine on the same subnet where one machine could ping the other.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using WCFLib;
namespace WCFHost
{
class Program
{
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(Calculator));
host.AddServiceEndpoint(typeof(ICalculator), new NetTcpBinding(), "net.tcp://xxx.xxx.xxx.xxx:9000");
host.Open();
Console.ReadLine();
host.Close();
}
}
}
--------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFLib
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract(Namespace = "http://www.mywebsite.com/WCFLib")]
public interface ICalculator
{
[OperationContract(Name="AddInt")]
int Add(int arg1, int arg2);
[OperationContract(Name = "AddDouble")]
Double Add(Double arg1, Double arg2);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
// You can add XSD files into the project. After building the project, you can directly use the data types defined there, with the namespace "WCFLib.ContractType".
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
}
----------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFLib
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
public class Calculator : ICalculator
{
public int Add(int arg1, int arg2)
{
return arg1+arg2;
}
public Double Add(Double arg1, Double arg2)
{
return arg1 + arg2;
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}
-------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.ServiceModel;
using WCFLib;
namespace WCFClient
{
public partial class CalculatorClient : Form
{
public ICalculator proxy;
public CalculatorClient()
{
InitializeComponent();
ChannelFactory<ICalculator> ch;
ch = new ChannelFactory<ICalculator>(new NetTcpBinding(), "net.tcp://xxx.xxx.xxx.xxx:9000");
proxy = ch.CreateChannel();
}
private void bAdd_Click(object sender, EventArgs e)
{
}
private void bResult_Click(object sender, EventArgs e)
{
tboxResult.Text=proxy.Add(12, 45).ToString();
}
}
}
Try adding a path to your URL when hosting and connecting:
e.g.: "net.tcp://xxx.xxx.xxx.xxx:9000/CalcService"

WCF Service Library Agatha Initialize Container

I have developed an WCF Service Library that uses Agatha RRSL, but I can not figure out how to initialize the container. If I recreate this service in an ASP.NET Web Application, I can call the initialization code from the Global.asax.cs Application_Start() and everything works perfectly. The initialization code is:
public static class ComponentRegistration
{
public static void Register()
{
new ServiceLayerConfiguration(Assembly.GetExecutingAssembly(),
typeof(HelloWorldRequest).Assembly,
typeof(Agatha.Castle.Container)).Initialize();
}
}
In the WCF Service Library, I added an App_Code folder with a class that calls:
public static void AppInitialize()
{
ComponentRegistration.Register();
}
That didn't work as my client app throws an exception that there is no response with that type. I also tried adding a component to the web.config file, but I never got that even close to working.
I also tried to create a custom ServiceHost that does the initialization:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Activation;
using Agatha.ServiceLayer;
using System.Reflection;
using Sample.Common.RequestsAndResponses;
namespace Sample.ServiceLayer.WCFHost
{
public class CustomServiceHostFactory : ServiceHostFactory
{
public CustomServiceHostFactory()
{
new ServiceLayerConfiguration(Assembly.GetExecutingAssembly(), typeof(HelloWorldRequest).Assembly,
typeof(Agatha.Castle.Container)).Initialize();
}
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
return new CustomServiceHost(serviceType, baseAddresses);
}
}
public class CustomServiceHost : ServiceHost
{
public CustomServiceHost()
{
}
public CustomServiceHost(Type serviceType, params Uri[] baseAddresses)
: base(serviceType, baseAddresses)
{
}
protected override void OnOpening()
{
base.OnOpening();
}
protected override void OnClosing()
{
base.OnClosing();
}
protected override void ApplyConfiguration()
{
base.ApplyConfiguration();
}
}
}
However, I get the same exception on my client:
System.InvalidOperationException was unhandled
Message=There is no response with type Sample.Common.RequestsAndResponses.HelloWorldResponse. Maybe you called Clear before or forgot to add appropriate request first.
Source=Agatha.Common
StackTrace:
at Agatha.Common.RequestDispatcher.Get[TResponse]() in c:\src\Agatha\Agatha.Common\RequestDispatcher.cs:line 125
at Agatha.Common.RequestDispatcher.Get[TResponse](Request request) in c:\src\Agatha\Agatha.Common\RequestDispatcher.cs:line 150
at ConsoleApplication1.Program.Main(String[] args) in C:\Users\ultraviolet\Documents\Visual Studio 2010\Projects\AgathaHelloWorld\ConsoleApplication1\Program.cs:line 20
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
What approach should I take to get the WCF Service Library to run my initialization code so that the host returns the correct type?
Any guidance would be much appreciated.
Thanks.

What causes: Unix transport error?

I'm doing unit test(using NUnit) on Postgresql, unfortunately it causes an error:
Internal error
RemotingException: Unix transport error.
Note: The error doesn't happen if I'm using Sqlite
Code:
using System;
using ncfg = NHibernate.Cfg;
using System.Collections.Generic;
using System.Reflection;
using NHibernate;
using System.Data;
using NHibernate.Tool.hbm2ddl;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.ByteCode.LinFu;
using NUnit.Framework;
using NHibernate.Mapping;
namespace RuntimeNhibernate
{
class MainClass
{
public static void Main (string[] args)
{
using(var c = new BlogTestFixture())
{
c.CanSaveAndLoadBlog();
}
}
}
public class InMemoryDatabaseTest : IDisposable
{
private static ncfg.Configuration Configuration;
private static ISessionFactory SessionFactory;
protected ISession session;
public InMemoryDatabaseTest(Assembly assemblyContainingMapping)
{
if (Configuration == null)
{
Configuration = new ncfg.Configuration()
.SetProperty(ncfg.Environment.ReleaseConnections,"on_close")
.SetProperty(ncfg.Environment.Dialect, typeof (SQLiteDialect).AssemblyQualifiedName)
.SetProperty(ncfg.Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
.SetProperty(ncfg.Environment.ConnectionString, "data source=:memory:")
.SetProperty(ncfg.Environment.ProxyFactoryFactoryClass, typeof (ProxyFactoryFactory).AssemblyQualifiedName)
.AddAssembly(assemblyContainingMapping);
/*Configuration = new ncfg.Configuration()
.SetProperty(ncfg.Environment.ReleaseConnections,"on_close")
.SetProperty(ncfg.Environment.Dialect, typeof (PostgreSQLDialect).AssemblyQualifiedName)
.SetProperty(ncfg.Environment.ConnectionDriver, typeof(NpgsqlDriver).AssemblyQualifiedName)
.SetProperty(ncfg.Environment.ConnectionString, "Server=127.0.0.1;Database=memdb;User ID=postgres;Password=password;Pooling=false;")
.SetProperty(ncfg.Environment.ProxyFactoryFactoryClass, typeof (ProxyFactoryFactory).AssemblyQualifiedName)
.AddAssembly(assemblyContainingMapping);*/
SessionFactory = Configuration.BuildSessionFactory();
}
session = SessionFactory.OpenSession();
new SchemaExport(Configuration).Execute(true, true, false, session.Connection, Console.Out);
}
public void Dispose()
{
session.Dispose();
}
}//class InMemory
public class Blog
{
public virtual int BlogId { get; set; }
public virtual bool AllowsComments { set; get; }
public virtual DateTime CreatedAt { get; set; }
public virtual string Subtitle { get; set; }
public virtual string Title { get; set; }
}
[TestFixture]
public class BlogTestFixture : InMemoryDatabaseTest
{
public BlogTestFixture() : base(typeof(Blog).Assembly)
{
}
[Test]
public void IsOK()
{
Assert.AreEqual(true, true);
return;
}
[Test]
public void CanSaveAndLoadBlog()
{
object id;
using (var tx = session.BeginTransaction())
{
id = session.Save(new Blog
{
AllowsComments = true,
CreatedAt = new DateTime(2000,1,1),
Subtitle = "Hello",
Title = "World",
});
tx.Commit();
}
session.Clear();
Console.WriteLine("Hello {0}", id);
using (var tx = session.BeginTransaction())
{
var blog = session.Get<Blog>(id);
Assert.AreEqual(new DateTime(2000, 1, 1), blog.CreatedAt);
Assert.AreEqual("Hello", blog.Subtitle);
Assert.AreEqual("World", blog.Title);
Assert.AreEqual(true, blog.AllowsComments);
tx.Commit();
}
}
}//Test
}//namespace
What could be the possible reason when I unit test Postgresql, it results to RemotingException: Unix transport error. ?
If I run the code outside of unit test (e.g. Main), it works. Btw, if I unit test Sqlite, it doesn't cause any errors too
Found the answer, I tried launching MonoDevelop from Terminal (/Applications/MonoDevelop.app/Contents/MacOS/monodevelop), I saw the more detailed error from the commandline when I ran the unit tests.
Unhandled Exception: System.TypeInitializationException: An exception was thrown by the type initializer for Npgsql.NpgsqlConnection ---> System.TypeLoadException: Could not load type 'System.Runtime.Versioning.TargetFrameworkAttribute' from assembly 'Npgsql'.
at (wrapper managed-to-native) System.MonoCustomAttrs:GetCustomAttributesInternal (System.Reflection.ICustomAttributeProvider,System.Type,bool)
at System.MonoCustomAttrs.GetCustomAttributesBase (ICustomAttributeProvider obj, System.Type attributeType) [0x00000] in <filename unknown>:0
at System.MonoCustomAttrs.GetCustomAttributes (ICustomAttributeProvider obj, System.Type attributeType, Boolean inherit) [0x00000] in <filename unknown>:0
at System.Reflection.Assembly.GetCustomAttributes (System.Type attributeType, Boolean inherit) [0x00000] in <filename unknown>:0
at System.Resources.ResourceManager.GetNeutralResourcesLanguage (System.Reflection.Assembly a) [0x00000] in <filename unknown>:0
at System.Resources.ResourceManager..ctor (System.Type resourceSource) [0x00000] in <filename unknown>:0
at Npgsql.NpgsqlConnection..cctor () [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at (wrapper managed-to-native) System.Reflection.MonoCMethod:InternalInvoke (System.Reflection.MonoCMethod*,object,object[],System.Exception&)
at System.Reflection.MonoCMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0
Then I tried changing the Npgsql version(the one that causes an error came from http://pgfoundry.org/frs/download.php/2868/Npgsql2.0.11-bin-ms.net4.0.zip) to http://pgfoundry.org/frs/download.php/2860/Npgsql2.0.11-bin-mono2.0.zip After this, there's no more Unix transport error ^_^
Lesson learned, use the Mono version of the component you are using if you are running things on Mono
This exception occurs, when a unit test in MonoDevelop raises an exception, which could not be caught by the test runner (i.e. when the test starts some threads and they crash).
If you have such a test which is grey even after running
and the unit test pad shows the internal error
you should try running the test on your console with nunit-console (should be in the repo of your distro where mono comes from) and leak the exception.
In my case it was a simple multiple enumeration exception in a sub-thread of my test.
Unhandled exceptions:
1) Residata.Platform.Server.Message.Test.MemoryBrokerTest.AssertThatReceiveMethodWaitsUntilPublish : System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.Generic.List`1+Enumerator[Residata.Platform.Contract.Message.IPackage].MoveNext () [0x00000] in <filename unknown>:0

Having problems with Powershell ConsoleShell.Start

Running the following code resulting in an HostException;
Public Sub RunPowershellInConsole(ByVal scriptText As String)
Dim config = RunspaceConfiguration.Create
Dim args() As String = New String() {scriptText}
ConsoleShell.Start(config, "Windows PowerShell", "", args)
End Sub
.
System.Management.Automation.Host.HostException was unhandled
Message=The Win32 internal error "The handle is invalid" 0x6 occurred when retrieving handle for active console output buffer. Contact Microsoft Support Services.
Source=Microsoft.PowerShell.ConsoleHost
WasThrownFromThrowStatement=False
StackTrace:
at Microsoft.PowerShell.ConsoleControl.GetActiveScreenBufferHandle()
at Microsoft.PowerShell.ConsoleHostRawUserInterface.GetBufferInfo(CONSOLE_SCREEN_BUFFER_INFO& bufferInfo)
at Microsoft.PowerShell.ConsoleHostRawUserInterface.get_ForegroundColor()
at Microsoft.PowerShell.ConsoleHostRawUserInterface..ctor(ConsoleHostUserInterface mshConsole)
at Microsoft.PowerShell.ConsoleHostUserInterface..ctor(ConsoleHost parent)
at Microsoft.PowerShell.ConsoleHost..ctor(RunspaceConfiguration configuration)
at Microsoft.PowerShell.ConsoleHost.CreateSingletonInstance(RunspaceConfiguration configuration)
at Microsoft.PowerShell.ConsoleHost.Start(RunspaceConfiguration configuration, String bannerText, String helpText, String preStartWarning, String[] args)
at Microsoft.PowerShell.ConsoleShell.Start(RunspaceConfiguration configuration, String bannerText, String helpText, String preStartWarning, String[] args)
at Microsoft.PowerShell.ConsoleShell.Start(RunspaceConfiguration configuration, String bannerText, String helpText, String[] args)
at MyApp.Barry.Bosely.RunPowershell.RunPowershellInConsole(String scriptText) in C:\Dev\MiscProjects\GordonB\Barry\Barry.Bosely\RunPowershell.vb:line 87
at MyApp.Barry.Bosely.frmMain.TEstToolStripMenuItem_Click(Object sender, EventArgs e) in C:\Dev\MiscProjects\GordonB\Barry\Barry.Bosely\frmMain.vb:line 119
at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at MyApp.Barry.Bosely.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.ComponentModel.Win32Exception
ErrorCode=-2147467259
Message=The handle is invalid
NativeErrorCode=6
InnerException:
Little help anyone?
I have just tried this code in my Console Application and it worked:
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;
namespace TryConsoleShell
{
class Program
{
static void Main(string[] args)
{
var config = RunspaceConfiguration.Create();
ConsoleShell.Start(config, "Windows PowerShell", "help text", new string[] { "-noexit", "ls" });
}
}
}
I guess your application is Windows Application and this scenario is either not supported at all or you still have to have a console window available (I have not tried this way yet).
EDIT:
It worked in WinForm Application as well. But the console window is still needed for the console host. To make the console window available just change the project output type to Console Application.
using System;
using System.Management.Automation.Runspaces;
using System.Windows.Forms;
using Microsoft.PowerShell;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var config = RunspaceConfiguration.Create();
ConsoleShell.Start(config, "Windows PowerShell", "help text", new string[] { "-noexit", "ls" });
}
}
}
P.S. I have never seen use of this scenario in practice and did not even know that it actually works. Are there some practically useful applications of it?