I am a C# newbie trying to implement SignalR in my Xamarin IOS app.
My code is quite simple:
_connection = new Microsoft.AspNet.SignalR.Client.Hubs.HubConnection (Common.signalRAddress);
feedHub = _connection.CreateHubProxy ("feedHub");
_connection.Received += data => { OnReceiveData (data); };
_connection.Start ();
my question is how can I remove my delegate?
Is it enough to write?
_connection.Received -= data => { OnReceiveData (data); };
Any help would be really appreciated.
You're using a hub, why not use the built in on/off for method invocations?
aka:
var doSomething = feeHub.On<int>("doSomething", val => {
// Do something with int val
});
Then to remove it you can do:
doSomething.Dispose();
If you truly want to listen to ALL data that flows through the hub then using Received is the correct approach and #Dracanus' answer will work.
I might be wrong, but if you do that it won't actually unsubscribe the event.
It didn't in a little test app I wrote anyways.
Instead create a function such as
void Connection_Recieved(string obj)
{
}
and do connection.Recieved += Connection_Recieved;
and connection.Recieved -= Connection_Recieved;
I don't think anonymous event functions are the way to go here :)
I am assuming, looking at your code sample you could just do,
connection.Recieved += OnReceiveData;
connection.Recieved -= OnReceiveData;
Related
I am porting some kind of code from Visual Studio to Delphi 10.
Wondering how we should translate the following construct:
public event PreviewReadyDelegate PreviewReady
{
add { Scheduler.AddOrRemoveEvent(() => { _previewReady += value; }); }
remove { Scheduler.AddOrRemoveEvent(() => { _previewReady -= value; }); }
}
Help appreciated.
C# events are multicast delegates. There is no equivalent construct in the Delphi language. You would need to implement your own multicast mechanism or use an existing one from a third party library, for instance that found in spring4d.
I am looking to implement async coding for some web services.
I came across a tutorial and tried to follow it and implement it however one specific section I am having trouble with.
My example
public void CalculatePricingAsync(QuoteInput obj)
{
AsyncManager.OutstandingOperations.Increment();
var apiService = new ApiService();
ApiService.CalculatedPricingCompleted += (sender, e) =>
{
AsyncManager.Parameters["Pricing"] = e.Value;
AsyncManager.OutstandingOperations.Decrement();
};
ApiService.CalculatedPricing(obj);
}
public JsonResult CalculatePricingCompleted(string[] pricing)
{
var jr = new JsonResult { Data = new { pricing } };
return jr;
}
The following line taken from the first method above does not exist in the ApiService class. Can someone explain what this expression is doing and what it means. Do I just create a method of this name in that ApiService class and leave it blank, does it somehow work with the second method. I am little unclear what its doing and where the method should be declared and what exactly should be in it.
ApiService.CalculatedPricingCompleted += (sender, e) =>
{
AsyncManager.Parameters["Pricing"] = e.Value;
AsyncManager.OutstandingOperations.Decrement();
};
this > (CalculatedPricingCompleted) in the line above is showing red in visual studio, it is clearly looking to be defined somewhere.
CalculatedPricingCompleted is a delegated method inside the ApiService. You need to look into the service class and add it. Having said this, I highly recommend using async / await for asynchronous operations in .NET. If you are on .NET 4.0+ there is no excuse not to use it.
So I'm currently working on a Skype bot thing, I wish it could automatically accept contact request so I don't have to do them manually, any idea how?
And while I was researching, I found this
ichat.AcceptAdd();
Any idea what does that do?
I don't know if I understood what you want to accomplish..
Do you want to accept contact requests automatically? Really? Do you like being target for hackers, spammers, etc? :)
Anyway, if that's what you want to do, you can subscribe to the UserAuthorizationRequestReceived event:
var events = (_ISkypeEvents_Event) _skype;
events.UserAuthorizationRequestReceived += UserAuthorizationRequestReceived;
try
{
_skype.Attach(8);
}
catch(COMException ce)
{
RaiseErrorEvent("Unable to attach to skype.", ce);
}
private void UserAuthorizationRequestReceived(SKYPE4COMLib.User puser)
{
if (do some user check here?? )
{
puser.IsAuthorized = true;
}
}
Hope this helps.
I have a Windows Phone 7 application that is using Silverlight with C#. This application has a method that fires off multiple web service requests. At another point in my code, I have some code that looks like the following:
myProgressBar.Visibility = Visibility.Visible;
while (AreWebServiceCallsDone() == false)
{
// Need "waiting" code here
}
// Proceed
How do I make my UI "wait" a small amount of time, without locking up the UI, and then check again to see if my web service calls are done?
Thank you!
The answer is to not make the UI wait at all but to "go with the (asynchronous) flow", as it were.
Ultimately, the async stuff in C# 5 will solve this particular problem, but there's no timeline for it's release for the desktop CLR let alone Silverlight or WP7.
I'd personally recommend looking into Microsoft.Phone.Reactive, which is the WP7 version of the Reactive Extensions (Rx) and ships with the SDK. It's a pretty big subject that takes a fair amount of time to get your head around, but can really simplify how you deal with asynchronous scenarios.
Assuming each of your web services return different types of data, I would:
Wrap each web service call in an IObservable1
Use Do to "peek" at the message and perform your side effects (like assigning the value locally)
Use Select to "normalize" the types so that they are all of the same type (required for the next step)
Use ForkJoin to execute each of the requests in parallel and to handle when each has completed
1 Creating an IObservable for your request really depends on how asynchronous pattern you are using. Assuming you're using WebClient, here's an extension method that creates an Observable from DownloadStringAsync as a sample (it may look complex but it's just handling errors and cancellation):
public static class ObservableWebClient
{
public static IObservable<string> DownloadStringObservable(
this WebClient webClient, Uri uri)
{
return Observable.Create(observer =>
{
var disposable = new CompositeDisposable();
var completedObservable = Observable.FromEvent<
DownloadStringCompletedEventHandler,
DownloadStringCompletedEventArgs
>(
h => new DownloadStringCompletedEventHandler(h),
h => webClient.DownloadStringCompleted += h,
h => webClient.DownloadStringCompleted h= h
);
disposable.Add(completedObservable
.SelectMany(ev =>
{
return (ev.EventArgs.Error != null)
? Observable.Throw<string>(ev.EventArgs.Error)
: Observable.Return(ev.EventArgs.Result);
})
.Subscribe(observer));
disposable.Add(Disposable.Create(
() => webClient.CancelAsync()));
return disposable;
});
}
}
You can then use it like so:
Note that I've skipped the Do + "normalizing" steps because my data types are all the same (String). As such, I can subscribe to them all as an array (it's a subtlety of how ForkJoin works, if you were wondering)
var webClientA = new WebClient();
var webClientB = new WebClient();
var webClientC = new WebClient();
Observable.ForkJoin(
webClientA.DownloadStringObservable(uriA),
webClientB.DownloadStringObservable(uriB),
webClientC.DownloadStringObservable(uriC),
)
.ObserveOnDispatcher()
.Subscribe(dataArray =>
{
// All three have completed
this.DataA = dataArray[0];
this.DataB = dataArray[1];
this.DataC = dataArray[2];
});
You should be using an async call back method and handle the progress bar's visibility on the call back event.
By using a while, you are making the UI wait for the thread to be executed.
I used this method in my blog post here: http://www.infopoint.com/News-Events/EntryId/29/Building-a-WP7-RSS-reader-Part-1-Basics.aspx
I want to use the status method but i dont understand how it works. Could someone show me an example of use please?
EventHandler < SvnStatusEventArgs > statusHandler = new EventHandler<SvnStatusEventArgs>(void(object, SvnStatusEventArgs) target);
client.Status(path, statusHandler);
Well, it'll work exactly like the svn status command : http://svnbook.red-bean.com/en/1.0/re26.html
You'll get the list of files pumped to the EventHandler:
using(SvnClient client = /* set up a client */ ){
EventHandler<SvnStatusEventArgs> statusHandler = new EventHandler<SvnStatusEventArgs>(HandleStatusEvent);
client.Status(#"c:\foo\some-working-copy", statusHandler);
}
...
void HandleStatusEvent (object sender, SvnStatusEventArgs args)
{
switch(args.LocalContentStatus){
case SvnStatus.Added: // Handle appropriately
break;
}
// review other properties of 'args'
}
Or if you don't mind inline delegates:
using(SvnClient client = new SvnClient())
{
client.Status(path,
delegate(object sender, SvnStatusEventArgs e)
{
if (e.LocalContentStatus == SvnStatus.Added)
Console.WriteLine("Added {0}", e.FullPath);
});
}
Note that the delegate versions of the SharpSvn functions are always a (tiny) bit faster than the revisions returns a collection as this method allows marshalling the least amount of information to the Managed world. You can use Svn*EventArgs.Detach() to marshall everything anyway. (This is what the .GetXXX() functions do internally)
The inline delegate version worked for me but the EventHandler<T> version didn't work until I set the type to EventHandler<SvnStatusEventArgs>.