public async Task DataServiceActionQueryExecuteAsyncCancellationTokenTest()
        {
            var      source  = new CancellationTokenSource();
            var      context = this.CreateWrappedContext <DefaultContainer>().Context;
            Customer c1      = new Customer {
                CustomerId = 11, Name = "customerOne"
            };

            context.AddToCustomer(c1);
            Customer c2 = new Customer {
                CustomerId = 22, Name = "customerTwo"
            };

            context.AddToCustomer(c2);
            await context.SaveChangesAsync();

            AuditInfo auditInfo = new AuditInfo()
            {
                ModifiedDate = new DateTimeOffset()
            };

            DataServiceQuerySingle <Customer> customer          = context.Customer.ByKey(11);
            DataServiceActionQuery            getComputerAction = customer.ChangeCustomerAuditInfo(auditInfo);

            Task response() => getComputerAction.ExecuteAsync(source.Token);

            source.Cancel();
            var exception = await Assert.ThrowsAsync <OperationCanceledException>(response);

            Assert.Equal("The operation was canceled.", exception.Message);

            this.EnqueueTestComplete();
        }
 /// <summary>Create a query of a single item based on another one.</summary>
 /// <param name="query">The query.</param>
 public DataServiceQuerySingle(DataServiceQuerySingle <TElement> query)
 {
     this.Context      = query.Context;
     this.Query        = query.Query;
     this.IsComposable = query.IsComposable;
     this.isFunction   = query.isFunction;
 }
Beispiel #3
0
        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <typeparam name="T">The type.</typeparam>
        /// <param name="query">The query.</param>
        /// <returns>A value</returns>
        public static T GetValue <T>(DataServiceQuerySingle <T> query)
        {
            var tries    = 0;
            var maxTries = 3;

            var watch = new Stopwatch();

            watch.Start();

            while (tries < maxTries)
            {
                try
                {
                    var result = query.GetValueAsync().Result;
                    watch.Stop();
                    LogInfo($"     <.><.> GetValue<T>: {query.RequestUri}: {watch.ElapsedMilliseconds}ms");

                    return(result);
                }
                catch (DataServiceQueryException ex)
                {
                    LogError($"Exception {ex.InnerException.Message} on GetValue:{ex.Response.Query}", typeof(Proxy));
                    return(default(T));
                }
                catch (AggregateException ex)
                {
                    foreach (var e in ex.InnerExceptions)
                    {
                        if (e is DataServiceQueryException dataserviceQueryException)
                        {
                            switch (dataserviceQueryException.Response.StatusCode)
                            {
                            case 404:
                                // If the item is not found, we return a null.
                                // That is easier to code for than throwing an exception
                                LogError($"Entity Not Found Exception (404) - Query: {dataserviceQueryException.Response.Query} - Message:{dataserviceQueryException.Message}", typeof(Proxy));
                                return(default(T));

                            default:
                                LogError($"Query Exception - Query:{dataserviceQueryException.Response.Query} - Message:{dataserviceQueryException.Message}", typeof(Proxy));
                                throw dataserviceQueryException;
                            }
                        }

                        LogError($"Exception {e.GetType()}: {e.Message} on GetValue:{query.RequestUri}", typeof(Proxy));
                        throw e;
                    }
                }
                catch (Exception ex)
                {
                    LogError($"Exception {ex.GetType()}: {ex.Message} GetValue:{query.RequestUri}", typeof(Proxy));
                    throw;
                }

                tries++;
                Thread.Sleep(100);
            }

            throw new CommerceServiceQuerySingleException(query.RequestUri.ToString());
        }
Beispiel #4
0
        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <typeparam name="T">The type.</typeparam>
        /// <param name="query">The query.</param>
        /// <returns>A value</returns>
        public static T GetValue <T>(DataServiceQuerySingle <T> query)
        {
            var tries    = 0;
            var maxTries = 3;

            var watch = new Stopwatch();

            watch.Start();

            while (tries < maxTries)
            {
                try
                {
                    var result = query.GetValueAsync().Result;

                    watch.Stop();
                    Console.WriteLine($"     <.><.> GetValue<T>: {query.RequestUri}: {watch.ElapsedMilliseconds}ms");

                    return(result);
                }
                catch (DataServiceQueryException ex)
                {
                    WriteColoredLine(ConsoleColor.Red, $"Exception {ex.InnerException.Message} on GetValue:{ex.Response.Query}");
                }
                catch (AggregateException ex)
                {
                    WriteColoredLine(ConsoleColor.Red, $"Aggregate Exception {ex.InnerException.Message}");
                    var exception = ex.InnerException as DataServiceQueryException;
                    if (exception != null)
                    {
                        var dataserviceQueryException = exception;

                        switch (dataserviceQueryException.Response.StatusCode)
                        {
                        case 404:
                            // If the item is not found, we return a null.
                            // That is easier to code for than throwing an exception
                            WriteColoredLine(ConsoleColor.Red, $"Entity Not Found Exception (404) - Query: {dataserviceQueryException.Response.Query}");
                            return(default(T));

                        default:
                            WriteColoredLine(ConsoleColor.Red, $"Query Exception - Query:{dataserviceQueryException.Response.Query} - Message:{dataserviceQueryException.Message}");
                            throw dataserviceQueryException;
                        }
                    }
                }
                catch (Exception ex)
                {
                    WriteColoredLine(ConsoleColor.Red, $"Unknown Exception {ex.Message} GetValue:{query.RequestUri}");
                }

                tries++;
                Thread.Sleep(100);
            }

            throw new CommerceServiceQuerySingleException(query.RequestUri.ToString());
        }
        public void FunctionOfEntityTakeCollectionReturnEntities()
        {
            var customerQuery = new DataServiceQuerySingle <Customer>(this.TestClientContext, "Customers(3)");

            var functionQuery = customerQuery.CreateFunctionQuery <Order>("Microsoft.Test.OData.Services.ODataOperationService.GetOrdersFromCustomerByNotes", true, new UriOperationParameter("notes", new Collection <string> {
                "1111", "2222"
            }));
            var orders = functionQuery.Execute();

            Assert.AreEqual(1, orders.Count());
        }
Beispiel #6
0
        static async Task Main(string[] args)
        {
            var context = new DataContainer(new Uri("http://localhost:5001/"));

            context.MergeOption = MergeOption.NoTracking;

            // go through the accounts
            foreach (var account in context.Accounts)
            {
                Console.WriteLine("Account: {0}", account.Name);
            }

            // project the ID of an account
            var accountId = (
                from a in context.Accounts
                where a.Name == "Customer 1"
                select new
            {
                Id = a.Id,
            }).FirstOrDefault();

            // get a query to the GetUsers() for the account we chose
            var keyPath    = context.Accounts.GetKeyPath(accountId.Id.ToString());
            var accountObj = new DataServiceQuerySingle <Account>(context.Accounts.Context, keyPath);
            var query      = accountObj.CreateFunctionQuery <User>("GetUsers", true);

            // project on GetUsers()
            var users =
                from u in query
                select new
            {
                Name = u.Name,
            };

            // output the result
            foreach (var user in users)
            {
                Console.WriteLine(user.Name);
            }


            Console.WriteLine("Done. Press a key to close.");
            Console.ReadKey();
        }
        public static async Task PatchPropertyAsync <TEntity>(this DataServiceQuerySingle <TEntity> singleQuery, ExpandoObject patchDelta) where TEntity : BaseEntityType
        {
            using (var client = new HttpClient())
            {
                var stringPayload = JsonConvert.SerializeObject(patchDelta);
                var httpContent   = new StringContent(stringPayload, Encoding.UTF8, "application/json");

                var request = new HttpRequestMessage(new HttpMethod("PATCH"), $"{singleQuery.RequestUri.AbsoluteUri}")
                {
                    Content = httpContent
                };

                var response = await client.SendAsync(request);

                if (!response.IsSuccessStatusCode)
                {
                    throw new ServerException(response);
                }
            }
        }
 /// <summary>
 /// Creates a data object with change tracking
 /// that can be used to PATCH an existing entity with
 /// just the data that was set or modified in the data object.
 /// </summary>
 /// <typeparam name="T">Type of the entity to create.</typeparam>
 /// <param name="entity">The entity to be patched.</param>
 /// <returns>
 /// A data object with change tracking enabled.
 /// </returns>
 /// <remarks>
 /// Operation is persisted when <see cref="DataServiceContext.SaveChangesAsync()"/> is invoked.
 /// </remarks>
 public static T PatchEntityWithChangeTracking <T>(this DataServiceQuerySingle <T> entity)
 {
     return(new DataServiceCollection <T>(entity)[0]);
 }
Beispiel #9
0
 /// <summary>Initializes a new instance of the <see cref="Microsoft.OData.Client.DataServiceCollection{T}" /> class based on query execution and with the specified tracking mode.</summary>
 /// <param name="trackingMode">A <see cref="Microsoft.OData.Client.TrackingMode" /> value that indicated whether or not changes made to items in the collection are automatically tracked.</param>
 /// <param name="item">A <see cref="Microsoft.OData.Client.DataServiceQuerySingle{T}" /> or LINQ query that returns an object that are used to initialize the collection.</param>
 public DataServiceCollection(TrackingMode trackingMode, DataServiceQuerySingle <T> item)
     : this(null, item.Query, trackingMode, null, null, null)
 {
 }
Beispiel #10
0
 /// <summary>Initializes a new instance of the <see cref="Microsoft.OData.Client.DataServiceCollection{T}" /> class based on query execution.</summary>
 /// <param name="item">A <see cref="Microsoft.OData.Client.DataServiceQuerySingle{T}" /> or LINQ query that returns an object that are used to initialize the collection.</param>
 public DataServiceCollection(DataServiceQuerySingle <T> item)
     : this(null, item.Query, TrackingMode.AutoChangeTracking, null, null, null)
 {
 }