Periodical Agent - Await for searchasync on Appointments - windows-phone

I am performing a
appts.SearchAsync
on
var appts = new Appointments();
In a "Periodical Agent".
The problem is that in the periodical agent. The searchasync and it's nested functions never finish before
NotifyComplete();
}
Could you please help me on how to wait for all the calls that are being done in here:
static void Appointments_SearchCompleted(object sender, AppointmentsSearchEventArgs e)
{
try
{
UpdatePrimaryTile(e.Results
.Where(a => a.Subject != null)
.OrderBy(a => a.StartTime)
.ToList());
}
catch (System.Exception)
{
}
}
public static void UpdatePrimaryTile(List<Appointment> calendarItems)
{
...........
..........
}
Before "NotifyComplete" is being called.
Thank you!
Jakub

You can use the await keyword to wait for an async operation to complete.
await appts.SearchAsync
Another option - have a loop that sleeps until the async call completes.
appts.SearchAsync
while (true)
{
if (searchCompleted)
{
break;
}
else
{
Thread.Sleep(100);
}
}
then in the event handler...
void Appointments_SearchCompleted(object sender, AppointmentsSearchEventArgs e)
{
searchCompleted = true;
// Other logic
}

Related

Trouble with getting thread to sleep - Android

I'm pretty new to java (first post) and trying to make a loop that does the following:
Post to a textview, Wait, Post to another textview, Wait, Clear both (by posting " " to each one), Sleep, Repeat loop.
The loop send the messages to the que almost instantaneously, without doing the sleep part inbetween
Runnable postRight = new Runnable() {
public void run() {
right_side.setText("post right");
}
};
Runnable postLeft = new Runnable() {
public void run() {
left_side.setText("post left");
}
};
Runnable clear = new Runnable() {
public void run() {
left_side.setText(" ");
right_side.setText(" ");
}
};
/////////////////////////////////////////////////////////////
while (i < 3) {
Log.i(TAG, "Entered while");
long Timer = SystemClock.uptimeMillis();
handler.postAtTime(postLeft, Timer + 1000);
Log.i(TAG, "post left");
handler.postAtTime(postRight, Timer + 2000);
Log.i(TAG, "postright");
handler.postAtTime(clear, Timer + 3000);
Log.i(TAG, "clear");
Thread t = new Thread() {
public void run() {
try {
Thread.sleep(4000);
runOnUiThread(new Runnable() {
public void run() {
Log.i(TAG, "inside runnable");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
i++;
}
the thread t is sleeping, but it's its own thread, so the main thread just keeps on going after initiating and the main thread never sleeps

ContentSharingModality ContentAdded event is not getting triggered (Lync silverlight application)

My ultimate aim is to transfer a file from one Lync client to another. I have following code.
First of all I have following 2 events registered
1.
((Modality)_conversation.Modalities[ModalityTypes.ContentSharing]).ModalityStateChanged += Modality_ModalityStateChanged;
2.
((ContentSharingModality)_conversation.Modalities[ModalityTypes.ContentSharing]).ContentAdded += _sharingModality_ContentAdded;
code for those event is
void _sharingModality_ContentAdded(object sender, ContentCollectionChangedEventArgs e)
{
MessageBox.Show("content added\n"+e.Item);
}
void Modality_ModalityStateChanged(object sender, ModalityStateChangedEventArgs e)
{
if (e.NewState == ModalityState.Connected)
{
textBox1.Text += "\nconnected";
send_file();
}
if (e.NewState == ModalityState.Connecting)
{
textBox1.Text += "\nconnecting";
}
}
Then I have a method which creates a file in isolated storage named "abc.txt".
Next there is a code which connects the content sharing modality.
private void button4_Click(object sender, RoutedEventArgs e)
{
if (_conversation.State == ConversationState.Active)
{
((Modality)_conversation.Modalities[ModalityTypes.ContentSharing])
.BeginConnect((ar) =>{((Modality)_conversation.Modalities[ModalityTypes.ContentSharing]).EndConnect(ar); }
, null);
else { MessageBox.Show("conversation not active"); }
}
After this there is 'send_file' method which actually upload the file. (this method id previously called when modality state changes to 'connected' but there (I think) conversation changes to multiparty and method returns false at 'canInvoke' statement. So Im calling it again and this time it succeeds. It is as below
void send_file()
{
if (((ContentSharingModality)_conversation.Modalities[ModalityTypes.ContentSharing]).State == ModalityState.Connected)
{
try
{
if (((ContentSharingModality)_conversation.Modalities[ModalityTypes.ContentSharing]).CanInvoke(ModalityAction.CreateShareableNativeFileOnlyContent))
{
ContentSharingModality contentSharingModality = (ContentSharingModality)_conversation.Modalities[ModalityTypes.ContentSharing];
contentSharingModality.BeginCreateContentFromFile(ShareableContentType.NativeFile, "samplefile.txt", fileNameFromIsolatedStorage, true,
(ar) =>
{
ShareableContent sContent = contentSharingModality.EndCreateContentFromFile(ar);
//_NativeFileNameAndPath = string.Empty;
sContent.Upload();
}
, null);
MessageBox.Show("upload done");
}
else { MessageBox.Show("u cannot invoke"); }
}
catch (Exception e1) { MessageBox.Show(e1.Message); }
}
else { MessageBox.Show("modality inactive"); }
}
Finally this is all I'm trying to do. The same code will lie on both sender & receiver machines. I'm new to lync development and very confused about what is going wrong. Please help. Thanks!

Improve software responsiveness when slider is manipulated in windows phone

I have a slider in my windows phone 7.1 project. When manipulated, this slider fires an event which starts a background worker to performs several trigonometric operations.
If I move the cursor on the slider, I have a certain delay in the response although I have implement background worker cancelAsync method in manipulationstarted event, I would like more responsiveness, how can I achieve this?
Code:
private void sliderCosinus_ManipulationStarted(object sender,ManipulationStartedEventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync(); // Cancel the asynchronous operation.
}
}
private void sldCosinus_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
try
{
Value = Convert.ToInt32(sldCosinus.Value) * 10;
}
catch
{
// errore message here
}
finally
{
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
}
else
{
Dispatcher.BeginInvoke(() => app.IsEffectApplied=TrigonometricTrans()
// TrigonomtriecTrans calculate sin and cosinus for every pixel in image
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// progress bar here
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
//this.tbProgress.Text = "Canceled!";
}
else if (!(e.Error == null))
{
//this.tbProgress.Text = ("Error: " + e.Error.Message);
}
else
{
DoubleBufferToScreen();
}
}

Call MessageDialog from Property Changed handler Store App

I'm trying to call a MessageDialog out of a PropertyChanged Handler. The first call is always successful, but when the Dialog gets called a second time, I get an UnauthorizedAccessException.
I've tried to wrap the call in a Dispatcher, but I got the same behavior.
Here's the code (snippet of MainPage.xaml.cs):
void PropertyChanged(object sender, PropertyChangedEventArgs e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
showMessage("Message", "Title");
});
}
async void showMessage(String message, String title)
{
MessageDialog dialog = new MessageDialog(message, title);
await dialog.ShowAsync();
}
Could anybody please help me with this issue?
I think your problem is that multiple property changes will cause multiple calls to display the dialog. You should only ever display one dialog at a time:
bool _isShown = false;
async void showMessage(String message, String title)
{
if (_isShown == false)
{
_isShown = true;
MessageDialog dialog = new MessageDialog(message, title);
await dialog.ShowAsync();
_isShown = false;
}
}

return result from async operation in mvvm

I have a viewModel named CarsList with main property
public ObservableCollection<Car> Cars
{
get
{
if (_cars.Count == 0)
{
IsBusy = true;
_ws.GetCarsCompleted += new EventHandler<GetCarsCompletedEventArgs>(GetCarsCompleted);
_ws.GetCarsAsync(_app.HandlerId);
}
return _cars;
}
set
{
if (_cars != value)
{
if (_cars != null)
{
Unsubscribe(_cars);
}
_cars = value;
if (_cars != null)
{
Subscribe(_cars);
}
RaisePropertyChanged("Cars");
}
}
}
private void GetCarsCompleted(object sender, GetCarsCompletedEventArgs e)
{
//_cars = e.Result;
IsBusy = false;
}
When view gets _cars and the list is empty I must wait to get collection of cars from wcf service, and there is a problem because it is async operation.
Or maybe if list is empty I should return null, and fire async operation, and in asynccompleted set _cars to result from the wcf service?
I can only guess that you are trying to set up a view binding and property change notification. If I am right I would change you code as follows:
public void GetCars(Int32 handlerId)
{
_ws.GetCarsCompleted += new EventHandler<GetCarsCompletedEventArgs>GetCarsCompleted);
IsBusy = true;
_ws.GetCarsAsync(handlerId);
}
public ObservableCollection<Car> Cars
{
get
{
return _cars;
}
set
{
if (_cars != value)
{
_cars = value;
RaisePropertyChanged("Cars");
}
}
private void GetCarsCompleted(object sender, GetCarsCompletedEventArgs e)
{
_ws.GetCarsCompleted -= new EventHandler<GetCarsCompletedEventArgs>GetCarsCompleted);
IsBusy = false;
if (e.Error != null)
{
//Error handler
}
else
{
Cars = e.Result;
}
}
And then the view binding (in the case of a DataGrid) would look something like this..
<DataGrid IsReadOnly="True"
ItemsSource="{Binding Cars}"
.........
........./>