SerializationException when raising event in other instance via IPC - wpf

I'm trying to send some information from a newly launched instance of my application to the currently running instance (namely one argument in the form of a string) by way of ipc.
Class RemoteObject
Inherits MarshalByRefObject
Public Event ParamEvent As RemoteObject.ParamEventHandler
Public Property path As String = ""
Delegate Sub ParamEventHandler()
Public Sub FireEvent()
RaiseEvent ParamEvent()
End Sub
End Class
Friend WithEvents on MainWindow:
Friend WithEvents theRemoteObject As RemoteObject
I'm setting it up in my first instance like this.
theRemoteObject = New RemoteObject
theRemoteObject.path = "blah"
theChannel = New IpcChannel("localhost:9090")
ChannelServices.RegisterChannel(theChannel, False)
RemotingServices.Marshal(theRemoteObject, "ParamReceiver")
And in my second instance:
Dim uri As String = "ipc://localhost:9090/ParamReceiver"
theChannel = New IpcChannel
ChannelServices.RegisterChannel(theChannel, False)
theRemoteObject = DirectCast(RemotingServices.Connect(GetType(RemoteObject), uri), RemoteObject)
theRemoteObject.path = "blarg"
theRemoteObject.FireEvent()
Everything works properly; when the second instance starts the path property changes from "blah" to "blarg" in both instances. However, when I add this event handler in MainWindow:
Public Sub ParamHandler() Handles theRemoteObject.ParamEvent
'do stuff here
End Sub
It halts on this line in the second instance:
theRemoteObject = DirectCast(RemotingServices.Connect(GetType(RemoteObject), uri), RemoteObject)
With the following exception:
An exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll but was not handled in user code
Additional information: Type 'Cutlist3.MainWindow' in Assembly 'Cutlist3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
I don't know what this means or where to start in debugging it. Any information you could provide would be super helpful and appreciated!

For future reference, I solved my problem by creating a new object declaration in the second instance Dim SecondObject as RemoteObject = DirectCast ... instead of using the original Friend WithEvents theRemoteObject declaration.

Related

Property Injection for User Controls in WinForms

I have inherited an a VB.NET WinForms application. It is very poorly written with a lot of bad practices. The first order of business is to get some DI into the app with a container to resolve the dependencies so I can start breaking this thing up and getting it under test.
This is my first WinForms app and I am learning the nuances of a non-request based application on a single thread.
I am using Simple Injector as the IoC container.
One of my use cases that I need to refactor is a UserControl that is extending a DevExpress XtraUserControl.
From the Simple Injector docs:
Note: It is not possible to use Constructor Injection in User Controls. User Controls are required to have a default constructor. Instead, pass on dependencies to your User Controls using Method Injection.
I am following the docs verbatim on how to set up property injection:
IPropertySelectionBehavior
Here is my configuration:
Private Shared Sub Bootstrap()
Container = New Container()
Container.Options.DefaultScopedLifestyle = New ThreadScopedLifestyle()
Container.Options.PropertySelectionBehavior = New ImportPropertySelectionBehavior()
Container.Register(Of ICommissionManager, CommissionManager)(Lifestyle.Singleton)
Container.Register(Of frmMain, frmMain)(Lifestyle.Singleton)
Container.Register(Of viewSalesCustomers, viewSalesCustomers)(Lifestyle.Transient)
'https://stackoverflow.com/questions/38417654/winforms-how-to-register-forms-with-ioc-container/38421425
Dim registration As Registration = Container.GetRegistration(GetType(viewSalesCustomers)).Registration
registration.SuppressDiagnosticWarning(DiagnosticType.DisposableTransientComponent, "a reason")
Container.Verify()
End Sub
The user control:
Public Class viewSalesCustomers
Inherits DevExpress.XtraEditors.XtraUserControl
<Import>
Public Property CommissionManager As ICommissionManager
...redacted...
Private Sub viewSalesCustomers_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim commissions As ICollection(Of Commission)
commissions = CommissionManager.Get(Function(commission) commission.CommissionId = 1) <-- Always nothing (null)
End Sub
I know the container is resolving for anything deriving from Form (I tested it through constructor injection).
Not sure what I missing here on the property injection for this control.
UPDATE:
#Steven was spot on. I found where they are instantiating the control.
Private Sub BarSubItem2_ItemClick(ByVal sender As Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarSubItem2.ItemClick
Cursor = Cursors.WaitCursor
'Dim mView as New viewSalesCustomers()
Dim mView As viewSalesCustomers
mView = Program.Container.GetInstance(Of viewSalesCustomers)
showViewer(mView, "viewSalesCustomers")
Cursor = Cursors.Default
End Sub

Make WPF-control shared

I'm trying to access Label from another class's method running in background thread with the help of MainWindow Class's Public Shared Sub like this:
Private Delegate Sub ProgressReportInvoker(ByVal progressStr As String)
Public Shared Sub ProgressReport(ByVal progressStr As String)
If MainWindow.Label.Dispatcher.CheckAccess() Then
MainWindow.Label.Content = progressStr
Else
MainWindow.Label.Dispatcher.Invoke(
New ProgressReportInvoker(AddressOf ProgressReport),
progressStr)
End If
End Sub
Call from another class is below:
MainWindow.ProgressReport("Sample text")
But I have this error on "MainWindow.Label":
Reference to a non-shared member requires an object reference.
I noticed that if I declare Label in MainWindow.g.i.vb as Public Shared than error is gone:
#ExternalSource ("..\..\MainWindow.xaml", 11)
<System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")>
Public Shared WithEvents Label As System.Windows.Controls.Label
#End ExternalSource
But this file is generated automatically from the *.XAML file so it takes previous look when I compile the code.
Is there any way to make control shared in *.XAML file or may be there are any alternatives of making my task possible?
You should access the instance of the MainWindow and not the type itself:
Public Shared Sub ProgressReport(ByVal progressStr As String)
Dim mainWindow = Application.Current.Windows.OfType(Of MainWindow).FirstOrDefault()
If mainWindow.Label.Dispatcher.CheckAccess() Then
mainWindow.Label.Content = progressStr
Else
mainWindow.Label.Dispatcher.Invoke(
New ProgressReportInvoker(AddressOf ProgressReport),
progressStr)
End If
End Sub
I tried this before but problem is in multitasking. I can't access the form from another thread without some special moves which I don't know about
You can only access a UI control in the thread on which it was originally created:
Application.Current.Dispatcher.BeginInvoke(New Action(Sub()
Dim mainWindow = Application.Current.Windows.OfType(Of MainWindow).FirstOrDefault()
mainWindow.Label.Content = progressStr
End Sub))
It is very bad practice to use anything global (shared/static). Use instance of class or other mechanism (Dependency Injection, messaging, events, etc.) for communication between independent classes.

DispatcherObject cast woes and Async / ObservableCollection issues in WPF

The code below pulls out a bunch of records from an Access 2010 database; hence rolling my own connector bits. I've succeeded in doing the observablecollection and made it all bind up with nice drag and drop data sources, from my own objects. However, like a daft person, I want to do this Asynchronously. Yet, I've got a small cast monster problem, and I don't know what to feed it! Can anyone advise me - I've tried a lot of reading around, but the concepts are just a little too many at once on a Friday afternoon and I'm struggling to make any real headway.
The line I'm having trouble with is:
Dim dispatcherObject As DispatcherObject = CType (handler.Target, DispatcherObject )
The exception is:
Unable to cast object of type '_Closure$__2[SomeRecord_Viewer.SomeRecord]' to type 'System.Windows.Threading.DispatcherObject'.
I've managed to make a WPF listbox populate via the code below, however only by commenting out a part of the ObservableCollectionEx class. This causes synchronisation problems and a crash after a few hundred records are entered.
Class that builds the threaded list of entities - in this case, an ObservableCollectionEx(Of SomeRecord):
Class SomeRecordSet
Inherits ObservableCollectionEx( Of SomeRecord)
Private Shared Property _SomeRecordList As New ObservableCollectionEx(Of SomeRecord )
Public Shared ReadOnly Property SomeRecordList As ObservableCollectionEx(Of SomeRecord )
Get
If _SomeRecordList.Count = 0 Then BuildSomeRecordListAsync()
Return _SomeRecordList
End Get
End Property
Public Shared ReadOnly Property ReturnSingleSomeRecord(id As Integer) As SomeRecord
Get
Return ( From SomeRecord In _SomeRecordList Where SomeRecord.id = id Select SomeRecord).First()
End Get
End Property
Private Shared Async Sub BuildSomeRecordListAsync()
Await Task.Run( Sub() BuildSomeRecordList())
Return
End Sub
Private Shared Sub BuildSomeRecordList()
Db.newcmd( "Select * from RecordList ")
While Db.read
Dim SomeRecord As New SomeRecord
With SomeRecord
.id = Db.dbint( "ID")
.type = Db.dbin( "type")
End With
_SomeRecordList.Add(SomeRecord)
End While
End Sub`
Partial code for the SomeRecord class:
Class SomeRecord
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged( ByVal info As String)
RaiseEvent PropertyChanged(Me , New PropertyChangedEventArgs (info))
End Sub
...'lots of simple properties.
End Class
The threaded collection class code - translated from another online source.
'I use PostSharp for try catch stuff.
`
Public Class ObservableCollectionEx (Of T )
Inherits ObservableCollection( Of T)
' Override the event so this class can access it
Public Shadows Event CollectionChanged As System.Collections.Specialized.NotifyCollectionChangedEventHandler
Protected Overrides Sub OnCollectionChanged( ByVal e As System.Collections.Specialized.NotifyCollectionChangedEventArgs )
Using BlockReentrancy()
Dim eventHandler As System.Collections.Specialized.NotifyCollectionChangedEventHandler = Sub () RaiseEvent CollectionChanged(Me , e)
If (eventHandler Is Nothing) Then Return
Dim delegates() As [Delegate] = eventHandler.GetInvocationList
*******If I comment this out I can populate the Listbox via a CollectionView, however it dies with issues to do with the list not staying synchronised :).
'Walk thru invocation list
For Each handler As System.Collections.Specialized.NotifyCollectionChangedEventHandler In delegates
Dim dispatcherObject As DispatcherObject = CType (handler.Target, DispatcherObject)
' If the subscriber is a DispatcherObject and different thread
If (( Not (dispatcherObject) Is Nothing) AndAlso (dispatcherObject.CheckAccess = False )) Then
' Invoke handler in the target dispatcher's thread
dispatcherObject.Dispatcher.Invoke(DispatcherPriority .DataBind, handler, Me, e)
Else
handler( Me, e)
End If
Next
*******End of stuff I comment out to get working partially***
End Using
End Sub
End Class
From what I can see, you have two problems.
You're assigning the local variable eventHandler to an anonymous method, rather than the actual event handler. It should be:
Dim eventHandler As NotifyCollectionChangedEventHandler = CollectionChangedEvent
NB: You need to use CollectionChangedEvent in VB, not CollectionChanged.
You're using CType to cast the target to a DispatcherObject, which won't work if the target isn't a DispatcherObject. Use TryCast instead:
Dim dispatcherObject As DispatcherObject = TryCast(handler.Target, DispatcherObject)
You can also tidy up the test on the next line by using IsNot:
If dispatcherObject IsNot Nothing AndAlso Not dispatcherObject.CheckAccess Then
WARNING - The code below acts differently to the C# version. The key difference seems to be that in VB you can't Override an Event (Why on earth not?) yet in C# you can.
The result is the Handler is Nothing in VB but not in C# :(.
So the syntax builds without error but the VB version doesn't ever do anything.
Redone with the updated answer in VB. Thank you!
Note I cannot make this work with Entity Framework, yet. But I think that a me and EF issue, not the collection.
The code itself is here for anyone interested. My list DOES populate perfectly fine now. However, I would take this answer of mine with a small pinch of salt until I update saying how I've extensively tested perhaps :)
However the omens are good - here is the original C# author's site: Original Site
Public Class ObservableCollectionEx(Of T)
Inherits ObservableCollection(Of T)
'Override the event so this class can access it
Public Shadows Event CollectionChanged As NotifyCollectionChangedEventHandler
Protected Overrides Sub OnCollectionChanged(ByVal e As NotifyCollectionChangedEventArgs)
Using BlockReentrancy()
Dim eventHandler As System.Collections.Specialized.NotifyCollectionChangedEventHandler = CollectionChangedEvent
If eventHandler Is Nothing Then
Return
End If
Dim delegates() As [Delegate] = CollectionChangedEvent.GetInvocationList
'Walk thru invocation list
For Each handler As NotifyCollectionChangedEventHandler In delegates
Dim dispatcherObject As DispatcherObject = TryCast(handler.Target, DispatcherObject)
' If the subscriber is a DispatcherObject and different thread
If dispatcherObject IsNot Nothing AndAlso Not dispatcherObject.CheckAccess Then
' Invoke handler in the target dispatcher's thread
dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, Me, e)
Else
handler(Me, e)
End If
Next
End Using
End Sub
End Class

Accessing the UI thread to change dependancy properties in WPF

I'm trying to update a dependancy property in VB.Net 4.0 inside of an Async callback. I feel like I am doing this correctly but I'm still getting the "The calling thread cannot access this object because a different thread owns it." error. Does someone see a better way of using delegates in VB.Net 4.0?
Private WithEvents myObj as CallingObject
Private Delegate Sub MyErrorDel(ByVal strError as string)
Public Property ErrorMessage As String
Get
Return CStr(GetValue(ErrorMessageProperty))
End Get
Set(ByVal value As String)
SetValue(ErrorMessageProperty, value)
End Set
End Property
Private Sub MySub()
myObj.CallFuncAsync()
End Sub
Private Sub DisplayError(ByVal strError as String)
'Set Dependancy Property value Bound to UI Textbox
ErrorMessage = strError
End Sub
Private Sub myObj_CallFuncCompleted(Byval sender as Object, ByVal e as CallFuncEventArgs)
'Call delegate and pass in error string as argument
Dim delError as MyErrorDel
delError = New MyErrorDel(AddressOf DisplayError)
delError("An error occured")
Me.Dispatcher.Invoke(delError, System.Windows.Threading.DispatcherPriority.Normal, Nothing)
End Sub
Whenever ErrorMessage gets set inside of DisplayError an exception gets thrown, even though I am using the dispatcher to call DisplayError.
If anyone see any issues with the way I am trying to access Dependancy Properties from a async callback I would really appreciate the feedback.
Thanks for the help!
Oh and I'm pretty new at blogging about code issues. Any suggestions about how to better formulate this question would be welcome as well.
The problem might be that at the call to Me... you are already accessing an object owned by another thread, try to store a reference to the dispatcher beforehand or possibly use Application.Current.Dispatcher.
Since you didn't indicate the offending line, I suspect the problem here is that you're invokng your delegate in the line delError("An error occured") rather than waiting until you get to the dispatcher. Consider changing your CallFuncCompeted implementation to
Me.Dispatcher.Invoke(AddressOf DisplayError, "An error occureed")

WPF Custom Control and exposing properties thru DependencyProperty

Ok - I'm pulling my hair out over what I thought was a simple scenario: create a custom Label for bilingual use that contained two additional properties (EnglishText, FrenchText). Currently its structured like this:
Public Class myCustomLabel
Inherits System.Windows.Controls.Label
Public myEnglishTextProperty As DependencyProperty = DependencyProperty.Register("myEnglishText", GetType(String), GetType(myCustomLabel), New PropertyMetadata("English", New PropertyChangedCallback(AddressOf TextChanged)))
Public myFrenchTextProperty As DependencyProperty = DependencyProperty.Register("myFrenchText", GetType(String), GetType(myCustomLabel), New PropertyMetadata("Francais", New PropertyChangedCallback(AddressOf TextChanged)))
Public Sub New()
'This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class.
'This style is defined in themes\generic.xaml
DefaultStyleKeyProperty.OverrideMetadata(GetType(myCustomLabel), New FrameworkPropertyMetadata(GetType(myCustomLabel)))
End Sub
Public Property myEnglishText() As String
Get
Return MyBase.GetValue(myFrenchTextProperty)
End Get
Set(ByVal value As String)
MyBase.SetValue(myFrenchTextProperty, value)
End Set
End Property
Public Property myFrenchText() As String
Get
Return MyBase.GetValue(myFrenchTextProperty)
End Get
Set(ByVal value As String)
MyBase.SetValue(myFrenchTextProperty, value)
End Set
End Property
Private Sub TextChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
If DesignerProperties.GetIsInDesignMode(Me) = True Then
Me.Content = myEnglishText
Else
If myUser.Language = "E" Then
Me.Content = myEnglishText
Else
Me.Content = myFrenchText
End If
End If
End Sub
End Class
My test window grid xaml is simple:
<Grid>
<my:myCustomLabel myEnglishText="English Text" myFrenchText="English Text" Height="25" Width="100" Background="Aqua" Foreground="Black"/>
</Grid>
This seems to work in the development environment - changing the English and French texts change the in the design preview and it works when the app runs and the test window is opened. But only the first time - if I open the test window a second time I receive the following message:
'myEnglishText' property was already
registered by 'myCustomLabel'.
I understand now that if I change the dependency property declarations to shared then this problem goes away - but that leads to a host of other problems like the callback function being required to be shared as well - and thus unable to update the Content (which needs to be instantiated with the class). All I really want is the content property to be updated in design time when the english and french labels are changed.
Is there a way around this? Or maybe are dependency properties overkill for what I need?
You are registering your dependency properties as instance variables, and during the instance constructor. So they are getting registered again every time you instantiate the control, which causes an error the second time. As you have found out, dependency properties need to be static (Shared) members:
Public Shared myEnglishTextProperty As DependencyProperty =
DependencyProperty.Register("myEnglishText", GetType(String), GetType(myCustomLabel),
New PropertyMetadata("English", New PropertyChangedCallback(AddressOf TextChanged)))
You probably need to call OverrideMetadata in your shared constructor (type initialiser) rather than your instance constructor as well.
Regarding your issue with the callback needing to be shared: yes, it will be, but one of the arguments to the callback is the label instance. So you can just cast that to label and call an instance method on that:
private static void TextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((MyLabel)d).TextChanged();
}
private void TextChanged()
{
// your code here
}
(forgive C# syntax)
Is the reason you don't want the callback method to be shared because you're accessing the "me" instance? If that's all it is, make it shared and use the "d" parameter. I don't know VB well enough to show you the code, but just create a variable of type myCustomLabel and assign "d" to it (with a cast). Then use that variable (say "lbl") instead:
If DesignerProperties.GetIsInDesignMode(lbl) = True Then
lbl.Content = myEnglishText
Else
If myUser.Language = "E" Then
lbl.Content = myEnglishText
Else
lbl.Content = myFrenchText
End If
End If
Also, there's a slight bug in your example code. Try using this:
Public Property myEnglishText() As String
Get
Return MyBase.GetValue(myEnglishTextProperty)
End Get
Set(ByVal value As String)
MyBase.SetValue(myEnglishTextProperty, value)
End Set
End Property
Instead of this:
Public Property myEnglishText() As String
Get
Return MyBase.GetValue(myFrenchTextProperty)
End Get
Set(ByVal value As String)
MyBase.SetValue(myFrenchTextProperty, value)
End Set
End Property

Resources