Exception while using ExecuteQuery() in Silverlight client object model - silverlight

I have been developing a Silverlight user control for SharePoint using the Client Object model. Here is the coding
InitializeComponent();
ctx = ClientContext.Current;
Web web = ctx.Web;
ctx.Load(web, oweb => oweb.Title);
ctx.Load(web, oweb => oweb.Lists);
ctx.ExecuteQuery();
I heard tht SIlverlight supports both ExecuteQuery() and ExecuteQueryAsync() methods. But I'm getting an Exception message like this "he method or property that is called may block the UI thread and it is not allowed. Please use background thread to invoke the method or property, for example, using System.Threading.ThreadPool.QueueUserWorkItem method to invoke the method or property."
Can anyone tell me where am I going wrong and how to use ExecuteQuery() method ?? Thank you.

I might be off base here, but as I understand it, ExecuteQuery() requires you to create a thread so you aren't calling a stop to the UI thread when you invoke the method. The reason you use ExecuteQueryAsync is exactly that: ExecuteQueryAsync performs the operation on a seperate thread, then you just call back in to the UI thread using the dispather:
ctx.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);
...
private void onQuerySucceeded(object sender, ClientRequestSucceededEventArgs args)
{
this.Dispatcher.BeginInvoke((Action)(() =>
{
doStuff();
}));
}

Related

Rx reactive extensions Observeondispatcher unit test error: The current thread has no Dispatcher associated with it

I want to unit test a view model which contains a registration like:
public SampleViewModel(IUnityContainer container)
{
...
Observable.FromEventPattern<PropertyChangedEventArgs>(gridViewModel, "PropertyChanged")
.**ObserveOnDispatcher()**
.Subscribe(_ => this.Update());
...
}
When I run the unit test it tells me that "The current thread has no Dispatcher associated with it." when reaching this code.
One solution would be to use a Scheduler but I don't want to modify the Viewmodel.
Is there a solution to make the unit test pass this statement without getting an error?
I would suggest that you provide you own IScheduler implementation to ObserveOn(IScheduler) instead of using the ObserveOnDispatcher() operator. I have used techniques for loading a DispatcherFrame or a Dispatcher but the problem is that you are still using a Dispatcher. Eventually I found that you just "fall off the cliff" especially once you have long running background threads involved. Following the guidelines of "No threading in Unit tests" just dont let the dispatcher get near your ViewModels! Your Unit tests will run much, much faster.
A far superior way to deal with this is to inject an interface that gives access to your Dispatcher Scheduler (via the IScheduler interface). This allows you to substitute in an implementation that exposes the TestScheduler. You now can control time in your unit test. You can control and validate which actions are marshalled to each scheduler.
This is a really old (pre-Rx) post on 'Unit' testing WPF with Dispatcher calls from early 2009. It seemed like a good idea at the time.
https://leecampbell.com/2009/02/17/responsive-wpf-user-interfaces-part-5/
More information on Testing with Rx and the TestScheduler is found in my other site on Rx
http://introtorx.com/Content/v1.0.10621.0/16_TestingRx.html
This works for me.
When setting up the unit test I create an application to simulate the environment for my VM:
static Application App;
static void BeforeTestRun()
{
var waitForApplicationRun = new ManualResetEventSlim();
Task.Run(() =>
{
App = new Application();
App.Startup += (s, e) => { waitForApplicationRun.Set(); };
App.Run();
});
waitForApplicationRun.Wait();
}
and this is how I use it to instanciate the view model.
App.Dispatcher.Invoke(() => { this.viewModel = new ViewModel(); });
To properly unit test your viewmodel, you really need to be able to supply all of its dependencies. In this case, your viewmodel has a dependency upon the dispatcher. Making your viewmodel take a IScheduler dependency is the ideal way. But if you really don't want to do that, then try looking at this duplicate question: Unit test IObservable<T> with ObserveOnDispatcher
I found a solution for avoiding the error, simply from Unit Test code instantiate the ViewModel by using a dispatcher like:
SampleViewModel sampleViewModel;
var dispatcher = Application.Current != null ? Application.Current.Dispatcher : Dispatcher.CurrentDispatcher;
dispatcher.Invoke((Action)(() => sampleViewModel = new SampleViewModel(this.container);
That's all and seems to work without modifying current code, maybe there are also better solutions.

Replacing methods that use backgroundworker to async / tpl (.NET 4.0)

My questions are many. Since I saw. NET 4.5, I was very impressed. Unfortunately all my projects are .NET 4.0 and I am not thinking about migrating. So I would like to simplify my code.
Currently, most of my code that usually take enough time to freeze the screen, I do the following:
BackgroundWorker bd = new BackgroundWorker();
bd.DoWork += (a, r) =>
{
r.Result = ProcessMethod(r.Argument);
};
bd.RunWorkerCompleted += (a, r) =>
{
UpdateView(r.Result);
};
bd.RunWorkerAsync(args);
Honestly, I'm tired of it. And that becomes a big problem when there is a logic complex user interaction.
I wonder, how to simplify this logic? (Remember that I'm with. Net 4.0) I noticed a few things by google, but not found anything easy to implement and suitable for my needs.
I thought this solution below:
var foo = args as Foo;
var result = AsyncHelper.CustomInvoke<Foo>(ProcessMethod, foo);
UpdateView(result);
public static class AsyncHelper
{
public static T CustomInvoke<T>(Func<T, T> func, T param) where T : class
{
T result = null;
DispatcherFrame frame = new DispatcherFrame();
Task.Factory.StartNew(() =>
{
result = func(param);
frame.Continue = false;
});
Dispatcher.PushFrame(frame);
return result;
}
}
I am not sure about the impact is on manipulating the dispatcher frame.
But I know That it would work very well, for example, I could use it in all the events of controls without bothering to freeze the screen.
My knowledge about generic types, covariance, contravariance is limited, maybe this code can be improved.
I thought of other things using Task.Factory.StartNew and Dispatcher.Invoke, but nothing that seems interesting and simple to use. Can anyone give me some light?
You should just use the Task Parallel Library (TPL). The key is specifying the TaskScheduler for the current SynchronizationContext for any continuations in which you update the UI. For example:
Task.Factory.StartNew(() =>
{
return ProcessMethod(yourArgument);
})
.ContinueWith(antecedent =>
{
UpdateView(antecedent.Result);
},
TaskScheduler.FromCurrentSynchronizationContext());
Aside from some exception handling when accessing the antecedent's Result property, that's all there is too it. By using FromCurrentSynchronizationContext() the ambient SynchronizationContext that comes from WPF (i.e. the DispatcherSynchronizationContext) will be used to execute the continuation. This is the same as calling Dispatcher.[Begin]Invoke, but you are completely abstracted from it.
If you wanted to get even "cleaner", if you control ProcessMethod I would actually rewrite that to return a Task and let it own how that gets spun up (can still use StartNew internally). That way you abstract the caller from the async execution decisions that ProcessMethod might want to make on its own and instead they only have to worry about chaining on a continuation to wait for the result.
UPDATE 5/22/2013
It should be noted that with the advent of .NET 4.5 and the async language support in C# this prescribed technique is outdated and you can simply rely on those features to execute a specific task using await Task.Run and then execution after that will take place on the Dispatcher thread again automagically. So something like this:
MyResultType processingResult = await Task.Run(() =>
{
return ProcessMethod(yourArgument);
});
UpdateView(processingResult);
How about encapsulating the code that is always the same in a reusable component? You could create a Freezable which implements ICommand, exposes a property of Type DoWorkEventHandler and a Result property. On ICommand.Executed, it would create a BackgroundWorker and wire up the delegates for DoWork and Completed, using the value of the DoWorkEventHandler as event handler, and handling Completed in a way that it sets its own Result property to the result returned in the event.
You'd configure the component in XAML, using a converter to bind the DoWorkEventHandler property to a method on the ViewModel (I assume you've got one), and bind your View to the component's Result property, so it gets updated automatically when Result does a change notification.
The advantages of this solution are: it is reusable, and it works with XAML only, so no more glue code in your ViewModel just for handling BackgroundWorkers. If you don't need your background process to report progress, it could even be unaware that it runs on a background thread, so you can decide in the XAML whether you want to call a method synchronously or asynchronously.
A few months have passed, but could this help you?
Using async/await without .NET Framework 4.5

How to implement a background worker thread queue

I'm trying to implement my first application using the MVVM pattern. I've manged to get most things working, but now I'm facing a problem with the following (IMHO pretty common) scenario:
Pressing a Button (View) shall invoke a Method (Model). Using a ICommand (ViewModel) this is pretty easy. But what to do if a time consuming operation has to be executed?
My current solution required me to implement a WorkQueue class containing WorkQueueItems. The WorkQueue has a Thread associated with it which executes the WorkQueueItems. Each WorkQueueItem has a Name, a Status and a Progress which is updated during execution.
Each Window has its own WorkQueue - visualized as StatusBar.
My problem: How can a ViewModel find the appropriate WorkQueue? Do I have to pass the WorkQueue to each ViewModel I create (this would be really be annoying)? Or are there other mechanism I could use?
I'm not really familiar with RoutedCommands - tough the basic concept seems to go into this direction. What'd love to see is a solution where I can bind a WorkQueueItem to a Command/Event which then bubbles up to the containing Window where it is added to the Window's WorkQueue.
I also considered making WorkQueue a Singleton - but this only works if I only have one Window at a time.
With the later .Net Frameworks (4.0+) and WPF you can utilize the System.Threading.Tasks library to provide a lot of this work under the hood.
If say your Command on your needs to update a property on your View Model, but it has to wait for the information, you simply start a task to perform the IO:
this.FindDataCommand = new RelayCommand<string>(
/* ICommand.Execute */
value =>
{
Task.Factory
.StartNew<IEnumerable<Foo>>(() => FindData(value))
.ContinueWith(
task =>
{
this.foundData.Clear();
this.foundData.AddRange(task.Result);
},
TaskScheduler.FromCurrentSynchronizationContext());
},
/* ICommand.CanExecute */
value => !String.IsNullOrWhitespace(value));
Breaking this down into manageable parts, we're starting a new task which calls some method IEnumerable<Foo> FindData(string). This is the plain old boring synchronous code you've always written. Likely it already exists on your view model!
Next we tell the framework to start a new task when that one finishes using ContinueWith, but to do it on the WPF Dispatcher instead. This allows you to avoid the hassles of cross-thread problems with UI elements.
You can extend this for monitoring with a helper class:
public class TaskManager
{
private static ConcurrentDictionary<Dispatcher, TaskManager> _map
= new ConcurrentDictionary<Dispatcher, TaskManager>();
public ObservableCollection<WorkItem> Running
{
get;
private set;
}
public TaskManager()
{
this.Running = new ObservableCollection<WorkItem>();
}
public static TaskManager Get(Dispatcher dispatcher)
{
return _map.GetOrAdd(dispatcher, new TaskManager());
}
// ...
Using this class in XAML would be along the lines of adding its instance to your Window's ViewModel:
public TaskManager CurrentTaskManager
{
get { return TaskManager.Get(Dispatcher.CurrentDispatcher); }
}
// <StatusBarItem Content="{Binding CurrentTaskManager.Running.Count}" />
You would then add a method to your TaskManager to handle the adding of tasks to and from the Running collection:
public Task<TResult> StartNew<TResult>(Func<TResult> work)
{
var task = Task.Factory
.StartNew<TResult>(work);
// build our view model
var workItem = new WorkItem(task);
this.Running.Add(workItem);
// Pass the result back using ContinueWith
return task.ContinueWith(
t => { this.Running.Remove(workItem); return t.Result; },
TaskScheduler.FromCurrentSynchronizationContext());
}
Now we simply change our FindDataCommand implementation:
TaskManager.Get(Dispatcher.CurrentDispatcher)
.StartNew<IEnumerable<Foo>>(() => FindData(value))
.ContinueWith(
task =>
{
this.foundData.Clear();
this.foundData.AddRange(task.Result);
},
TaskScheduler.FromCurrentSynchronizationContext());
The WorkItem class could expose the properties on the Task class to the UI, or it could be extended to encapsulate a CancellationToken to support cancellation in the future.
I'm not sure I got the question right, but I feel that using buil in Dispatcher would solve your problem and you do not need implementing WorkQueue manually since Dispatcher implements such a queue for you and able dispatching "worker items" to the UI/any thred using predefined set of priorities. You can execute an operation either synchronously or asynchronously using Dispatcher.Invoke() or Dispatcher.BeginInvoke()
Useful links:
MSDN Magazine: WPF Threads, Build More Responsive Apps With The Dispatcher

How do I access the UI thread for my WCF subscriber?

I am currently developing a WCF Publish Subscribe service. The subscriber is a winform app. As the subscriber needs to implement the callback method for the service, which in my case is the PostReceived() method, and the publisher has the PublishPost() method.
For the PostReceived() method for my winform, it is unable to access the UI thread of my winform. The subscribe method is done on my main method. How do I program my PostReceived() method in such a way that it is able to access the labels and such of my mainForm?
EDIT
what I have tried so far is calling the mainForm object from my program.cs but it crashes when i run all 3 , stating the error that it is unable to access the UI thread.
EDIT 2
I have tried using the following code but there is an error for it.
mainForm b;
public void PostReceived(string postSampleData)
{
b.BeginInvoke((MethodInvoker)delegate()
{
b.lblSearch.Text = "lakjslkaja";
});
After running the code, there is an error of
Object reference not set to an instance of an object.
Any idea how to fix it?
Your PostReceived method should be something like this
void PostReceived()
{
yourform.BeginInvoke((MethodInvoker)delegate()
{
yourform.button.Text = "new label";
//More stuff here
});
}
This will guarantee that all the stuff after BeginInvoke is invoked in the UI thread.

AppDomain.GetData method not accessible?

I am developing a Silverlight 3 application and I would like to delegate all unexpected error handling in a single instance of a class I have named ErrorHandler. This class has one method named HandleApplicationException, plus a couple of other methods to handle more specialized errors.
In my application I am using Unity for dependency injection, but since I want the error handling object to be available even when the Unity container is not yet set up, I register the object as AppDomain global data in the App class constructor, this way:
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
AppDomain.CurrentDomain.SetData("ErrorHandler", new ErrorHandler());
InitializeComponent();
}
And in case of unhandled exception, I retrieve the error handler object and use it this way:
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
e.Handled = true;
var errorHandler = AppDomain.CurrentDomain.GetData("ErrorHandler") as ErrorHandler;
Debug.Assert(errorHandler != null, "No ErrorHandler registered.");
errorHandler.HandleApplicationException(e.ExceptionObject);
}
The problem is that the AppDomain.GetData method in the Application_UnhandledException method is throwing a MethodAccessException. I don't understand why, as I am just invoking a public method on the AppDomain class. I have used a similar approach in other applications and it worked fine (anyway these were not Silverlight applications).
So, what's going on? Am I doing something wrong?
Ok, I got it. From MSDN documentation:
This member has a
SecurityCriticalAttribute attribute,
which restricts it to internal use by
the .NET Framework for Silverlight
class library. Application code that
uses this member throws a
MethodAccessException.
I have resorted to storing the error handler in a public property in the App class, then I access it using ((App)Application.Current).ErrorHandler. I don't like doing things this way but I suppose it is ok in this special case.
Why can't you just use a static instance of ErrorHandler? I.e. have something like ErrorHandler.Current?
It looks like you're trying to manually construct a poor man's IoC framework to be honest.
Consider doing some research on Unity/Ninject and see for yourself why strongly-typed decoupling is better.

Resources