Having problems with Powershell ConsoleShell.Start - vb.net

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?

Related

HanaConnection NullReferenceException:

I am using VS2019, windows 10 Framework 4.5 and Sap.Data.Hana.v4.5, Version=2.3.144.0
When I execute this code in page load
HanaConnection conn = new HanaConnection();
got error
Sap.Data.Hana.HanaUnmanagedDll.SearchNativeDlls() +346
Sap.Data.Hana.HanaUnmanagedDll..ctor() +18
Sap.Data.Hana.HanaUnmanagedDll.get_Instance() +103
Sap.Data.Hana.HanaConnection..cctor() +42
[TypeInitializationException: The type initializer for 'Sap.Data.Hana.HanaConnection' threw an exception.]
Sap.Data.Hana.HanaConnection..ctor() +15
Home.Page_Load(Object sender, EventArgs e) in c:\NerveNew\Home.aspx.cs:20
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +85
System.Web.UI.Control.OnLoad(EventArgs e) +79
System.Web.UI.Control.LoadRecursive() +130
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2852```

Null error on ImageRezising.net Faces plugin

I'm testing the faces plugin: http://imageresizing.net/docs/v4/plugins/faces
But I'm only getting the response "Object reference not set to an instance of an object.". Why? From the look of it the error is from the ImageRezing.net software.
Here is an example to see the error:
http://azure.content.dev.bloc.net/azure/group/200000206/5319/2018/10/10/20150406145944-dos-donts-taking-perfect-linkedin-profile-picture-selfie-mobile-camera-2.jpeg?f.detect=true
Exception information:
Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object.
at ImageResizer.Plugins.Faces.FeatureDetectionBase`1.Dispose()
at ImageResizer.Plugins.Faces.FacesPlugin.PostPrepareSourceBitmap(ImageState s)
at ImageResizer.Resizing.AbstractImageProcessor.PostPrepareSourceBitmap(ImageState s)
at ImageResizer.ImageBuilder.Process(ImageState s)
at ImageResizer.ImageBuilder.BuildJobBitmapToBitmap(ImageJob job, Bitmap source, Boolean transparencySupported)
at ImageResizer.ImageBuilder.BuildJobBitmapToStream(ImageJob job, Bitmap source, Stream dest)
at ImageResizer.ImageBuilder.BuildJob(ImageJob job)
at ImageResizer.ImageBuilder.Build(ImageJob job)
at ImageResizer.InterceptModule.<>c__DisplayClass5_0.b__1(Stream stream)
at ImageResizer.Plugins.DiskCache.CustomDiskCache.<>c__DisplayClass29_0.b__0()
at ImageResizer.Plugins.DiskCache.LockProvider.TryExecute(String key, Int32 timeoutMs, LockCallback success)
at ImageResizer.Plugins.DiskCache.CustomDiskCache.GetCachedFile(String keyBasis, String extension, ResizeImageDelegate writeCallback, Int32 timeoutMs, Boolean asynchronous)
at ImageResizer.Plugins.DiskCache.DiskCache.Process(IResponseArgs e)
at ImageResizer.Plugins.DiskCache.DiskCache.Process(HttpContext context, IResponseArgs e)
at ImageResizer.InterceptModule.HandleRequest(HttpContext context, HttpModuleRequestAssistant ra, IVirtualFile vf)
at ImageResizer.InterceptModule.CheckRequest_PostAuthorizeRequest(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Global.asax has nothing:
using ImageResizer.Plugins.RemoteReader;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
namespace Bloc.AzureContent
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RemoteReaderPlugin.Current.AllowRemoteRequest += Current_AllowRemoteRequest;
}
static void Current_AllowRemoteRequest(object sender, RemoteRequestEventArgs args)
{
args.DenyRequest = false;
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
}

Unable To Cast Object error when trying to populate ObjectListView control

I have downloaded the ObjectListView.dll and added it as a reference into my VB.NET application. I have added it to my toolbox and added an ObjectListView control to my form. However, when I try and populate it, I get the following error:
Unable to cast object of type 'System.Windows.Forms.ListViewItem' to
type 'BrightIdeasSoftware.OLVListItem'
My code snippet looks like so:
lsvOverdueCalls.Items.Add(tempDT.Rows(0)("id").ToString)
lsvOverdueCalls.Items(0).SubItems.Add(tempDT.Rows(0)("summary").ToString)
lsvOverdueCalls.Items(0).SubItems.Add(tempDT.Rows(0)("first_name").ToString)
Unsure if I'm doing something wrong. My applicaton is compiled under the full version of dot.net 4.5, not the client version as advised.
Any help appreciated.
Update
I noticed I get the following error in my debugger window but ONLY when moving the mouse over a ListViewItem:
A first chance exception of type 'System.InvalidCastException'
occurred in ObjectListView.dll System.Transactions Critical: 0 :
http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/UnhandledUnhandled
exceptionDrakeMon2.0.vshost.exeSystem.InvalidCastException,
mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089Unable to cast
object of type 'System.Windows.Forms.ListViewItem' to type
'BrightIdeasSoftware.OLVListItem'. at
BrightIdeasSoftware.ObjectListView.GetItem(Int32 index) at
BrightIdeasSoftware.ObjectListView.LowLevelHitTest(Int32 x, Int32 y)
at BrightIdeasSoftware.ObjectListView.OlvHitTest(Int32 x, Int32 y)
at BrightIdeasSoftware.ObjectListView.BuildCellEvent(CellEventArgs
args, Point location) at
BrightIdeasSoftware.ObjectListView.OnMouseMove(MouseEventArgs e) at
System.Windows.Forms.Control.WmMouseMove(Message& m) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.ListView.WndProc(Message& m) at
BrightIdeasSoftware.ObjectListView.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(IntPtr
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
System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at
DrakeMon2.frmNewDashboard.ToolStripMenuItem2_Click(Object sender,
EventArgs e) in C:\Dropbox\VS Projects\DrakeMon v2.0\DrakeMon
v2.0\frmNewDashboard.vb:line 986 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.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(IntPtr
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 DrakeMon2.My.MyApplication.Main(String[] Args) in
17d14f5c-a337-4978-8281-53493378c1071.vb:line 81 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at
System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext
activationContext, String[] activationCustomData) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()System.InvalidCastException:
Unable to cast object of type 'System.Windows.Forms.ListViewItem' to
type 'BrightIdeasSoftware.OLVListItem'. at
BrightIdeasSoftware.ObjectListView.GetItem(Int32 index) at
BrightIdeasSoftware.ObjectListView.LowLevelHitTest(Int32 x, Int32 y)
at BrightIdeasSoftware.ObjectListView.OlvHitTest(Int32 x, Int32 y)
at BrightIdeasSoftware.ObjectListView.BuildCellEvent(CellEventArgs
args, Point location) at
BrightIdeasSoftware.ObjectListView.OnMouseMove(MouseEventArgs e) at
System.Windows.Forms.Control.WmMouseMove(Message& m) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.ListView.WndProc(Message& m) at
BrightIdeasSoftware.ObjectListView.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(IntPtr
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
System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at
DrakeMon2.frmNewDashboard.ToolStripMenuItem2_Click(Object sender,
EventArgs e) in C:\Dropbox\VS Projects\DrakeMon v2.0\DrakeMon
v2.0\frmNewDashboard.vb:line 986 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.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(IntPtr
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 DrakeMon2.My.MyApplication.Main(String[] Args) in
17d14f5c-a337-4978-8281-53493378c1071.vb:line 81 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at
System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext
activationContext, String[] activationCustomData) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()
I'm assuming a threading issue, but I'm unsure why this control throws an error and a normal listview or even the BetterListView control doesn't. My form only contains this control and nothing else. And...like mentioned, it ONLY occurs if I try and move the mouse over a ListViewItem.
Thanks
You cannot do Add() on the ObjectListView like you do on a normal ListView. Instead, you need to call the SetObjects method on the ObjectListView instance, and pass it a list of items to add.
So in your case, create a List<Call> of the items to add (assuming your model is a Call class with id, summary and first_name fields, and then pass it on to the lsvOverdueCalls.SetObjects() like so.
var lstCalls = new List<Call>()
{
new Call() {
Id = tempDT.Rows(0)("id").ToString,
Summary = tempDT.Rows(0)("summary").ToString,
First_Name = tempDT.Rows(0)("first_name").ToString
}
};
lsvOverdueCalls.SetObjects(lstCalls);
And here's how your Call model should look like.
public class Call
{
public string Id { get; set; }
public string Summary { get; set; }
public string First_Name { get; set; }
}

Why does .NET4 try-catch fail on a simple user exception in Release only?

Here's an example. On the app below, I click Start, then Stop - in Release only*, the Start routine's catch does not get the Stop's exception.
*EDIT: Now I find this is specific not to Release build, but to any build run outside the debugger. I.e. Release and Debug builds outside the debugger fail, and Debug build inside the debugger is OK. Rather worrying to see that not attatching the debugger can have such a detrimental effect!
EDIT: Here's the stack trace from running Release build from Windows Explorer:
WindowsFormsApplication1.RunStopException: Exception of type 'WindowsFormsApplication1.RunStopException' was thrown.
at WindowsFormsApplication1.Form1.Stop_button_Click(Object sender, EventArgs e) in D:\Projects\! FastSpecc FAP2\RunStopExceptionfail\Form1.cs:line 35
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)
and the stack trace from running Debug from the VS2010 debugger: http://img502.imageshack.us/img502/2749/runstopexceptionfaildeb.png
Code as text:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Start_button.Enabled = true; Stop_button.Enabled = false;
}
private void Start_button_Click(object sender, EventArgs e)
{
this.Text= "Started";
try
{
Start_button.Enabled = false; Stop_button.Enabled = true;
while (true)
Application.DoEvents();
}
catch (RunStopException)
{
// in Debug build, works fine.
// In Release build, fails
// Unhandled exception has occurred in your application. ...
// Exception of type 'WindowsFormsApplication1.RunStopException' was thrown.
this.Text= "Stopped";
Start_button.Enabled = true; Stop_button.Enabled = false;
}
}
private void Stop_button_Click(object sender, EventArgs e)
{
this.Text= "Stopping";
throw new RunStopException();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
public class RunStopException : Exception { }
}

Reassign ItemsSource - Items collection must be empty before using ItemsSource

I'm using ItemsSource on a ListView. I now want to perform a search and filter the items with an SQL query, so I reassign the ItemsSource; but then an exception is thrown:
Items collection must be empty before using ItemsSource.
Alright, but how can I empty the items collection? Items.Clear is not allowed when using ItemsSource..
Okay, code looks like this:
this.Songs.ItemsSource = this.Library.ExecuteQuery<Songs>("SELECT * FROM songs WHERE title LIKE '%" + search + "%' OR artist LIKE '%" + search + "%' OR album LIKE '%" + search + "%'");
This piece of code is executed every time the text in the search box is changed.
Here are the exception details:
System.InvalidOperationException was unhandled
Message="Items collection must be empty before using ItemsSource."
Source="PresentationFramework"
StackTrace:
bei System.Windows.Controls.ItemCollection.SetItemsSource(IEnumerable value)
bei System.Windows.Controls.ItemsControl.OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
bei System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
bei System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
bei System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
bei System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType)
bei System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, OperationType operationType, Boolean isInternal)
bei System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
bei System.Windows.Controls.ItemsControl.set_ItemsSource(IEnumerable value)
bei Musiclibrary.Window1.Search_TextChanged(Object sender, TextChangedEventArgs e) in C:\Dokumente und Einstellungen\v. Wurstemberger\Eigene Dateien\Visual Studio 2008\Projects\Musiclibrary\Musiclibrary\Window1.xaml.cs:Zeile 132.
bei System.Windows.Controls.TextChangedEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
bei System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
bei System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
bei System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
bei System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
bei System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
bei System.Windows.Controls.Primitives.TextBoxBase.OnTextChanged(TextChangedEventArgs e)
bei System.Windows.Controls.Primitives.TextBoxBase.OnTextContainerChanged(Object sender, TextContainerChangedEventArgs e)
bei System.Windows.Controls.TextBox.OnTextContainerChanged(Object sender, TextContainerChangedEventArgs e)
bei System.Windows.Documents.TextContainerChangedEventHandler.Invoke(Object sender, TextContainerChangedEventArgs e)
bei System.Windows.Documents.TextContainer.EndChange(Boolean skipEvents)
bei System.Windows.Documents.TextContainer.System.Windows.Documents.ITextContainer.EndChange(Boolean skipEvents)
bei System.Windows.Documents.TextRangeBase.EndChange(ITextRange thisRange, Boolean disableScroll, Boolean skipEvents)
bei System.Windows.Documents.TextRange.System.Windows.Documents.ITextRange.EndChange(Boolean disableScroll, Boolean skipEvents)
bei System.Windows.Documents.TextRange.ChangeBlock.System.IDisposable.Dispose()
bei System.Windows.Documents.TextEditorTyping.DoTextInput(TextEditor This, String textData, Boolean isInsertKeyToggled, Boolean acceptControlCharacters)
bei System.Windows.Documents.TextEditorTyping.TextInputItem.Do()
bei System.Windows.Documents.TextEditorTyping.ScheduleInput(TextEditor This, InputItem item)
bei System.Windows.Documents.TextEditorTyping.OnTextInput(Object sender, TextCompositionEventArgs e)
bei System.Windows.Controls.Primitives.TextBoxBase.OnTextInput(TextCompositionEventArgs e)
bei System.Windows.UIElement.OnTextInputThunk(Object sender, TextCompositionEventArgs e)
bei System.Windows.Input.TextCompositionEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
bei System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
bei System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
bei System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
bei System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
bei System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
bei System.Windows.Input.InputManager.ProcessStagingArea()
bei System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
bei System.Windows.Input.TextCompositionManager.UnsafeCompleteComposition(TextComposition composition)
bei System.Windows.Input.TextCompositionManager.PostProcessInput(Object sender, ProcessInputEventArgs e)
bei System.Windows.Input.InputManager.ProcessStagingArea()
bei System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
bei System.Windows.Input.TextCompositionManager.UnsafeStartComposition(TextComposition composition)
bei System.Windows.Input.TextCompositionManager.PostProcessInput(Object sender, ProcessInputEventArgs e)
bei System.Windows.Input.InputManager.ProcessStagingArea()
bei System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
bei System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
bei System.Windows.Interop.HwndKeyboardInputProvider.ProcessTextInputAction(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
bei System.Windows.Interop.HwndSource.OnPreprocessMessage(Object param)
bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
bei System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
bei System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
bei System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
bei System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
bei System.Windows.Interop.HwndSource.OnPreprocessMessageThunk(MSG& msg, Boolean& handled)
bei System.Windows.Interop.HwndSource.WeakEventPreprocessMessage.OnPreprocessMessage(MSG& msg, Boolean& handled)
bei System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage(MSG& msg)
bei System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
bei System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
bei System.Windows.Threading.Dispatcher.Run()
bei System.Windows.Application.RunDispatcher(Object ignore)
bei System.Windows.Application.RunInternal(Window window)
bei System.Windows.Application.Run(Window window)
bei System.Windows.Application.Run()
bei Musiclibrary.App.Main() in C:\Dokumente und Einstellungen\v. Wurstemberger\Eigene Dateien\Visual Studio 2008\Projects\Musiclibrary\Musiclibrary\obj\Debug\App.g.cs:Zeile 0.
bei System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
bei System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bei System.Threading.ThreadHelper.ThreadStart()
InnerException:
This is usually a sign that you're setting the ItemsSource property AND you have manipulated the actual elements within the ItemsControl itself meaning either you've put things in the XAML or have manually added Children to the ItemsControl.