WCF - communication object cannot be used for communication - wcf

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"

Related

integrate vivotek ip camera in C# windows application using VitaminCtrl

i develop a application to get video from vivotek ip camera the code is given below but it shows connecting to 10.60.13.12... video is not received
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 VITAMINDECODERLib;
using AxVITAMINDECODERLib;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnconnect_Click_1(object sender, EventArgs e)
{
string strPreIP = "http://";
if (txtip.TextLength != 0)
axVitaminCtrl1.Url = strPreIP + txtip.Text;
// Port
axVitaminCtrl1.HttpPort = Convert.ToInt32(txtport.Text);
// User name
if (txtusername.TextLength != 0)
axVitaminCtrl1.UserName = txtusername.Text;
// Password
if (txtpass.TextLength != 0)
axVitaminCtrl1.Password = txtpass.Text;
// View stream
axVitaminCtrl1.ViewStream = (VITAMINDECODERLib.EDualStreamOption)comboviewstream.SelectedIndex.GetHashCode();
// Protocol
axVitaminCtrl1.ConnectionProtocol = (VITAMINDECODERLib.EConnProtocol)comboprotocol.SelectedIndex.GetHashCode() + 1;
axVitaminCtrl1.Connect();
}
private void button1_Click(object sender, EventArgs e)
{
axVitaminCtrl1.Disconnect();
}
private void comboviewstream_SelectedIndexChanged(object sender, EventArgs e)
{
axVitaminCtrl1.ViewStream = (VITAMINDECODERLib.EDualStreamOption)((System.Windows.Forms.ComboBox)sender).SelectedIndex.GetHashCode();
}
private void axVitaminCtrl1_OnVideoCodec(object sender, _IVitaminCtrlEvents_OnVideoCodecEvent e)
{
e.eVideoCodec = VITAMINDECODERLib.EVideoCodecType.eViCodecMJpeg;
}
}
}
You should check debug/release platform (change it to x86)
Your pc that run this program and the camera should have same subnet

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.

UnauthorizedAccessException in Webcam app

I'm trying to make a simple webcam app:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media.MediaProperties;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
namespace App1
{
public sealed partial class MainPage : Page
{
private Windows.Media.Capture.MediaCapture m_mediaCaptureMgr;
private Windows.Storage.StorageFile m_photoStorageFile;
private readonly String PHOTO_FILE_NAME = "photo.jpg";
public MainPage()
{
this.InitializeComponent();
}
internal async void initializeCamera()
{
m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
await m_mediaCaptureMgr.InitializeAsync();
statusBox.Text = "initialized";
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
internal async void takePicture(object sender, RoutedEventArgs e)
{
m_photoStorageFile = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(PHOTO_FILE_NAME, Windows.Storage.CreationCollisionOption.GenerateUniqueName);
ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
await m_mediaCaptureMgr.CapturePhotoToStorageFileAsync(imageProperties, m_photoStorageFile);
}
private void initializeButton(object sender, RoutedEventArgs e)
{
initializeCamera();
}
}
}
However, when I click on the initializeButton, I got an exception:
UnauthorizedAccessException (Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)))
What could be the problem here?
EDIT: I found the bug. Basically, if the webcam is already initialized, trying to initialize it again will trigger an exception. So I had to put in a flag, and some try/catch
Have you set the capabilities for Microphone and Webcam in the manifest file?
Seect the Microphone and Webcam capability in Package.Appmnifest file

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

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.

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?