/// <summary>Asynchronously loads the collection by executing a <see cref="Microsoft.OData.Client.DataServiceQuery{TElement}" />.Supported only by the WCF Data Services 5.0 client for Silverlight.</summary> /// <param name="query">The <see cref="Microsoft.OData.Client.DataServiceQuery{TElement}" /> that, when executed, returns the entities to load into the collection.</param> /// <exception cref="System.ArgumentException">When query is null or not a <see cref="Microsoft.OData.Client.DataServiceQuery{TElement}" />.</exception> /// <exception cref="System.InvalidOperationException">When a previous call to <see cref="Microsoft.OData.Client.DataServiceCollection{T}.LoadAsync(System.Linq.IQueryable{T})" /> is not yet complete.</exception> /// <remarks>This method uses the event-based async pattern. /// The method returns immediately without waiting for the query to complete. Then it calls the handler of the /// <see cref="LoadCompleted"/> event exactly once on the UI thread. The event will be raised regardless /// if the query succeeded or not. /// This class only support one asynchronous operation in flight.</remarks> public void LoadAsync(System.Linq.IQueryable <T> query) { Util.CheckArgumentNull(query, "query"); DataServiceQuery <T> dsq = query as DataServiceQuery <T>; if (dsq == null) { throw new ArgumentException(Strings.DataServiceCollection_LoadAsyncRequiresDataServiceQuery, nameof(query)); } if (this.ongoingAsyncOperation != null) { throw new InvalidOperationException(Strings.DataServiceCollection_MultipleLoadAsyncOperationsAtTheSameTime); } if (this.trackingOnLoad) { this.StartTracking( ((DataServiceQueryProvider)dsq.Provider).Context, null, this.entitySetName, this.entityChangedCallback, this.collectionChangedCallback); this.trackingOnLoad = false; } this.BeginLoadAsyncOperation( asyncCallback => dsq.BeginExecute(asyncCallback, null), asyncResult => { QueryOperationResponse <T> response = (QueryOperationResponse <T>)dsq.EndExecute(asyncResult); this.Load(response); return(response); }); }
private void ReadNotesCompleted(IAsyncResult result) { try { DataServiceQuery <Annotation> NotesQuery = result.AsyncState as DataServiceQuery <Annotation>; ObservableCollection <Annotation> Notes = new DataServiceCollection <Annotation>(NotesQuery.EndExecute(result)); if (Notes.Count > 0) { Annotation Note = Notes[0]; ThisNoteId = Note.AnnotationId.ToString(); byte[] encodedData = System.Convert.FromBase64String(Note.DocumentBody); MemoryStream str = new MemoryStream(encodedData); BitmapImage bmp = new BitmapImage(); bmp.SetSource(str); IMG_Image.Source = bmp; IMG_Image.Height = MainControl.Height; IMG_Image.Width = MainControl.Width; } else { IMG_Image.Source = null; } ReadConfiguration(); } catch (Exception ex) { throw ex; } }
private void OnQueryCompleted(IAsyncResult result) { // Get the original query object from the state cache. DataServiceQuery <Customer> query = (DataServiceQuery <Customer>)result.AsyncState; // Use the Dispatcher to ensure that the query returns in the UI thread. this.Dispatcher.BeginInvoke(new OperationResultCallback(delegate { try { // Instantiate the binding collection using the // results of the query execution. customerBinding = new DataServiceCollection <Customer>( query.EndExecute(result)); // Bind the collection to the root element of the UI. this.LayoutRoot.DataContext = customerBinding; } catch (DataServiceRequestException ex) { MessageBox.Show(ex.ToString()); } }), null); }
/// <summary> /// Called when [customer complete]. /// </summary> /// <param name="result">The result.</param> private void OnCustomerComplete(IAsyncResult result) { IEnumerable <CUSTOMER> cs = customerDsq.EndExecute(result); csl = new List <CUSTOMER>(cs); System.Diagnostics.Debug.WriteLine(csl[0].NAME); }
public async Task <IPagedCollection <TInterface> > ExecuteAsync <TSource, TInterface>(DataServiceQuery <TSource> inner) where TSource : TInterface { try { return(await Task.Factory.FromAsync( inner.BeginExecute, new Func <IAsyncResult, IPagedCollection <TInterface> >( r => new PagedCollection <TInterface, TSource>( this, (QueryOperationResponse <TSource>)inner.EndExecute(r))), TaskCreationOptions.None)); } catch (Exception ex) { var newException = ProcessException(ex); if (newException != null) { throw newException; } throw; } }
public void PostAndGetShouldReturnSameEntity(UniverseEntity entity) { var uri = new Uri(this.BaseAddress); const string entitySetName = "UniverseEntity"; this.ClearRepository(entitySetName); var ctx = WriterClient(uri, ODataProtocolVersion.V4); ctx.AddObject(entitySetName, entity); ctx.SaveChangesAsync().Wait(); // get collection of entities from repository ctx = ReaderClient(uri, ODataProtocolVersion.V4); DataServiceQuery <UniverseEntity> query = ctx.CreateQuery <UniverseEntity>(entitySetName); IAsyncResult asyncResult = query.BeginExecute(null, null); asyncResult.AsyncWaitHandle.WaitOne(); var entities = query.EndExecute(asyncResult); var beforeUpdate = entities.ToList().First(); AssertExtension.DeepEqual(entity, beforeUpdate); // clear repository this.ClearRepository(entitySetName); }
public void QueryHeadersViaExecuteMethod() { Uri baseUri = ctx.BaseUri; // Accessing headers via DataServiceContext.Execute<> method Uri requestUri = new Uri(baseUri.OriginalString + "/Customers('QUICK')"); var results = (QueryOperationResponse <northwindClient.Customers>)ctx.Execute <northwindClient.Customers>(requestUri); Utils.IsSuccessResponse(results, HttpStatusCode.OK); // assert that there is exactly one object results.Single <northwindClient.Customers>(); // Accessing headers via DataServiceContext.BeginExecute/EndExecute method IAsyncResult asyncResult = ctx.BeginExecute <northwindClient.Customers>(requestUri, null, null); results = (QueryOperationResponse <northwindClient.Customers>)ctx.EndExecute <northwindClient.Customers>(asyncResult); Utils.IsSuccessResponse(results, HttpStatusCode.OK); // assert that there is exactly one object results.Single <northwindClient.Customers>(); // Accessing headers via DataServiceQuery<>.Execute method DataServiceQuery <northwindClient.Customers> query = ctx.CreateQuery <northwindClient.Customers>("Customers"); results = (QueryOperationResponse <northwindClient.Customers>)query.Execute(); Utils.IsSuccessResponse(results, HttpStatusCode.OK); Assert.IsTrue(results.Count <northwindClient.Customers>() > 0, "expecting atleast one object"); // Accessing headers via DataServiceQuery<>.BeginExecute/EndExecute method asyncResult = query.BeginExecute(null, null); results = (QueryOperationResponse <northwindClient.Customers>)query.EndExecute(asyncResult); Utils.IsSuccessResponse(results, HttpStatusCode.OK); Assert.IsTrue(results.Count <northwindClient.Customers>() > 0, "expecting atleast one object"); }
protected async Task PostAndGetShouldReturnSameEntity(UniverseEntity entity) { var uri = new Uri(this.BaseAddress); const string entitySetName = "UniverseEntity"; await this.ClearRepositoryAsync(entitySetName); var ctx = WriterClient(uri, ODataProtocolVersion.V4); ctx.AddObject(entitySetName, entity); await ctx.SaveChangesAsync(); // get collection of entities from repository ctx = ReaderClient(uri, ODataProtocolVersion.V4); DataServiceQuery <UniverseEntity> query = ctx.CreateQuery <UniverseEntity>(entitySetName); var entities = await Task.Factory.FromAsync(query.BeginExecute(null, null), (asyncResult) => { return(query.EndExecute(asyncResult)); }); var beforeUpdate = entities.ToList().First(); AssertExtension.DeepEqual(entity, beforeUpdate); // clear repository await this.ClearRepositoryAsync(entitySetName); }
/// <summary> /// Callback method of the query to get CourseGrade records. /// </summary> /// <param name="result"></param> private void OnCourseGradeQueryComplete(IAsyncResult result) { Dispatcher.BeginInvoke(() => { DataServiceQuery <CourseGrade> query = result.AsyncState as DataServiceQuery <CourseGrade>; try { var returnedCourseGrade = query.EndExecute(result); if (returnedCourseGrade != null) { _collection = (from c in returnedCourseGrade.ToList() select new ScoreCardForSchoolLinqToSQL() { CourseGrade = c, Course = c.Course.Title, Grade = c.Grade, PersonName = string.Format("{0} {1}", c.Person.FirstName, c.Person.LastName) }).ToList(); this.mainDataGrid.ItemsSource = _collection; } } catch (DataServiceQueryException ex) { this.messageTextBlock.Text = string.Format("Error: {0} - {1}", ex.Response.StatusCode.ToString(), ex.Response.Error.Message); } }); }
void LoadMoreItems(uint count, int baseIndex) { BackgroundWorker worker = new BackgroundWorker(); //worker.RunWorkerAsync (); worker.DoWork += (o, ae) => { DataServiceQuery <Order> query = northwindEntity.Orders.Expand("Customer"); query = query.Skip <Order>(baseIndex).Take <Order>(50) as DataServiceQuery <Order>; IAsyncResult ar = query.BeginExecute(null, null); var items = query.EndExecute(ar); var list = items.ToList(); Android.OS.Handler mainHandler = new Android.OS.Handler(Android.OS.Looper.MainLooper); Java.Lang.Runnable myRunnable = new Java.Lang.Runnable(() => { GridSource.LoadItems(list); }); mainHandler.Post(myRunnable); }; worker.RunWorkerCompleted += (o, ae) => { IsBusy = false; }; IsBusy = true; worker.RunWorkerAsync(); }
/// <summary> /// Ons the resource complete. /// </summary> /// <param name="res">The resource.</param> private void onResComplete(IAsyncResult res) { IEnumerable <RESOURCE> resources = resourceDsq.EndExecute(res); RESOURCE resource = resources.FirstOrDefault(); resTypeDsq = (DataServiceQuery <RES_TYPE>)(ctx.RES_TYPE.Where(r => r.ID == resource.TYPE)); resTypeDsq.BeginExecute(onQueryComplete2, null); }
private static void EntitiesLoaded <T>(IAsyncResult result, Collection <T> entities) { DataServiceQuery <T> query = result.AsyncState as DataServiceQuery <T>; foreach (T entity in query.EndExecute(result)) { entities.Add(entity); } }
public static async Task <IEnumerable <TResult> > ExecuteAsync <TResult>(this DataServiceQuery <TResult> query) { var queryTask = Task.Factory.FromAsync <IEnumerable <TResult> >(query.BeginExecute(null, null), (asResult) => { var result = query.EndExecute(asResult).ToList(); return(result); }); return(await queryTask); }
private IEnumerable <Order> ProcessOrder(DataServiceQuery <Order> queryOrder) { IAsyncResult resultOrder = queryOrder.BeginExecute((res) => { Console.WriteLine(res); }, null); IEnumerable <Order> objOrder = queryOrder.EndExecute(resultOrder); return(objOrder); }
/// <summary> /// Extension method to perform sync/async version of DataServiceQuery.Execute dynamically /// </summary> /// <typeparam name="TElement">The element type of the results</typeparam> /// <param name="query">The query to execute</param> /// <param name="continuation">The asynchronous continuation</param> /// <param name="async">A value indicating whether or not to use async API</param> /// <param name="onCompletion">A callback for when the call completes</param> public static void Execute <TElement>(this DataServiceQuery <TElement> query, IAsyncContinuation continuation, bool async, Action <IEnumerable <TElement> > onCompletion) { ExceptionUtilities.CheckArgumentNotNull(query, "query"); AsyncHelpers.InvokeSyncOrAsyncMethodCall <IEnumerable <TElement> >( continuation, async, () => query.Execute(), c => query.BeginExecute(c, null), r => query.EndExecute(r), onCompletion); }
protected virtual void AsyncRemoveCallback(IAsyncResult asyncResult) { DataServiceQuery <Item> query = asyncResult.AsyncState as DataServiceQuery <Item>; if (query == null) { return; } Item items = query.EndExecute(asyncResult).First(); UIDispatcher.BeginInvoke(() => RemoveCallbackCore(items)); }
private void DisplayParts(IAsyncResult result) { Dispatcher.BeginInvoke(() => { DataServiceQuery <PartsItem> query = (DataServiceQuery <PartsItem>)result.AsyncState; var partResults = query.EndExecute(result); foreach (var part in partResults) { parts.Add(part); } }); }
// Handle the query callback. private void _onImageQueryComplete(IAsyncResult imageResults) { // Get the original query from the imageResults. DataServiceQuery <Bing.ImageResult> query = imageResults.AsyncState as DataServiceQuery <Bing.ImageResult>; var resultList = new List <string>(); foreach (var result in query.EndExecute(imageResults)) { resultList.Add(result.MediaUrl); } FindImageCompleted(this, resultList); }
protected virtual void AsyncGetItemCallback(IAsyncResult asyncResult) { DataServiceQuery <Item> query = asyncResult.AsyncState as DataServiceQuery <Item>; if (query == null) { return; } IEnumerable <Item> items = query.EndExecute(asyncResult); var en = items.GetEnumerator(); en.MoveNext(); UIDispatcher.BeginInvoke(() => GetItemCallbackCore(en.Current)); }
private void DisplaySuppliers(IAsyncResult result) { Deployment.Current.Dispatcher.BeginInvoke(() => { DataServiceQuery <SuppliersItem> query = (DataServiceQuery <SuppliersItem>)result.AsyncState; var partSuppliers = query.EndExecute(result); foreach (var partSupplier in partSuppliers) { CurrentPartSuppliers.Add(partSupplier); } }); }
/// <summary> /// Called when [pg complete]. /// </summary> /// <param name="result">The result.</param> private async void OnPGComplete(IAsyncResult result) { try { IEnumerable <PARENT_GUIDE> ps = pgDsq.EndExecute(result); pgs = new List <PARENT_GUIDE>(ps); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { pgComboBox.ItemsSource = pgs; pgComboBox.SelectedIndex = 0; }); } catch { } }
/// <summary> /// DataServiceQuery callback method to refresh the UI. /// </summary> /// <param name="result">Async operation result.</param> private async void OnCategoryComplete(IAsyncResult result) { try { IEnumerable <CATEGORY> cts = categoryDsq.EndExecute(result); categories = new List <CATEGORY>(cts); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { categoryComboBox.ItemsSource = categories; categoryComboBox.SelectedIndex = 0; }); } catch { ShowNetworkMessageDialog(); } }
private void DisplayLocations(IAsyncResult asyncResult) { Dispatcher.BeginInvoke( () => { DataServiceQuery <InventoryLocationsItem> query = (DataServiceQuery <InventoryLocationsItem>)asyncResult.AsyncState; //this delegate will execute when the results of the async query have returned var partLocations = query.EndExecute(asyncResult); foreach (var location in partLocations) { inventoryLocations.Add(location); } }); }
private void RetrieveLicense(IAsyncResult result) { //Retrieve the query that was DataServiceQuery <WebResource> results = result.AsyncState as DataServiceQuery <WebResource>; ObservableCollection <WebResource> Licenses = new DataServiceCollection <WebResource>(results.EndExecute(result)); if (Licenses.Count > 0) { try { MemoryStream LicenseStream = new MemoryStream(Convert.FromBase64String(Licenses[0].Content)); Aspose.Imaging.License Lic = new Imaging.License(); Lic.SetLicense(LicenseStream); } catch (Exception) { } } }
/// <summary> /// CourseGrade查询的回调方法。 /// </summary> /// <param name="result"></param> private void OnCourseGradeQueryComplete(IAsyncResult result) { Dispatcher.BeginInvoke(() => { DataServiceQuery<CourseGrade> query = result.AsyncState as DataServiceQuery<CourseGrade>; try { var returnedCourseGrade = query.EndExecute(result); if (returnedCourseGrade != null) { _collection = (from c in returnedCourseGrade.ToList() select new ScoreCardForSchoolLinqToEntities() { // 由于在服务器端有一个查询拦截器(如下),所以服务器端只能返回ID大于4000的Course数据 // [QueryInterceptor("Course")] // public Expression<Func<Course, bool>> QueryCourse() // { // // LINQ lambda expression to filter the course objects // return c => c.CourseID > 4000; // } CourseGrade = c, Course = c.Course == null ? "只有 Course ID>4000 才会被显示" : c.Course.Title, Grade = c.Grade, PersonName = string.Format("{0} {1}", c.Person.FirstName, c.Person.LastName) }).ToList(); this.mainDataGrid.ItemsSource = _collection; } } catch (DataServiceQueryException ex) { this.messageTextBlock.Text = string.Format("错误: {0} - {1}", ex.Response.StatusCode.ToString(), ex.Response.Error.Message); } }); }
// Handle the query callback. private void _onImageQueryComplete(IAsyncResult imageResults) { //_clientDone.Set(); // Get the original query from the imageResults. DataServiceQuery <Bing.ImageResult> query = imageResults.AsyncState as DataServiceQuery <Bing.ImageResult>; ChameleonAlbum webAlbum = new ChameleonAlbum(); try { foreach (var result in query.EndExecute(imageResults)) { webAlbum.Add(new WebPicture() { Guid = Guid.NewGuid(), SourceOrigin = SourceOrigin.Search, Name = result.Title, Path = result.MediaUrl, Width = (int)result.Width, Height = (int)result.Height, FileSize = (long)result.FileSize, ContentType = result.ContentType, Thumbnail = new WebPicture() { Path = result.Thumbnail.MediaUrl, Width = (int)result.Thumbnail.Width, Height = (int)result.Thumbnail.Height, FileSize = (long)result.Thumbnail.FileSize, ContentType = result.Thumbnail.ContentType } }); } } catch (Exception e) { if (e.InnerException.Message == "NotFound") { //검색된 데이터 없음. } } FindCompleted(this, webAlbum); }
/// <summary> /// Called when [shared note complete]. /// </summary> /// <param name="result">The result.</param> private async void OnSharedNoteComplete(IAsyncResult result) { try { sharedNotesList = sharedNoteDsq.EndExecute(result).ToList(); foreach (var n in sharedNotesList) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { allSharedNotesStackPanel.Children.Add(GenerateSharedNoteItem(n.ID, n.TITLE, n.CONTENT, n.CUSTOMER_NAME, n.DATE, n.LESSON_NUMBER, n.CUSTOMER_ID.Value)); }); } } catch { ShowMessageDialog("Network connection error27!"); } }
private void ReadConfiguration(IAsyncResult result) { DataServiceQuery <aspose_configuration> results = result.AsyncState as DataServiceQuery <aspose_configuration>; ObservableCollection <aspose_configuration> Configs = new DataServiceCollection <aspose_configuration>(results.EndExecute(result)); foreach (aspose_configuration Config in Configs) { if (Config.aspose_name.ToLower() == "SaveToEntity".ToLower()) { SaveToEntity = Config.aspose_Value; } if (Config.aspose_name.ToLower() == "LicenseWebResourceName".ToLower()) { LicenseWebResourceName = Config.aspose_Value; } } EnableLicense(); }
/// <summary> /// Called when [comment complete]. /// </summary> /// <param name="result">The result.</param> private async void OnCommentComplete(IAsyncResult result) { try { IEnumerable <COMMENT_DET> coms = commentDsq.EndExecute(result); allComments = new List <COMMENT_DET>(coms); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { foreach (COMMENT_DET c in allComments) { StackPanel newComment = GenerateACommentBox(c.USERNAME, c.TITLE, Convert.ToInt32(c.RATE), c.CONTENT); commentsStackPanel.Children.Add(newComment); } }); } catch { ShowMessageDialog(); } }
// Handle the query callback. private void _onNewsQueryComplete(IAsyncResult newsResults) { var resultList = new List <ArticleSearchResult>(); try { DataServiceQuery <Bing.WebResult> query = newsResults.AsyncState as DataServiceQuery <Bing.WebResult>; foreach (var result in query.EndExecute(newsResults).Take(resultNumber)) { DateTime now = DateTime.Now; if (result.Url.Contains(now.Year.ToString())) { /*Deployment.Current.Dispatcher.BeginInvoke(() => * { * MessageBox.Show(result.Url); * });*/ resultList.Add(new ArticleSearchResult(result.Title, result.DisplayUrl, result.Url)); } } } catch (DataServiceQueryException) { } if (resultList.Count != 0) { Deployment.Current.Dispatcher.BeginInvoke(() => { arPageViewModel.addArticlesToView(resultList); }); } else { Deployment.Current.Dispatcher.BeginInvoke(() => { //MessageBox.Show("No result"); arPageViewModel.tryNextNearbyLocation(); }); } }