public async Task <IActionResult> OnPostAsync(string id) { _context.Credentials = CredentialCache.DefaultNetworkCredentials; if (id == null) { return(NotFound()); } var contracts = _context.Contract; DataServiceQuery <Contract> query = contracts; TaskFactory <IEnumerable <Contract> > taskFactory = new TaskFactory <IEnumerable <Contract> >(); var kontract = await taskFactory.FromAsync(query.BeginExecute(null, null), iar => query.EndExecute(iar)); Contract = kontract.SingleOrDefault(m => m.Contract_No == id); //_context.AttachTo("Contracts", Contract); //_context.AddLink(Contract, "Contract_No", Contract); _context.DeleteObject(Contract); _context.BeginSaveChanges(adoSave_RLMember, Contract); return(RedirectToPage("./Index")); }
private TableCommand <ResultSegment <TElement>, IEnumerable <TElement> > GenerateExecuteCommand(TableContinuationToken continuationToken, TableRequestOptions requestOptions) { DataServiceQuery <TElement> localQuery = this.Query; // Continuation localQuery = TableUtilities.ApplyContinuationToQuery <TElement>(continuationToken, localQuery); if (requestOptions.ServerTimeout.HasValue) { localQuery = localQuery.AddQueryOption("timeout", Convert.ToString(requestOptions.ServerTimeout.Value.TotalSeconds, CultureInfo.InvariantCulture)); } TableCommand <ResultSegment <TElement>, IEnumerable <TElement> > cmd = new TableCommand <ResultSegment <TElement>, IEnumerable <TElement> >(); cmd.ExecuteFunc = localQuery.Execute; cmd.Begin = (callback, state) => localQuery.BeginExecute(callback, state); cmd.End = localQuery.EndExecute; cmd.ParseResponse = this.ParseTableQueryResponse; cmd.ParseDataServiceError = StorageExtendedErrorInformation.ReadDataServiceResponseFromStream; cmd.Context = this.Context; requestOptions.ApplyToStorageCommand(cmd); return(cmd); }
/// <summary> /// </summary> /// <param name="Query">Bing search query Sample Values : xbox</param> /// <param name="Options">Specifies options for this request for all Sources. Valid values are: DisableLocationDetection, EnableHighlighting. Sample Values : EnableHighlighting</param> /// <param name="Market">Market. Note: Not all Sources support all markets. Sample Values : en-US</param> /// <param name="Adult">Adult setting is used for filtering sexually explicit content Sample Values : Moderate</param> /// <param name="Latitude">Latitude Sample Values : 47.603450</param> /// <param name="Longitude">Longitude Sample Values : -122.329696</param> /// <param name="ImageFilters">Array of strings that filter the response the API sends based on size, aspect, color, style, face or any combination thereof. Valid values are: Size:Small, Size:Medium, Size:Large, Size:Width:[Width], Size:Height:[Height], Aspect:Square, Aspect:Wide, Aspect:Tall, Color:Color, Color:Monochrome, Style:Photo, Style:Graphics, Face:Face, Face:Portrait, Face:Other. Sample Values : Size:Small+Aspect:Square</param> public DataServiceQuery <ImageResult> Image(String Query, String Options, String Market, String Adult, Double?Latitude, Double?Longitude, String ImageFilters) { if ((Query == null)) { throw new ArgumentNullException("Query", "Query value cannot be null"); } DataServiceQuery <ImageResult> query = base.CreateQuery <ImageResult>("Image"); query = query.AddQueryOption("Query", string.Concat("\'", Uri.EscapeDataString(Query), "\'")); if ((Options != null)) { query = query.AddQueryOption("Options", string.Concat("\'", Uri.EscapeDataString(Options), "\'")); } if ((Market != null)) { query = query.AddQueryOption("Market", string.Concat("\'", Uri.EscapeDataString(Market), "\'")); } if ((Adult != null)) { query = query.AddQueryOption("Adult", string.Concat("\'", Uri.EscapeDataString(Adult), "\'")); } if (((Latitude != null))) { query = query.AddQueryOption("Latitude", Latitude.Value); } if (((Longitude != null))) { query = query.AddQueryOption("Longitude", Longitude.Value); } if ((ImageFilters != null)) { query = query.AddQueryOption("ImageFilters", string.Concat("\'", Uri.EscapeDataString(ImageFilters), "\'")); } return(query); }
public override bool RoleExists(string roleName) { SecUtility.CheckParameter(ref roleName, true, true, true, MaxTableRoleNameLength, "rolename"); try { TableServiceContext svc = CreateDataServiceContext(); DataServiceQuery <RoleRow> queryObj = svc.CreateQuery <RoleRow>(_tableName); var query = (from role in queryObj where role.PartitionKey == SecUtility.CombineToKey(_applicationName, string.Empty) && role.RowKey == SecUtility.Escape(roleName) select role).AsTableServiceQuery(); try { // this query addresses exactly one result // we thus should get an exception if there is no element return(query.Execute().Any()); } catch (InvalidOperationException e) { if (e.InnerException is DataServiceClientException && (e.InnerException as DataServiceClientException).StatusCode == (int)HttpStatusCode.NotFound) { return(false); } else { throw; } } } catch (InvalidOperationException e) { throw new ProviderException("Error while accessing the data store.", e); } }
async Task <IList <Order> > LoadMoreItems(CancellationToken c, uint count, int baseIndex) { IList <Order> list = null; IsBusy = true; await Task.Run(new Action(() => { DataServiceQuery <Order> query = northwindEntity.Orders.Expand("Customer"); query = query.Skip <Order>(baseIndex).Take <Order>(50) as DataServiceQuery <Order>; try { IAsyncResult ar = query.BeginExecute(null, null); var items = query.EndExecute(ar); list = items.ToList(); } catch (Exception) { } })); IsBusy = false; return(list); }
public virtual int Count(string where, object[] args = null) { int result; Filter(ref where, ref args); if (!String.IsNullOrEmpty(where)) { if (args != null) { result = Query().Where(where, args).Count(); } else { result = Query().Where(where).Count(); } } else { result = DataServiceQuery.Count(); } return(result); }
public void BasesDontMatchFail() { var context = this.CreateWrappedContext <DefaultContainer>(); DataServiceQuery customQuery = context.CreateQuery <Customer>("BasesDontMatchFail"); //Path should remap to the customers set var expectedServiceUrl = "http://potato:9090/FailMeService/"; var expectedRequestUrl = "http://potato:9090/DontFailMeService/Customer"; try { customQuery.Execute(); Assert.True(false, "Different service bases between service uri and request uri should fail"); } catch (DataServiceQueryException ex) { //No inner exception found Assert.NotNull(ex.InnerException); //Unexpected inner exception type Assert.IsType <DataServiceClientException>(ex.InnerException); StringResourceUtil.VerifyODataLibString(ClientExceptionUtil.ExtractServerErrorMessage(ex), "UriQueryPathParser_RequestUriDoesNotHaveTheCorrectBaseUri", true, expectedRequestUrl, expectedServiceUrl); } }
/// <summary> /// Populate this collection with another collection of items /// </summary> /// <param name="items">The items to populate this collection with</param> private void InternalLoadCollection(IEnumerable <T> items) { Debug.Assert(items != null, "items != null"); #if !PORTABLELIB // For SDP, we must execute the Query implicitly DataServiceQuery <T> query = items as DataServiceQuery <T>; if (query != null) { items = query.Execute() as QueryOperationResponse <T>; } #else Debug.Assert(!(items is DataServiceQuery), "SL Client using DSQ as items...should have been caught by ValidateIteratorParameter."); #endif foreach (T item in items) { // if this is too slow, consider hashing the set // or just use LoadProperties if (!this.Contains(item)) { this.Add(item); } } QueryOperationResponse <T> response = items as QueryOperationResponse <T>; if (response != null) { // this should never be throwing (since we've enumerated already)! // Note: Inner collection's nextPartLinkUri is set by the materializer this.continuation = response.GetContinuation(); } else { this.continuation = null; } }
public static T CreateEntity <T>(DataServiceContext ctx, string entitySetName, EntityStates state) where T : class, new() { DataServiceQuery <T> query = ctx.CreateQuery <T>(entitySetName).AddQueryOption("$top", 1); return(CreateEntity <T>(ctx, entitySetName, state, query)); }
/// <summary> /// Creates a query which retrieves all elements in a table. /// </summary> /// <typeparam name="T">The element type of the table.</typeparam> /// <param name="table">The table to query.</param> /// <returns>The query of all elements.</returns> private IQueryable <T> CreateQueryForAllElements <T>(DataServiceQuery <T> table) { return(from entity in table select entity); }
protected override IQueryable <UserEvent> Selector(DataServiceQuery <UserEvent> userEvents, Searcher searcher) => userEvents .Expand(userEvent => userEvent.User) .Expand(userEvent => userEvent.Event) .Where(userEvent => userEvent.User.Id == Guid.Parse(Id));
// the username to match can be in a format that varies between providers // for this implementation, a syntax similar to the one used in the SQL provider is applied // "user%" will return all users in a role that start with the string "user" // the % sign can only appear at the end of the usernameToMatch parameter // because the current version of the table storage service does not support StartsWith in LINQ queries, // calling this function can cause significant network trafic when '%' is used in the usernameToMach // parameter public override string[] FindUsersInRole(string roleName, string usernameToMatch) { SecUtility.CheckParameter(ref roleName, true, true, true, MaxTableRoleNameLength, "rolename"); SecUtility.CheckParameter(ref usernameToMatch, true, true, false, Constants.MaxTableUsernameLength, "usernameToMatch"); bool startswith = false; if (usernameToMatch.Contains('%')) { if (usernameToMatch.IndexOf('%') != usernameToMatch.Length - 1) { throw new ArgumentException("The TableStorageRoleProvider only supports search strings that contain '%' as the last character!"); } usernameToMatch = usernameToMatch.Substring(0, usernameToMatch.Length - 1); startswith = true; } try { TableStorageDataServiceContext svc = CreateDataServiceContext(); DataServiceQuery <RoleRow> queryObj = svc.CreateQuery <RoleRow>(_tableName); IEnumerable <RoleRow> query; if (startswith && string.IsNullOrEmpty(usernameToMatch)) { // get all users in the role query = from userRole in queryObj where userRole.PartitionKey.CompareTo(SecUtility.EscapedFirst(_applicationName)) >= 0 && userRole.PartitionKey.CompareTo(SecUtility.NextComparisonString(SecUtility.EscapedFirst(_applicationName))) < 0 && userRole.RowKey == SecUtility.Escape(roleName) select userRole; } else if (startswith) { // get all users in the role that start with the specified string (we cannot restrict the query more because StartsWith is not supported) // we cannot include the username to search for in the key, because the key might e escaped query = from userRole in queryObj where userRole.PartitionKey.CompareTo(SecUtility.EscapedFirst(_applicationName)) >= 0 && userRole.PartitionKey.CompareTo(SecUtility.NextComparisonString(SecUtility.EscapedFirst(_applicationName))) < 0 && userRole.RowKey == SecUtility.Escape(roleName) && (userRole.UserName.CompareTo(usernameToMatch) >= 0 || userRole.UserName == string.Empty) select userRole; } else { // get a specific user query = from userRole in queryObj where (userRole.PartitionKey == SecUtility.CombineToKey(_applicationName, usernameToMatch) || userRole.PartitionKey == SecUtility.CombineToKey(_applicationName, string.Empty)) && userRole.RowKey == SecUtility.Escape(roleName) select userRole; } TableStorageDataServiceQuery <RoleRow> q = new TableStorageDataServiceQuery <RoleRow>(query as DataServiceQuery <RoleRow>, _tableRetry); IEnumerable <RoleRow> userRows = q.ExecuteAllWithRetries(); if (userRows == null) { throw new ProviderException("The role does not exist!"); } List <RoleRow> l = new List <RoleRow>(userRows); if (l.Count == 0) { // the role does not exist throw new ProviderException("The role does not exist!"); } RoleRow role; if (IsStaleRole(l, out role)) { throw new ProviderException("The role does not exist!"); } List <string> ret = new List <string>(); foreach (RoleRow row in l) { if (row != role) { if (startswith && !string.IsNullOrEmpty(usernameToMatch) && !row.UserName.StartsWith(usernameToMatch, StringComparison.Ordinal)) { continue; } ret.Add(row.UserName); } } return(ret.ToArray()); } catch (InvalidOperationException e) { throw new ProviderException("Error while accessing the data store.", e); } }
/// <summary> /// Select a colleciton of items from the data source /// </summary> /// <returns>Collection of Item</returns> public IEnumerable <TQuery> ExecuteQuery <TQuery>(IQueryable <TQuery> query) { DataServiceQuery <TQuery> service = query as DataServiceQuery <TQuery>; return(service.Execute()); }
/// <summary> /// Helper extension method to stand in for DataServiceQuery.Execute in Silverlight. Always throws. /// </summary> /// <typeparam name="TElement">The element type</typeparam> /// <param name="query">The query</param> /// <returns>Always throws</returns> private static IEnumerable <TElement> Execute <TElement>(this DataServiceQuery <TElement> query) { throw new TaupoInvalidOperationException("Sync API not supported in Silverlight"); }
/// <summary> /// Gets the lessons by course identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="onComplete">The on complete.</param> public void GetLessonsByCourseId(int id, OnQueryComplete onComplete) { lessonDsq = (DataServiceQuery <LESSON>)(from les in ctx.LESSON where les.COURSE_ID == id select les); this.onUQC = onComplete; lessonDsq.BeginExecute(onQueryComplete2, null); }
public void NamedStreams_NestedQuery_2() { // projecting out collection of collection properties - both narrow type and anonymous type { // Querying url of the nested type - doing this makes the entity non-tracking, but populated the link property DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4); context.EnableAtom = true; context.Format.UseAtom(); DataServiceQuery <EntityWithNamedStreams1> q = (DataServiceQuery <EntityWithNamedStreams1>) from s in context.CreateQuery <EntityWithNamedStreams1>("MySet1") select new EntityWithNamedStreams1 { ID = s.ID, Stream1 = s.Stream1, Collection = (from c in s.Collection select new EntityWithNamedStreams2() { ID = c.ID, ColStream = c.ColStream, Collection1 = (from c1 in c.Collection1 select new EntityWithNamedStreams1() { ID = c1.ID, RefStream1 = c1.RefStream1 }).ToList() }).ToList() }; Assert.AreEqual(request.ServiceRoot.AbsoluteUri + "/MySet1?$expand=Collection($select=ID),Collection($select=ColStream),Collection($expand=Collection1($select=ID)),Collection($expand=Collection1($select=RefStream1))&$select=ID,Stream1", q.ToString(), "make sure the right uri is produced by the linq translator"); var response = (QueryOperationResponse <EntityWithNamedStreams1>)q.Execute(); DataServiceQueryContinuation <EntityWithNamedStreams2> continuation = null; foreach (var o in response) { Assert.IsNotNull(o.Stream1.EditLink, "Stream1 should not be null"); Assert.AreEqual(o.Stream1.EditLink, context.GetReadStreamUri(o, "Stream1"), "the stream url for Stream1 must be populated correctly"); foreach (var c in o.Collection) { Assert.IsNotNull(c.ColStream.EditLink, "ColStream should not be null"); Assert.AreEqual(c.ColStream.EditLink, context.GetReadStreamUri(c, "ColStream"), "the url for the nested collection entity should match - Level 0"); foreach (var c1 in c.Collection1) { Assert.IsNotNull(c1.RefStream1.EditLink, "RefStream1 should not be null"); Assert.AreEqual(c1.RefStream1.EditLink, context.GetReadStreamUri(c1, "RefStream1"), "the url for the nested collection entity should match - Level 1"); } } // Make sure you get the continuation token for the collection and try and get the next page continuation = response.GetContinuation(o.Collection); } Assert.AreEqual(context.Entities.Count, 3, "there should be 3 entities tracked by the context"); Assert.AreEqual(context.Entities[0].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet1(1)", "top level entity must be tracked"); Assert.AreEqual(context.Entities[1].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet3('ABCDE')", "top level entity must be tracked"); Assert.AreEqual(context.Entities[2].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet2(3)", "the nested entity must be tracked"); Assert.IsNotNull(continuation, "since SDP is turned on, we should get the continuation token"); // Get the next page and make sure we get the right entity and the link is populated. foreach (var entity in context.Execute(continuation)) { Assert.IsNotNull(entity.ColStream.EditLink, "ColStream should not be null"); Assert.AreEqual(entity.ColStream.EditLink, context.GetReadStreamUri(entity, "ColStream"), "the url for the nested collection entity should match - Level 1"); foreach (var c1 in entity.Collection1) { Assert.IsNotNull(c1.RefStream1.EditLink, "RefStream1 should not be null"); Assert.AreEqual(c1.RefStream1.EditLink, context.GetReadStreamUri(c1, "RefStream1"), "the url for the nested collection entity should match - Level 1"); } } Assert.AreEqual(context.Entities.Count, 4, "there should be 4 entities tracked by the context"); } { // Querying url of the nested type - doing this makes the entity non-tracking, but populated the link property DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4); context.EnableAtom = true; context.Format.UseAtom(); var q = from s in context.CreateQuery <EntityWithNamedStreams1>("MySet1") select new { ID = s.ID, Stream1Url = s.Stream1, Collection = (from c in s.Collection select new { Name = c.Name, Stream1Url = c.ColStream, Collection1 = (from c1 in c.Collection1 select new { ID = c1.ID, Stream1Url = c1.RefStream1 }) }) }; Assert.AreEqual(request.ServiceRoot.AbsoluteUri + "/MySet1?$expand=Collection($select=Name),Collection($select=ColStream),Collection($expand=Collection1($select=ID)),Collection($expand=Collection1($select=RefStream1))&$select=ID,Stream1", q.ToString(), "make sure the right uri is produced by the linq translator"); foreach (var o in q) { Assert.AreEqual(o.Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet1(1)/Stream1", "the stream url for Stream1 must be populated correctly"); Assert.AreEqual(o.Collection.First().Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet3('ABCDE')/ColStream", "the stream url of the collection stream must be populated correctly - index 0"); Assert.AreEqual(o.Collection.First().Collection1.Single().Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet2(3)/RefStream1", "the stream url of the collection stream must be populated correctly - index 0 - index 0"); } Assert.AreEqual(context.Entities.Count, 0, "there should be no entities tracked by the context"); } }
public DataServiceQueryWrapper(IDataServiceContext context, DataServiceQuery query) : this(context, query, typeof(T)) { }
/// <summary> /// Gets the note by customer identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="onComplete">The on complete.</param> public void GetNoteByCustomerID(int id, OnQueryComplete onComplete) { noteDsq = (DataServiceQuery <NOTE>)(ctx.NOTE.Where(n => n.CUSTOMER_ID == id)); this.onUQC = onComplete; noteDsq.BeginExecute(onQueryComplete2, null); }
/// <summary> /// Asynchronously executes an <see cref="T:System.Data.Services.Client.DataServiceQuery`1"/> and loads results into the <see cref="T:System.Data.Services.Client.DataServiceCollection`1"/>. /// </summary> /// <typeparam name="T">Entity type of the <see cref="T:System.Data.Services.Client.DataServiceCollection`1"/> instance.</typeparam> /// <param name="bindingCollection">The <see cref="T:System.Data.Services.Client.DataServiceCollection`1"/> instance on which this extension method is enabled.</param> /// <param name="query">Query that when executed loads entities into the collection.</param> /// <returns>A <see cref="T:System.Threading.Tasks.Task`1"/> that, when completed, returns a <see cref="T:System.Data.Services.Client.LoadCompletedEventArgs"/>.</returns> public static async Task <LoadCompletedEventArgs> LoadAsync <T>(DataServiceCollection <T> bindingCollection, DataServiceQuery <T> query) { var tcs = new TaskCompletionSource <LoadCompletedEventArgs>(); EventHandler <LoadCompletedEventArgs> handler = delegate(object o, LoadCompletedEventArgs e) { if (e.Error != null) { tcs.TrySetException(e.Error); } else if (e.Cancelled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(e); } }; bindingCollection.LoadCompleted += handler; bindingCollection.LoadAsync(query); LoadCompletedEventArgs eventArgs = await tcs.Task; bindingCollection.LoadCompleted -= handler; return(eventArgs); }
/// <summary> /// Gets the note by lesson identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="onComplete">The on complete.</param> public void GetNoteByLessonId(int id, OnQueryComplete onComplete) { noteDsq = (DataServiceQuery <NOTE>)(from note in ctx.NOTE where note.LESSON_ID == id select note); this.onUQC = onComplete; noteDsq.BeginExecute(onQueryComplete2, null); }
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { SecUtility.CheckParameter(ref roleName, true, true, true, MaxTableRoleNameLength, "rolename"); try { TableStorageDataServiceContext svc = CreateDataServiceContext(); DataServiceQuery <RoleRow> queryObj = svc.CreateQuery <RoleRow>(_tableName); IEnumerable <RoleRow> query = from userRole in queryObj where userRole.PartitionKey.CompareTo(SecUtility.EscapedFirst(_applicationName)) >= 0 && userRole.PartitionKey.CompareTo(SecUtility.NextComparisonString(SecUtility.EscapedFirst(_applicationName))) < 0 && userRole.RowKey == SecUtility.Escape(roleName) select userRole; TableStorageDataServiceQuery <RoleRow> q = new TableStorageDataServiceQuery <RoleRow>(query as DataServiceQuery <RoleRow>, _tableRetry); IEnumerable <RoleRow> userRows = q.ExecuteAllWithRetries(); if (userRows == null) { return(false); } List <RoleRow> l = new List <RoleRow>(userRows); if (l.Count == 0) { // the role does not exist return(false); } RoleRow role; if (IsStaleRole(l, out role)) { return(false); } if (l.Count > 1 && throwOnPopulatedRole) { throw new ProviderException("Cannot delete populated role."); } svc.DeleteObject(role); svc.SaveChangesWithRetries(); // lets try to remove all remaining elements in the role foreach (RoleRow row in l) { if (row != role) { try { svc.DeleteObject(row); svc.SaveChangesWithRetries(); } catch (InvalidOperationException ex) { HttpStatusCode status; if (TableStorageHelpers.EvaluateException(ex, out status) && (status == HttpStatusCode.NoContent || status == HttpStatusCode.NotFound)) { // this element already was already deleted by another process or during a failed retry // this is not a fatal error; continue deleting elements Log.Write(EventKind.Warning, string.Format(CultureInfo.InstalledUICulture, "The user {0} does not exist in the role {1}.", row.UserName, row.RoleName)); } else { throw new ProviderException(string.Format(CultureInfo.InstalledUICulture, "Error deleting user {0} from role {1}.", row.UserName, row.RoleName)); } } } } return(true); } catch (InvalidOperationException e) { throw new ProviderException("Error while accessing the data store.", e); } }
/// <summary> /// Gets the resource by identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="onComplete">The on complete.</param> public void GetResourceByID(int id, OnQueryComplete onComplete) { resourceDsq = (DataServiceQuery <RESOURCE>)(ctx.RESOURCE.Where(r => r.ID == id)); this.onUQC = onComplete; resourceDsq.BeginExecute(onQueryComplete2, null); }
public ReadOnlyQueryableSet(DataServiceQuery inner, DataServiceContextWrapper context) : base(inner, context) { }
/// <summary> /// Gets the note by identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="onComplete">The on complete.</param> public void GetNoteByID(int id, OnQueryComplete onComplete) { noteDsq = (DataServiceQuery <NOTE>)(ctx.NOTE.Where(r => r.ID == id)); this.onUQC = onComplete; resourceDsq.BeginExecute(onResComplete, null); }
/// <summary> /// Executes the operation asynchronously. /// </summary> /// <typeparam name="T">The type of element.</typeparam> /// <param name="query">The query to execute.</param> /// <param name="state">The state transferable state.</param> /// <returns>A function delegate that returns the future result to be available through the Task.</returns> public static Task <IEnumerable <T> > ExecuteAsync <T>(this DataServiceQuery <T> query, object state) { return(Task.Factory.FromAsync <IEnumerable <T> >(query.BeginExecute, query.EndExecute, state)); }
/// <summary> /// Gets the lesson by identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="onComplete">The on complete.</param> public void GetLessonByID(int id, OnQueryComplete onComplete) { lessonDsq = (DataServiceQuery <LESSON>)(ctx.LESSON.Where(r => r.ID == id)); this.onUQC = onComplete; resourceDsq.BeginExecute(onResComplete, null); }
public static DataServiceQuerySingle <T> GetSingleEntityByKey <T>(this DataServiceQuery <T> source, IDictionary <string, object> alternateKeys) { var keys = string.Join(',', alternateKeys.Select(kv => $"{kv.Key}={ODataUriUtils.ConvertToUriLiteral(kv.Value, ODataVersion.V4)}")); return(new DataServiceQuerySingle <T>(source.Context, source.GetKeyPath(keys))); }
/// <summary> /// Gets the course by identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="onComplete">The on complete.</param> public void GetCourseByID(int id, OnQueryComplete onComplete) { courseDsq = (DataServiceQuery <COURSE>)(ctx.COURSE.Where(r => r.ID == id)); this.onUQC = onComplete; resourceDsq.BeginExecute(onResComplete, null); }
public static T CreateEntity <T>(DataServiceContext ctx, string entitySetName, EntityStates state, DataServiceQuery <T> query) where T : class, new() { T entity = null; try { switch (state) { case EntityStates.Added: entity = new T(); ctx.AddObject(entitySetName, entity); break; case EntityStates.Deleted: entity = CreateEntity(ctx, entitySetName, EntityStates.Unchanged, query); ctx.DeleteObject(entity); break; case EntityStates.Detached: entity = query.Execute().Single(); Assert.AreEqual(MergeOption.NoTracking != ctx.MergeOption, ctx.Detach(entity)); break; case EntityStates.Unchanged: entity = query.Execute().Single(); if (MergeOption.NoTracking == ctx.MergeOption) { ctx.AttachTo(entitySetName, entity); } break; case EntityStates.Modified: entity = CreateEntity(ctx, entitySetName, EntityStates.Unchanged, query); ctx.UpdateObject(entity); break; default: Assert.Fail(String.Format("unexpected state encountered: {0}", state)); break; } } catch (Exception ex) { Assert.Fail("{0}", ex); } return(entity); }
/// <summary> /// Gets the user by identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="onComplete">The on complete.</param> public void getUserById(int id, OnQueryComplete onComplete) { customerDsq = (DataServiceQuery <CUSTOMER>)(from cus in ctx.CUSTOMER where cus.ID == Constants.User.ID select cus); this.onUQC = onComplete; customerDsq.BeginExecute(onQueryComplete2, null); }