AllJoyn Studio - Multiple Interface Implementation - c#

I am trying to implement an AllJoyn consumer with multiple interfaces. The AllJoyn menu creates the helper files for all the interfaces from the introspection xml. After Adding the watcher event handler and starting the same for all the interfaces only the first watcher event handler is fired and completed.
for example in the LSF introspection we have four interfaces hence:
AllJoynBusAttachment bus_Consumer = new AlljoynBusAttachment();
watcher_Consumer = new LampStateWatcher(bus_Consumer);
watcher_Consumer.Added += Watcher_Consumer_Added;
watcher_Consumer.Start();
watcher_Details = new LampDetailsWatcher(bus_Consumer);
watcher_Details.Added += Watcher_Details_Added;
watcher_Details.Start();
private async void Watcher_Details_Added(LampDetailsWatcher sender, AllJoynServiceInfo args)
{
Join_Session_Details = await LampDetailsConsumer.JoinSessionAsync(args, sender);
Consumer_Details = Join_Session_Details.Consumer;
if (Join_Session_Details.Status == AllJoynStatus.Ok)
{
var LampName = await Consumer_Details.GetLampIDAsync();
Status_List.Items.Add(LampName.LampID);
}
}
private async void Watcher_Consumer_Added(LampStateWatcher sender, AllJoynServiceInfo args)
{
Join_Session = await LampStateConsumer.JoinSessionAsync(args, sender);
Consumer_Bulb = Join_Session.Consumer;
if (Join_Session.Status == AllJoynStatus.Ok)
{
LightBulbs.Add(Consumer_Bulb);
}
Consumer_Bulb.SessionMemberRemoved += Consumer_Bulb_SessionMemberRemoved;
}
In this case only the Watcher_Consumer_Added is fired and completed where as the the Watcher_Details_Added is fired but not completed.
How can I complete both the processes. Is the above method correct to implement multiple interfaces on the consumer?
P.S. : this is using the AllJoyn Studio extension for VS2015 running on Windows10

An additional BusAttachement is required for the second watcher. A single bus cannot be shared between two watchers.
This is the answer i received on MSDN forum.
The link to the same is here
AllJoyn Studio - Multiple Interface Implementation

Related

Single Observer created for every unique Symbol

I am working on a .NET Application which is rendering data from a source (say TCP) to excel using the Excel-DNA Library.
I have given example of LtpObserver which I have created by implementing IExcelObservable. I am creating the Observer using a Excel Function Call (Refer Code) --> "GetLtp".
'Data' referred here is containing a List of LtpObservers and Ltp value.
THE PROBLEM -
When I call the formula in Excel using a symbol say 'X', it creates the Observer (verified via Logging), and the data starts updating. Constructor of observer is called, as well as, callback is received on Subscribe() Method. But, when I call the same formula for 'X in another cell, no new Observer is created, neither a call on subscribe is received.
And upon deletion, of formula from just Cell#1, the Dispose is not called. But upon deleting from both Cell#1 and Cell#2 Dispose is called.
So is there just one observer for every unique symbol in the Excel Workbook? In that case does keeping a list of Observers and updating each of them on OnNext() makes sense? And what about the case when 2 or more formulas are used together in a single cell? How does this work Internally
CODE
class LtpObserver : IExcelObservable
{
private List<IExcelObserver> _observerList;
private string _symbol;
private Timer _timer;
public LtpObserver(string symbol)
{
Trace.TraceInformation("Constructor Called. New Ltp Observer Loaded for Symbol : " + symbol);
_symbol = symbol;
_observerList = new List<IExcelObserver>();
_timer = new Timer();
_timer.AutoReset = true;
_timer.Interval = FeedTimerConstant.ltpFrequency;
_timer.Elapsed += _timer_Elapsed;
}
void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (Data != null))
{
_timer.Stop();
Data.LtpObserver = _observerList;
timer_tick(Data.Ltp);
}
else
{
timer_tick(0);
}
}
public IDisposable Subscribe(IExcelObserver observer)
{
Trace.TraceInformation("LTP Subscription for : " + observer.ToString() + " Symbol : " + _symbol);
_observerList.Add(observer);
if (Data != null)
{
Data.LtpObserver = _observerList;
timer_tick(Data.Ltp);
}
else
{
timer_tick(0);
_timer.Start();
}
return new ActionDisposable(() => {
Trace.TraceInformation("Un Subscribed for LTP Price :" + _symbol);
_observerList.Remove(observer);
});
}
void timer_tick(object _now)
{
foreach (var obs in _observerList)
obs.OnNext(_now);
}
}
-----------------------------------------------------------------------------------------------------------
[ExcelFunction(Name = "GetLtp", IsVolatile = true)]
public static object GetLtp(string symbol)
{
if (String.IsNullOrEmpty(symbol))
{
return INVALID_SYMBOL;
}
return ExcelAsyncUtil.Observe("GetLtp", symbol, () => new LtpObserver(symbol)
);
}
-------------------------------------------------------------------------------------------------------------
public class Data {
public decimal Ltp { get; set; }
public List<IExcelObserver> LtpObserver { get; set; }
}
The behaviour you describe is by design. The first two parameters passed to ExcelAsyncUtil.Observe are normally a string with the function name and an object or array of objects that provide a unique identifier for the IObservable stream.
So the part you describe in "THE PROBLEM" is exactly how it is intended to work. For every unique symbol you have a stream of values, and you can use the same values in multiple places on the sheet without a problem - they will be listening to the same underlying stream. If you have multiple different symbols active, you have multiple streams that you update with whatever mechanism, using the OnNext() calls.
In your code you need not make provision for multiple IObservers that Subscribe to your IObservable. But this detail is specific to the way Excel-DNA will call your IObservable. Excel-DNA will only ever Subscribe once to your IObservable. However, if you wanted to use the same IObservable class in other contexts or in another application, this might not hold an you might get multiple Subscribe calls.
(It would also make more sense to rename LtpObserver to LtpObservable.)
You could add extra information to that list to create separate topics according to the calling cell. This code might be something like this:
(I've removed the IsVolatile=true as that doesn't make sense for a streaming function wrapper like this)
[ExcelFunction(Name = "GetLtp")]
public static object GetLtp(string symbol)
{
if (String.IsNullOrEmpty(symbol))
{
return INVALID_SYMBOL;
}
var callerReference = XlCall.Excel(XlCall.xlfCaller);
var identifiers = new object[] { symbol, callerReference };
return ExcelAsyncUtil.Observe("GetLtp", identifiers, () => new LtpObserver(symbol, callerReference)
);
}
But now again you have a unique LtpObserver for the combination of symbol and calling cell. And again each such IObservable will only be subscribed to once by Excel-DNA.
Internally this is implemented using Excel's RTD mechanism. Excel can associate one or more RTD topics with a cell. When the topic value changes, Excel will invalidate the relevant cells, and recalculate them. There is some optimisation inside Excel so that this scales well.

Unsure of type to use in an event subscription method

I was trying to create a general function, that should describe some threads to the windows event log to different internal methods. So i wrote:
void SubScribeToEventLogEvent(string EventLog,int EventID,string Source, Action named ="myMethod")
{
string query = "*[System/Level=8] and [System/EventID=" +EventID.ToString()+"]";
EventLogQuery subscriptionQuery = new EventLogQuery(EventLog, PathType.LogName, "*[System/Level=8]");
EventLogWatcher watcher = new EventLogWatcher(subscriptionQuery);
watcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(named);
watcher.Enabled = true;
}
Then I have a few functions triggered for specific events
private void myMethod(object obj,EventRecordWrittenEventArgs arg)
{
//do something
if (arg.EventRecord != null)
{
MessageBox.Show(arg.EventRecord.Id.ToString() + arg.EventRecord.FormatDescription());
Console.WriteLine("Received event {0} from the subscription.", arg.EventRecord.Id);
Console.WriteLine("Description: {0}", arg.EventRecord.FormatDescription());
}
else
{
Console.WriteLine("The event instance was null.");
}
}
So that in my main I could simply write
SubScribeToEventLogEvent(EventlogName,200,myMethod);
However it doesn't seam to work, I am coding in .net 4.0 and I believed that Action is a reserved method word for doing such things. But I get an error (red line already under named in the first line of the code):
SubScribeToEventLogEvent(string EventLog,int EventID,string Source, Action named ="myMethod")
apparently it cann't be assigned a string value (but what else?), and if I remove the string value its still not recognized in the Eventhandler function.

Storage Commitment with fo-dicom

I am trying to implement a storage commitment with FO-DICOM framework, but with no result. I am able to create the N-ACTION request. I am able to receive the N-ACTION response. But I don't know how to receive the EVENTREPORT. Anyone can help me and address me to the right way?
private DicomStatus _responseStatus;
public void SendRequestForCommitment(string scImageUid)
{
var client = new DicomClient();
var nAction = new DicomNActionRequest(DicomUID.StorageCommitmentPushModelSOPClass,
new UIDGenerator().PrivatelyDefinedSoapInstanceUid(), 1);
var ds = new DicomDataset();
nAction.Dataset = ds;
nAction.Dataset.Add(DicomTag.TransactionUID, new UIDGenerator().uid);
var sps = new DicomDataset();
nAction.Dataset.Add(new DicomSequence(DicomTag.ReferencedSOPSequence, sps));
sps.Add(DicomTag.ReferencedSOPClassUID, DicomUID.SecondaryCaptureImageStorage);
sps.Add(DicomTag.ReferencedSOPInstanceUID, scImageUid);
DicomNActionRequest.ResponseDelegate nActionResponseDelegate = NActionResponse;
nAction.OnResponseReceived = nActionResponseDelegate;
client.AddRequest(nAction);
client.Send("127.0.0.1", 105, false, "myAE", "DVTK_STRC_SCP");
}
private void NActionResponse(DicomNActionRequest request, DicomNActionResponse response)
{
_responseStatus = response.Status;
}
Disclaimer: I never used FO-DICOM. The code below is just a pseudo code and is NOT FO-DICOM syntax. I hope looking at pseudo code, you will able to figure out exact members (properties, methods, and events) in toolkit.
In your code, you are already building request dataset. Then, you are calling client.AddRequest(nAction); and then client.Send(.......);. I assume this will internally establish a connection, association and will send NAction request.
Then you have subscribed for private void NActionResponse(....) event. I assume this event is being fired and you are getting NAction Response.
Similarly, you should subscribe NEventReport event something (look for exact syntax in toolkit) like following:
private void NEventReportReceived(DicomNEventReport request, ......)
{
//Parse the request here.
//Check what files were archived and what were failed.
//Do your stuff accordingly.
//Send NEventReport response conveying the status.
client.SendReleaseRequest();
}
Subscribe another event to handle release response.
private void ReleaseResponseReceived(......)
{
//Close connection
}
As I said in other answer, your SCU should have ability to process NEventReport. You have added NAction to your client by writing line client.AddRequest(nAction);. Check the toolkit documentation to see if you also need to add similar for NEventReport. I strongly think this should not be needed; you just need to subscribe an event.

How to expose IObservable<T> properties without using Subject<T> backing field

In this answer to a question about Subject<T> Enigmativity mentioned:
as an aside, you should try to avoid using subjects at all. The
general rule is that if you're using a subject then you're doing
something wrong.
I often use subjects as backing fields for IObservable properties, which would have probably been .NET events in the days before Rx. e.g. instead of something like
public class Thing
{
public event EventHandler SomethingHappened;
private void DoSomething()
{
Blah();
SomethingHappened(this, EventArgs.Empty);
}
}
I might do
public class Thing
{
private readonly Subject<Unit> somethingHappened = new Subject<Unit>();
public IObservable<Unit> SomethingHappened
{
get { return somethingHappened; }
}
private void DoSomething()
{
Blah();
somethingHappened.OnNext(Unit.Default);
}
}
So, if I want to avoid using Subject what would be the correct way of doing this kind of thing? Or I should I stick to using .NET events in my interfaces, even when they'll be consumed by Rx code (so probably FromEventPattern)?
Also, a bit more details on why using Subject like this is a bad idea would be helpful.
Update: To make this question a bit more concrete, I'm talking about using Subject<T> as a way to get from non-Rx code (maybe you're working with some other legacy code) into the Rx world. So, something like:
class MyVolumeCallback : LegacyApiForSomeHardware
{
private readonly Subject<int> volumeChanged = new Subject<int>();
public IObservable<int> VolumeChanged
{
get
{
return volumeChanged.AsObservable();
}
}
protected override void UserChangedVolume(int newVolume)
{
volumeChanged.OnNext(newVolume);
}
}
Where, instead of using events, the LegacyApiForSomeHardware type makes you override virtual methods as a way of getting "this just happened" notifications.
For one thing, someone can cast the SomethingHappened back to an ISubject and feed things into it from the outside. At the very least, apply AsObservable to it in order to hide the subject-ness of the underlying object.
Also, subject broadcasting of callbacks doesn't do strictly more than a .NET event. For example, if one observer throws, the ones that are next in the chain won't be called.
static void D()
{
Action<int> a = null;
a += x =>
{
Console.WriteLine("1> " + x);
};
a += x =>
{
Console.WriteLine("2> " + x);
if (x == 42)
throw new Exception();
};
a += x =>
{
Console.WriteLine("3> " + x);
};
a(41);
try
{
a(42); // 2> throwing will prevent 3> from observing 42
}
catch { }
a(43);
}
static void S()
{
Subject<int> s = new Subject<int>();
s.Subscribe(x =>
{
Console.WriteLine("1> " + x);
});
s.Subscribe(x =>
{
Console.WriteLine("2> " + x);
if (x == 42)
throw new Exception();
});
s.Subscribe(x =>
{
Console.WriteLine("3> " + x);
});
s.OnNext(41);
try
{
s.OnNext(42); // 2> throwing will prevent 3> from observing 42
}
catch { }
s.OnNext(43);
}
In general, the caller is dead once an observer throws, unless you protect every On* call (but don't swallow exceptions arbitrarily, as shown above). This is the same for multicast delegates; exceptions will swing back at you.
Most of the time, you can achieve what you want to do without a subject, e.g. by using Observable.Create to construct a new sequence. Such sequences don't have an "observer list" that results from multiple subscriptions; each observer has its own "session" (the cold observable model), so an exception from an observer is nothing more than a suicide command in a confined area rather than blowing yourself up in the middle of a square.
Essentially, subjects are best used at the edges of the reactive query graph (for ingress streams that need to be addressable by another party that feeds in the data, though you could use regular .NET events for this and bridge them to Rx using FromEvent* methods) and for sharing subscriptions within a reactive query graph (using Publish, Replay, etc. which are Multicast calls in disguise, using a subject). One of the dangers of using subjects - which are very stateful due to their observer list and potential recording of messages - is to use them when trying to write a query operator using subjects. 99.999% of the time, such stories have a sad ending.
In an answer on the Rx forum, Dave Sexton (of Rxx), said as part an answer to something:
Subjects are the stateful components of Rx. They are useful for when
you need to create an event-like observable as a field or a local
variable.
Which is exactly what's happening with this question, he also wrote an in-depth follow up blog post on To Use Subject Or Not To Use Subject? which concludes with:
When should I use a subject?
When all of the following are true:
you don't have an observable or anything that can be converted into one.
you require a hot observable.
the scope of your observable is a type.
you don't need to define a similar event and no similar event already exists.
Why should I use a subject in that case?
Because you've got no choice!
So, answering the inner question of "details on why using Subject like this is a bad idea" - it's not a bad idea, this is one of the few places were using a Subject is the correct way to do things.
While I can't speak for Enigmativity directly, I imagine it's because it's very low-level, something you don't really need to use directly; everything that's offered by the Subject<T> class can be achieved by using the classes in the System.Reactive.Linq namespace.
Taking the example from the Subject<T> documentation:
Subject<string> mySubject = new Subject<string>();
//*** Create news feed #1 and subscribe mySubject to it ***//
NewsHeadlineFeed NewsFeed1 = new NewsHeadlineFeed("Headline News Feed #1");
NewsFeed1.HeadlineFeed.Subscribe(mySubject);
//*** Create news feed #2 and subscribe mySubject to it ***//
NewsHeadlineFeed NewsFeed2 = new NewsHeadlineFeed("Headline News Feed #2");
NewsFeed2.HeadlineFeed.Subscribe(mySubject);
This is easily achieved with the Merge extension method on the Observable class:
IObservable<string> feeds =
new NewsHeadlineFeed("Headline News Feed #1").HeadlineFeed.Merge(
new NewsHeadlineFeed("Headline News Feed #2").HeadlineFeed);
Which you can then subscribe to normally. Using Subject<T> just makes the code more complex. If you're going to use Subject<T> then you should be doing some very low-level processing of observables where the extension methods fail you.
One approach for classes which have simple one-off events, is to provide a ToObservable method which creates a meaningful cold observable based on an event.
This is more readable than using the Observable factory methods, and allows developers who don't use Rx to make use of the API.
public IObservable<T> ToObservable()
{
return Observable.Create<T>(observer =>
{
Action notifier = () =>
{
switch (Status)
{
case FutureStatus.Completed:
observer.OnNext(Value);
observer.OnCompleted();
break;
case FutureStatus.Cancelled:
observer.OnCompleted();
break;
case FutureStatus.Faulted:
observer.OnError(Exception);
break;
}
};
Resolve += notifier;
return () => Resolve -= notifier;
});
}

How to update textbox on GUI from another thread [duplicate]

This question already has answers here:
How do I update the GUI from another thread?
(47 answers)
Closed 5 years ago.
I'm new with C# and I'm trying to make a simple client server chat application.
I have RichTextBox on my client windows form and I am trying to update that control from server which is in another class. When I try to do it I get the error: "Cross-thread operation not valid: Control textBox1 accessed from a thread other than the thread it was created on".
Here the code of my Windows form:
private Topic topic;
public RichTextBox textbox1;
bool check = topic.addUser(textBoxNickname.Text, ref textbox1, ref listitems);
Topic class:
public class Topic : MarshalByRefObject
{
//Some code
public bool addUser(string user, ref RichTextBox textBox1, ref List<string> listBox1)
{
//here i am trying to update that control and where i get that exception
textBox1.Text += "Connected to server... \n";
}
So how to do that? How can I update the textbox control from another thread?
I'm trying to make some basic chat client/server application using .net remoting.
I want to make windows form client application and console server application as separate .exe files. Here im trying to call server function AddUser from client and i want to AddUser function update my GUI. Ive modified code as you suggested Jon but now instead of cross-thread exception i've got this exception ... "SerializationException: Type Topic in Assembly is not marked as serializable".
Ill post my whole code bellow, will try to keep it simple as possible.
Any suggestion is welcome. Many thanks.
Server:
namespace Test
{
[Serializable]
public class Topic : MarshalByRefObject
{
public bool AddUser(string user, RichTextBox textBox1, List<string> listBox1)
{
//Send to message only to the client connected
MethodInvoker action = delegate { textBox1.Text += "Connected to server... \n"; };
textBox1.BeginInvoke(action);
//...
return true;
}
public class TheServer
{
public static void Main()
{
int listeningChannel = 1099;
BinaryServerFormatterSinkProvider srvFormatter = new BinaryServerFormatterSinkProvider();
srvFormatter.TypeFilterLevel = TypeFilterLevel.Full;
BinaryClientFormatterSinkProvider clntFormatter = new BinaryClientFormatterSinkProvider();
IDictionary props = new Hashtable();
props["port"] = listeningChannel;
HttpChannel channel = new HttpChannel(props, clntFormatter, srvFormatter);
// Register the channel with the runtime
ChannelServices.RegisterChannel(channel, false);
// Expose the Calculator Object from this Server
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Topic),
"Topic.soap",
WellKnownObjectMode.Singleton);
// Keep the Server running until the user presses enter
Console.WriteLine("The Topic Server is up and running on port {0}", listeningChannel);
Console.WriteLine("Press enter to stop the server...");
Console.ReadLine();
}
}
}
}
Windows form client:
// Create and register a channel to communicate to the server
// The Client will use the port passed in as args to listen for callbacks
BinaryServerFormatterSinkProvider srvFormatter = new BinaryServerFormatterSinkProvider();
srvFormatter.TypeFilterLevel = TypeFilterLevel.Full;
BinaryClientFormatterSinkProvider clntFormatter = new BinaryClientFormatterSinkProvider();
IDictionary props = new Hashtable();
props["port"] = 0;
channel = new HttpChannel(props, clntFormatter, srvFormatter);
//channel = new HttpChannel(listeningChannel);
ChannelServices.RegisterChannel(channel, false);
// Create an instance on the remote server and call a method remotely
topic = (Topic)Activator.GetObject(typeof(Topic), // type to create
"http://localhost:1099/Topic.soap" // URI
);
private Topic topic;
public RichTextBox textbox1;
bool check = topic.addUser(textBoxNickname.Text,textBox1, listitems);
You need to either use BackgroundWorker, or Control.Invoke/BeginInvoke. Anonymous functions - either anonymous methods (C# 2.0) or lambda expressions (C# 3.0) make this easier than it was before.
In your case, you can change your code to:
public bool AddUser(string user, RichTextBox textBox1, List listBox1)
{
MethodInvoker action = delegate
{ textBox1.Text += "Connected to server... \n"; };
textBox1.BeginInvoke(action);
}
A few things to note:
To conform with .NET conventions, this should be called AddUser
You don't need to pass the textbox or listbox by reference. I suspect you don't quite understand what ref really means - see my article on parameter passing for more details.
The difference between Invoke and BeginInvoke is that BeginInvoke won't wait for the delegate to be called on the UI thread before it continues - so AddUser may return before the textbox has actually been updated. If you don't want that asynchronous behaviour, use Invoke.
In many samples (including some of mine!) you'll find people using Control.InvokeRequired to see whether they need to call Invoke/BeginInvoke. This is actually overkill in most cases - there's no real harm in calling Invoke/BeginInvoke even if you don't need to, and often the handler will only ever be called from a non-UI thread anyway. Omitting the check makes the code simpler.
You can also use BackgroundWorker as I mentioned before; this is particularly suited to progress bars etc, but in this case it's probably just as easy to keep your current model.
For more information on this and other threading topics, see my threading tutorial or Joe Albahari's one.
Use Invoke method
// Updates the textbox text.
private void UpdateText(string text)
{
// Set the textbox text.
yourTextBox.Text = text;
}
Now, create a delegate that has the same signature as the method that was previously defined:
public delegate void UpdateTextCallback(string text);
In your thread, you can call the Invoke method on yourTextBox, passing the delegate to call, as well as the parameters.
yourTextBox.Invoke(new UpdateTextCallback(this.UpdateText),
new object[]{”Text generated on non-UI thread.”});

Categories