/// <summary>Constructor</summary>
 /// <param name="queryOperationResponse">The response for the Load operation. null when the operation didn't succeed.</param>
 /// <param name="error"><see cref="Exception"/> which represents the error if the Load operation failed. null if the operation
 /// didn't fail.</param>
 /// <param name="cancelled">True, if the LoadAsync operation was cancelled, False otherwise.</param>
 /// <remarks>This constructor doesn't allow creation of canceled event args.</remarks>
 internal LoadCompletedEventArgs(
     QueryOperationResponse queryOperationResponse,
     Exception error,
     bool cancelled)
     : base(error, cancelled, null)
 {
     this.queryOperationResponse = queryOperationResponse;
 }
        /// <summary>
        /// Extracts the server error message from a client side query exception.
        /// </summary>
        /// <param name="response">The QueryOperationResponse to extract error message from.</param>
        /// <returns>The server error message.</returns>
        public static string ExtractServerErrorMessage(QueryOperationResponse response)
        {
            string contentType = response.Headers[HttpHeaders.ContentType];

            var innerException = response.Error as DataServiceClientException;
            ExceptionUtilities.Assert(innerException != null, "No inner exception on query exception");

            return GetErrorMessage(innerException, contentType);
        }
        private void GetPhotosFromService(MergeOption mergeOption)
        {
            // Set the merge option.
            context.MergeOption = mergeOption;

            try
            {
                // Define a query that returns a feed with all PhotoInfo objects.
                var query = context.PhotoInfo;

                // Create a new collection for binding based on the executed query.
                trackedPhotos = new DataServiceCollection <PhotoInfo>(query);

                // Load all pages of the response into the binding collection.
                while (trackedPhotos.Continuation != null)
                {
                    trackedPhotos.Load(
                        context.Execute <PhotoInfo>(trackedPhotos.Continuation.NextLinkUri));
                }

                // Bind the root StackPanel element to the collection;
                // related object binding paths are defined in the XAML.
                LayoutRoot.DataContext = trackedPhotos;

                if (trackedPhotos.Count == 0)
                {
                    MessageBox.Show("Data could not be returned from the data service.");
                }

                // Select the first photo in the collection.
                photoComboBox.SelectedIndex = 0;

                // Enable the buttons.
                photoDetails.IsEnabled = true;
                addPhoto.IsEnabled     = true;
                deletePhoto.IsEnabled  = true;
            }
            catch (DataServiceQueryException ex)
            {
                string errorMessage = string.Empty;

                // Get the response from the request.
                QueryOperationResponse response = ex.Response;

                // If we have a 404, the URI may be incorrect.
                if (response.StatusCode == 404)
                {
                    errorMessage = string.Format("Make sure that the service URI '{0}' is correct.",
                                                 svcUri.ToString());
                }
                else
                {
                    // Get the error message from the response.
                    errorMessage = response.Error.Message;
                }

                // Display the message.
                MessageBox.Show(errorMessage,
                                string.Format("Error Status Code: {0}", response.StatusCode));
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                // Reset the merge option to the default.
                context.MergeOption = MergeOption.AppendOnly;
            }
        }
        /// <summary>
        /// Translates the data service exception.
        /// </summary>
        /// <param name="e">The exception.</param>
        /// <param name="reqResult">The request result.</param>
        /// <param name="parseError">The delegate used to parse the error to get extended error information.</param>
        /// <returns>
        /// The translated exception.
        /// </returns>
        internal static StorageException TranslateDataServiceException(Exception e, RequestResult reqResult, Func <Stream, IDictionary <string, string>, StorageExtendedErrorInformation> parseError)
        {
            try
            {
                // The exception thrown is based on whether it is a change/query operation.
                DataServiceRequestException dsre = FindInnerExceptionOfType <DataServiceRequestException>(e);

                DataServiceQueryException dsqe = FindInnerExceptionOfType <DataServiceQueryException>(e);

                if (dsre == null && dsqe == null)
                {
                    InvalidOperationException ioe = TableUtilities.FindInnerExceptionOfType <InvalidOperationException>(e);

                    if (ioe != null && !(ioe is WebException) && string.CompareOrdinal(ioe.Source, "Microsoft.Data.Services.Client") == 0 && ioe.Message.Contains("type is not compatible with the expected"))
                    {
                        return(new StorageException(reqResult, e.Message, e)
                        {
                            IsRetryable = false
                        });
                    }

                    return(null);
                }
                else if (dsre != null)
                {
                    DataServiceResponse response = dsre.Response;

                    // Get the batch status code first in case batch does not contain any responses.
                    reqResult.HttpStatusCode = response.BatchStatusCode;

                    IDictionary <string, string> headers;
                    foreach (OperationResponse operationResponse in response)
                    {
                        reqResult.HttpStatusCode = operationResponse.StatusCode;

                        // The exception thrown will contain the first error in the group of requests.
                        if (reqResult.HttpStatusCode >= 300)
                        {
                            headers = operationResponse.Headers;

                            // Strip off the extra exception type at the beginning.
                            string innerException = dsre.InnerException.ToString().Replace("System.Data.Services.Client.DataServiceClientException: ", string.Empty);

                            using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(innerException)))
                            {
                                reqResult.ExtendedErrorInformation = parseError(stream, headers);
                            }

                            break;
                        }
                    }

                    return(new StorageException(
                               reqResult,
                               reqResult.ExtendedErrorInformation != null ? reqResult.ExtendedErrorInformation.ErrorCode : dsre.Message,
                               dsre));
                }
                else
                {
                    QueryOperationResponse response = dsqe.Response;

                    reqResult.HttpStatusCode = response.StatusCode;

                    string innerException = dsqe.InnerException.Message;

                    using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(innerException)))
                    {
                        reqResult.ExtendedErrorInformation = parseError(stream, response.Headers);
                    }

                    return(new StorageException(
                               reqResult,
                               reqResult.ExtendedErrorInformation != null ? reqResult.ExtendedErrorInformation.ErrorCode : dsqe.Message,
                               dsqe));
                }
            }
            catch (Exception)
            {
                return(new StorageException(reqResult, e.Message, e));
            }
        }
Beispiel #5
0
            public void QueryRowCountNotFoundException()
            {
                var    baseQuery                   = ctx.CreateQuery <northwindClient.Customers>("Customer");
                var    inlineQuery                 = baseQuery.IncludeTotalCount();
                string countNotPresentMsg          = DataServicesClientResourceUtil.GetString("MaterializeFromAtom_CountNotPresent");
                string resourceNotFoundCustomerMsg = DataServicesResourceUtil.GetString("RequestUriProcessor_ResourceNotFound", "Customer");
                string resourceNotFoundVar1Msg     = DataServicesResourceUtil.GetString("RequestUriProcessor_ResourceNotFound", "VAR1");

                for (int i = 0; i < 2; ++i)
                {
                    ctx.IgnoreResourceNotFoundException = (i == 0);

                    // case 1: $count=inline, 404 exception gives empty set
                    try
                    {
                        QueryOperationResponse <northwindClient.Customers> qor = (QueryOperationResponse <northwindClient.Customers>)inlineQuery.Execute();
                        Assert.AreEqual(i, 0);

                        // client count:
                        Assert.AreEqual(qor.Count(), 0);

                        // server count should fail:
                        long count = qor.TotalCount;

                        Assert.Fail("Server count failed to throw on 404");
                    }
                    catch (DataServiceQueryException ex)
                    {
                        Assert.AreEqual(i, 1);
                        Assert.IsNotNull(ex.InnerException);
                        Assert.IsTrue(ex.InnerException.Message.Contains(resourceNotFoundCustomerMsg));
                    }
                    catch (InvalidOperationException ex)
                    {
                        Assert.AreEqual(i, 0);
                        Assert.AreEqual(countNotPresentMsg, ex.Message);
                    }

                    // case 2: $count=value, 404 exception
                    try
                    {
                        long count = baseQuery.LongCount();
                        Assert.Fail("Server count failed to throw on 404");
                    }
                    catch (DataServiceQueryException ex)
                    {
                        Assert.IsNotNull(ex.InnerException);
                        Assert.IsTrue(ex.InnerException.Message.Contains(resourceNotFoundCustomerMsg));
                    }

                    // case 3: custom URI on context
                    try
                    {
                        QueryOperationResponse <northwindClient.Customers> qor = (QueryOperationResponse <northwindClient.Customers>)ctx.Execute <northwindClient.Customers>("/VAR1?$count=true");
                        Assert.AreEqual(i, 0);

                        // client count:
                        Assert.AreEqual(qor.Count(), 0);

                        // server count should fail:
                        long count = qor.TotalCount;

                        Assert.Fail("Server count failed to throw on 404");
                    }
                    catch (DataServiceQueryException ex)
                    {
                        Assert.AreEqual(i, 1);
                        Assert.IsNotNull(ex.InnerException);
                        Assert.IsTrue(ex.InnerException.Message.Contains(resourceNotFoundVar1Msg));
                    }
                    catch (InvalidOperationException ex)
                    {
                        Assert.AreEqual(i, 0);
                        Assert.AreEqual(countNotPresentMsg, ex.Message);
                    }


                    // case 4: $count=inline, ASYNC, 404 exception gives empty set
                    bool asyncComplete = false;
                    inlineQuery.BeginExecute(ar =>
                    {
                        try
                        {
                            QueryOperationResponse <northwindClient.Customers> qor = (QueryOperationResponse <northwindClient.Customers>)inlineQuery.EndExecute(ar);
                            Assert.AreEqual(qor.Count(), 0);
                            long count = qor.TotalCount;
                            Assert.Fail("Server count failed to throw on 404");
                        }
                        catch (DataServiceQueryException ex)
                        {
                            Assert.AreEqual(i, 1);
                            Assert.IsNotNull(ex.InnerException);
                            Assert.IsNotNull(ex.InnerException.InnerException);
                            Assert.IsTrue(ex.InnerException.InnerException.Message.Contains(resourceNotFoundCustomerMsg));
                        }
                        catch (InvalidOperationException ex)
                        {
                            Assert.AreEqual(i, 0);
                            Assert.AreEqual(countNotPresentMsg, ex.Message);
                        }
                        finally
                        {
                            asyncComplete = true;
                        }
                    }, null);

                    while (!asyncComplete)
                    {
                        Thread.Sleep(10);
                    }
                }
            }
        [Ignore] // Remove Atom
        // [TestMethod]
        public void LoadPropertyRemoveElementUnChangedSource()
        {
            MergeOption original = this.context.MergeOption;

            try
            {
                foreach (MergeOption mo in new[] { MergeOption.OverwriteChanges, MergeOption.PreserveChanges })
                {
                    foreach (bool usePaging in new[] { false, true })
                    {
                        using (CustomDataContext.CreateChangeScope())
                            using (OpenWebDataServiceHelper.PageSizeCustomizer.Restore())
                            {
                                OpenWebDataServiceHelper.PageSizeCustomizer.Value = (config, type) => { config.SetEntitySetPageSize("Orders", usePaging ? 1 : 5); };
                                Customer c = new Customer()
                                {
                                    ID = 0
                                };
                                Customer c2 = new Customer()
                                {
                                    ID = 2
                                };
                                Order o = new Order()
                                {
                                    ID = 102
                                };

                                this.context.MergeOption = mo;

                                this.context.AttachTo("Customers", c);
                                this.context.AttachTo("Customers", c2);
                                this.context.AttachTo("Orders", o);

                                this.context.AddLink(c, "Orders", o);
                                this.context.SetLink(o, "Customer", c);
                                this.context.SaveChanges();

                                if (usePaging)
                                {
                                    DataServiceQueryContinuation continuation = null;
                                    do
                                    {
                                        QueryOperationResponse response = this.context.LoadProperty(c, "Orders", continuation);
                                        continuation = response.GetContinuation();
                                    }while (continuation != null);
                                }
                                else
                                {
                                    this.context.LoadProperty(c, "Orders");
                                }

                                this.context.LoadProperty(o, "Customer");

                                if (c.Orders != null)
                                {
                                    Assert.IsTrue(c.Orders.Contains(o));
                                }
                                if (o.Customer != null)
                                {
                                    Assert.IsTrue(o.Customer.ID == c.ID);
                                }

                                // Remove the link
                                this.context.DeleteLink(c, "Orders", o);
                                this.context.SetLink(o, "Customer", c2);

                                this.context.SaveChanges();

                                if (usePaging)
                                {
                                    DataServiceQueryContinuation continuation = null;
                                    do
                                    {
                                        QueryOperationResponse response = this.context.LoadProperty(c, "Orders", continuation);
                                        continuation = response.GetContinuation();
                                    }while (continuation != null);
                                }
                                else
                                {
                                    this.context.LoadProperty(c, "Orders");
                                }

                                this.context.LoadProperty(o, "Customer");

                                if (c.Orders != null)
                                {
                                    Assert.IsFalse(c.Orders.Contains(o));
                                }
                                if (o.Customer != null)
                                {
                                    Assert.IsFalse(o.Customer.ID == c.ID);
                                }
                            }

                        this.ClearContext();
                    }
                }
            }
            finally
            {
                this.context.MergeOption = original;
            }
        }
        public static void InitRequest <T, INTERMEDIATE_TYPE>(ExecutionState <T> executionState)
        {
            try
            {
                executionState.Init();

                // 0. Begin Request
                TableExecutor.StartRequestAttempt(executionState);

                if (TableExecutor.CheckTimeout <T>(executionState, false))
                {
                    TableExecutor.EndOperation <T, INTERMEDIATE_TYPE>(executionState);
                    return;
                }

                lock (executionState.CancellationLockerObject)
                {
                    if (TableExecutor.CheckCancellation(executionState))
                    {
                        TableExecutor.EndOperation <T, INTERMEDIATE_TYPE>(executionState);
                        return;
                    }

                    TableCommand <T, INTERMEDIATE_TYPE> tableCommandRef = executionState.Cmd as TableCommand <T, INTERMEDIATE_TYPE>;

                    // Execute Call
                    Logger.LogInformational(executionState.OperationContext, SR.TraceStartRequestAsync, tableCommandRef.Context.BaseUri);
                    tableCommandRef.Begin(
                        (res) =>
                    {
                        executionState.UpdateCompletedSynchronously(res.CompletedSynchronously);
                        INTERMEDIATE_TYPE tResult = default(INTERMEDIATE_TYPE);

                        try
                        {
                            tResult = tableCommandRef.End(res);

                            executionState.Result = tableCommandRef.ParseResponse(tResult, executionState.Cmd.CurrentResult, tableCommandRef);

                            if (executionState.Req != null)
                            {
                                DataServiceResponse dataServiceResponse = tResult as DataServiceResponse;
                                QueryOperationResponse queryResponse    = tResult as QueryOperationResponse;

                                if (dataServiceResponse != null)
                                {
                                    if (dataServiceResponse.IsBatchResponse)
                                    {
                                        // Attempt to populate response headers
                                        if (executionState.Req != null)
                                        {
                                            SetExecutionStateCommandResult(executionState, dataServiceResponse);
                                            Logger.LogInformational(executionState.OperationContext, SR.TraceResponse, executionState.Cmd.CurrentResult.HttpStatusCode, executionState.Cmd.CurrentResult.ServiceRequestID, executionState.Cmd.CurrentResult.ContentMd5, executionState.Cmd.CurrentResult.Etag);
                                        }
                                    }
                                    else
                                    {
                                        int index = 0;
                                        foreach (OperationResponse operationResponse in dataServiceResponse)
                                        {
                                            // Attempt to populate response headers
                                            if (executionState.Req != null)
                                            {
                                                SetStorageCmdRequestResults(executionState.Cmd.RequestResults.ElementAt(index), operationResponse);
                                                Logger.LogInformational(executionState.OperationContext, SR.TraceResponse, executionState.Cmd.RequestResults.ElementAt(index).HttpStatusCode, executionState.Cmd.RequestResults.ElementAt(index).ServiceRequestID, executionState.Cmd.RequestResults.ElementAt(index).ContentMd5, executionState.Cmd.RequestResults.ElementAt(index).Etag);
                                                index++;
                                            }
                                        }
                                    }
                                }
                                else if (queryResponse != null)
                                {
                                    // Attempt to populate response headers
                                    if (executionState.Req != null)
                                    {
                                        SetStorageCmdRequestResults(executionState.Cmd.CurrentResult, queryResponse);
                                        Logger.LogInformational(executionState.OperationContext, SR.TraceResponse, executionState.Cmd.CurrentResult.HttpStatusCode, executionState.Cmd.CurrentResult.ServiceRequestID, executionState.Cmd.CurrentResult.ContentMd5, executionState.Cmd.CurrentResult.Etag);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogWarning(executionState.OperationContext, SR.TraceGenericError, ex.Message);

                            lock (executionState.CancellationLockerObject)
                            {
                                if (executionState.CancelRequested)
                                {
                                    // Ignore DSC exception if request was canceled.
                                    return;
                                }
                            }

                            // Store exception and invoke callback here. All operations in this try would be non-retryable by default
                            if (executionState.ExceptionRef == null || !(executionState.ExceptionRef is StorageException))
                            {
                                executionState.ExceptionRef = ExecutorBase.TranslateDataServiceExceptionBasedOnParseError(ex, executionState.Cmd.CurrentResult, executionState.Cmd.ParseDataServiceError);
                            }

                            try
                            {
                                executionState.Result = tableCommandRef.ParseResponse(tResult, executionState.Cmd.CurrentResult, tableCommandRef);

                                // clear exception
                                executionState.ExceptionRef = null;
                            }
                            catch (Exception parseEx)
                            {
                                Logger.LogWarning(executionState.OperationContext, SR.TraceGenericError, ex.Message);
                                executionState.ExceptionRef = parseEx;
                            }
                        }
                        finally
                        {
                            EndOperation <T, INTERMEDIATE_TYPE>(executionState);
                        }
                    },
                        null);

                    if (tableCommandRef.Context != null)
                    {
                        executionState.CancelDelegate = tableCommandRef.Context.InternalCancel;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogWarning(executionState.OperationContext, SR.TraceGenericError, ex.Message);

                // Store exception and invoke callback here. All operations in this try would be non-retryable by default
                if (executionState.ExceptionRef == null || !(executionState.ExceptionRef is StorageException))
                {
                    executionState.ExceptionRef = ExecutorBase.TranslateDataServiceExceptionBasedOnParseError(ex, executionState.Cmd.CurrentResult, executionState.Cmd.ParseDataServiceError);
                }

                executionState.OnComplete();
            }
        }
 internal static void PreprocessObjectToWrite(ref object objectToWrite, ObjectGraphInfo info)
 {
     if (objectToWrite is DataServiceQuery)
     {
         objectToWrite = ((DataServiceQuery)objectToWrite).Execute();
     }
     if (objectToWrite is QueryOperationResponse)
     {
         QueryOperationResponse qor = (QueryOperationResponse)objectToWrite;
         if (qor.GetType().IsGenericType&& (qor.GetType().GetGenericTypeDefinition() == typeof(QueryOperationResponse <>)))
         {
             objectToWrite = Util.VerticalRun(new object[] { new QueryOperationResponseWrapper(true, qor), new QueryOperationResponseWrapper(false, qor) });
         }
     }
     else if (objectToWrite is QueryOperationResponseWrapper)
     {
         QueryOperationResponseWrapper wrapper = (QueryOperationResponseWrapper)objectToWrite;
         if (wrapper.Enumerate)
         {
             objectToWrite = wrapper.Qor;
         }
         else
         {
             DataServiceQueryContinuation continuation = wrapper.Qor.GetContinuation();
             if (!((continuation == null) || wrapper.ElementType.Name.Contains <char>('<')))
             {
                 Uri nextLinkUri = continuation.NextLinkUri;
                 objectToWrite = new Hyperlinq(QueryLanguage.Expression, "Execute<" + wrapper.ElementType.Name + "> (new Uri (\"" + nextLinkUri.ToString() + "\"))", "Next Page");
             }
             else
             {
                 objectToWrite = info.DisplayNothingToken;
             }
         }
     }
     else
     {
         DataServiceQueryException exception = objectToWrite as DataServiceQueryException;
         if ((exception != null) && (exception.InnerException is DataServiceClientException))
         {
             DataServiceClientException innerException = (DataServiceClientException)exception.InnerException;
             try
             {
                 XElement element = XElement.Parse(innerException.Message);
                 if (element.Name.LocalName == "error")
                 {
                     XNamespace namespace2 = element.Name.Namespace;
                     string     str        = (string)element.Element((XName)(namespace2 + "message"));
                     if (!string.IsNullOrEmpty(str))
                     {
                         str = str.Trim();
                         if (str.EndsWith("cannot be used in a query"))
                         {
                             str = str + " predicate";
                         }
                         if (!str.EndsWith("."))
                         {
                             str = str + ".";
                         }
                         Util.Highlight(str + " See exception below for more details.").Dump <object>();
                     }
                 }
             }
             catch
             {
             }
         }
     }
 }
 public QueryOperationResponseWrapper(bool enumerate, QueryOperationResponse qor)
 {
     this.Enumerate = enumerate;
     this.Qor = qor;
 }
Beispiel #10
0
 // Creator - should be faster than Activator.CreateInstance
 public static PagedCollection <TElement, TConcrete> Create(DataServiceContextWrapper context,
                                                            QueryOperationResponse <TConcrete> qor)
 {
     return(new PagedCollection <TElement, TConcrete>(context, qor));
 }
Beispiel #11
0
 public QueryOperationResponseWrapper(QueryOperationResponse qr)
     : base(qr)
 {
     this._QueryResponse = qr;
 }
 /// <summary>Constructor</summary>
 /// <param name="queryOperationResponse">The response for the Load operation. null when the operation didn't succeed.</param>
 /// <param name="error"><see cref="Exception"/> which represents the error if the Load operation failed. null if the operation
 /// didn't fail.</param>
 /// <remarks>This constructor doesn't allow creation of canceled event args.</remarks>
 internal LoadCompletedEventArgs(QueryOperationResponse queryOperationResponse, Exception error)
     : this(queryOperationResponse, error, false)
 {
 }
        /// <remarks></remarks>
        private IEnumerable <CloudEntity <T> > GetInternal <T>(TableServiceContext context, string tableName, Maybe <string> filter)
        {
            string continuationRowKey       = null;
            string continuationPartitionKey = null;

            var stopwatch = Stopwatch.StartNew();

            context.MergeOption = MergeOption.AppendOnly;
            context.ResolveType = ResolveFatEntityType;

            do
            {
                var query = context.CreateQuery <FatEntity>(tableName);

                if (filter.HasValue)
                {
                    query = query.AddQueryOption("$filter", filter.Value);
                }

                if (null != continuationRowKey)
                {
                    query = query.AddQueryOption(NextRowKeyToken, continuationRowKey)
                            .AddQueryOption(NextPartitionKeyToken, continuationPartitionKey);
                }

                QueryOperationResponse response    = null;
                FatEntity[]            fatEntities = null;

                Retry.Do(_policies.TransientTableErrorBackOff(), CancellationToken.None, () =>
                {
                    try
                    {
                        response    = query.Execute() as QueryOperationResponse;
                        fatEntities = ((IEnumerable <FatEntity>)response).ToArray();
                    }
                    catch (DataServiceQueryException ex)
                    {
                        // if the table does not exist, there is nothing to return
                        var errorCode = RetryPolicies.GetErrorCode(ex);
                        if (TableErrorCodeStrings.TableNotFound == errorCode ||
                            StorageErrorCodeStrings.ResourceNotFound == errorCode)
                        {
                            fatEntities = new FatEntity[0];
                            return;
                        }

                        throw;
                    }
                });

                NotifySucceeded(StorageOperationType.TableQuery, stopwatch);

                foreach (var fatEntity in fatEntities)
                {
                    var etag = context.Entities.First(e => e.Entity == fatEntity).ETag;
                    context.Detach(fatEntity);
                    yield return(FatEntity.Convert <T>(fatEntity, _serializer, etag));
                }

                Debug.Assert(context.Entities.Count == 0);

                if (null != response && response.Headers.ContainsKey(ContinuationNextRowKeyToken))
                {
                    continuationRowKey       = response.Headers[ContinuationNextRowKeyToken];
                    continuationPartitionKey = response.Headers[ContinuationNextPartitionKeyToken];

                    stopwatch.Restart();
                }
                else
                {
                    continuationRowKey       = null;
                    continuationPartitionKey = null;
                }
            } while (null != continuationRowKey);
        }
Beispiel #14
0
 public QueryOperationResponseWrapper(bool enumerate, QueryOperationResponse qor)
 {
     this.Enumerate = enumerate;
     this.Qor       = qor;
 }
        private void RunPositiveFunctionTest(ODataFormat format, TestCase testCase)
        {
            // All of the functions tests use the PlaybackService since the WCF Data Services server doesn't support functions
            // The PlaybackService itself will not automatically turn Metadata into an absolute URI, so set that to false on all tests.
            // The tests also use absolute URIs for Target, so suppress that as well.
            testCase.AddBaseUriToMetadata = false;
            testCase.AddBaseUriToTarget   = false;

            using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
                using (PlaybackService.ProcessRequestOverride.Restore())
                {
                    request.ServiceType = typeof(AstoriaUnitTests.Stubs.PlaybackService);
                    request.StartService();

                    var payloadBuilder = testCase.ResponsePayloadBuilder;
                    PlaybackService.ProcessRequestOverride.Value = (req) =>
                    {
                        string contentType;
                        if (format == ODataFormat.Json)
                        {
                            contentType             = UnitTestsUtil.JsonLightMimeType;
                            payloadBuilder.Metadata = request.BaseUri + "/$metadata#TestService.CustomerEntities/$entity";
                        }
                        else
                        {
                            contentType = UnitTestsUtil.AtomFormat;
                        }

                        req.SetResponseStreamAsText(PayloadGenerator.Generate(payloadBuilder, format));
                        req.ResponseHeaders.Add("Content-Type", contentType);
                        req.SetResponseStatusCode(200);
                        return(req);
                    };

                    testCase.AddBaseUriStringToExpectedDescriptors(request.ServiceRoot.OriginalString, format);

                    Uri uri = new Uri(request.ServiceRoot + "/" + testCase.RequestUriString);
                    DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                    ctx.EnableAtom = true;

                    if (format == ODataFormat.Json)
                    {
                        string serviceEdmx = GetServiceEdmxWithOperations(payloadBuilder);
                        JsonLightTestUtil.ConfigureContextForJsonLight(ctx, serviceEdmx);
                    }

                    QueryOperationResponse <CustomerEntity> qor = (QueryOperationResponse <CustomerEntity>)ctx.Execute <CustomerEntity>(uri);
                    Assert.IsNotNull(qor);
                    Assert.IsNull(qor.Error);

                    IEnumerator <CustomerEntity> entities = qor.GetEnumerator();

                    int expectedDescriptorsPerEntity = 0;

                    while (entities.MoveNext())
                    {
                        CustomerEntity   c  = entities.Current;
                        EntityDescriptor ed = ctx.GetEntityDescriptor(c);
                        IEnumerable <OperationDescriptor> actualDescriptors = ed.OperationDescriptors;
                        TestEquality(actualDescriptors, testCase.GetExpectedDescriptors(format)[expectedDescriptorsPerEntity++]);
                    }
                }
        }
Beispiel #16
0
 internal LoadCompletedEventArgs(QueryOperationResponse queryOperationResponse, Exception error)
     : base(error, false, null)
 {
     this.queryOperationResponse = queryOperationResponse;
 }
Beispiel #17
0
        public static T ExecuteSync <T, INTERMEDIATE_TYPE>(TableCommand <T, INTERMEDIATE_TYPE> cmd, IRetryPolicy policy, OperationContext operationContext)
        {
            // Note all code below will reference state, not params directly, this will allow common code with async executor
            ExecutionState <T> executionState = new ExecutionState <T>(cmd, policy, operationContext);

            TableExecutor.AcquireContext(cmd.Context, executionState);
            bool     shouldRetry = false;
            TimeSpan delay       = TimeSpan.Zero;

            try
            {
                // Enter Retryable Section of execution
                do
                {
                    executionState.Init();

                    // 0. Begin Request
                    TableExecutor.StartRequestAttempt(executionState);

                    TableExecutor.CheckTimeout <T>(executionState, true);

                    try
                    {
                        INTERMEDIATE_TYPE tempResult = default(INTERMEDIATE_TYPE);

                        try
                        {
                            Logger.LogInformational(executionState.OperationContext, SR.TraceStartRequestSync, cmd.Context.BaseUri);
                            tempResult = cmd.ExecuteFunc();

                            executionState.Result = cmd.ParseResponse(tempResult, executionState.Cmd.CurrentResult, cmd);

                            DataServiceResponse    dataServiceResponse = tempResult as DataServiceResponse;
                            QueryOperationResponse queryResponse       = tempResult as QueryOperationResponse;

                            if (dataServiceResponse != null)
                            {
                                if (dataServiceResponse.IsBatchResponse)
                                {
                                    // Attempt to populate response headers
                                    if (executionState.Req != null)
                                    {
                                        SetExecutionStateCommandResult(executionState, dataServiceResponse);
                                        Logger.LogInformational(executionState.OperationContext, SR.TraceResponse, executionState.Cmd.CurrentResult.HttpStatusCode, executionState.Cmd.CurrentResult.ServiceRequestID, executionState.Cmd.CurrentResult.ContentMd5, executionState.Cmd.CurrentResult.Etag);
                                    }
                                }
                                else
                                {
                                    int index = 0;
                                    foreach (OperationResponse operationResponse in dataServiceResponse)
                                    {
                                        // Attempt to populate response headers
                                        if (executionState.Req != null)
                                        {
                                            SetStorageCmdRequestResults(executionState.Cmd.RequestResults.ElementAt(index), operationResponse);
                                            Logger.LogInformational(executionState.OperationContext, SR.TraceResponse, executionState.Cmd.RequestResults.ElementAt(index).HttpStatusCode, executionState.Cmd.RequestResults.ElementAt(index).ServiceRequestID, executionState.Cmd.RequestResults.ElementAt(index).ContentMd5, executionState.Cmd.RequestResults.ElementAt(index).Etag);
                                            index++;
                                        }
                                    }
                                }
                            }
                            else if (queryResponse != null)
                            {
                                // Attempt to populate response headers
                                if (executionState.Req != null)
                                {
                                    SetStorageCmdRequestResults(executionState.Cmd.CurrentResult, queryResponse);
                                    Logger.LogInformational(executionState.OperationContext, SR.TraceResponse, executionState.Cmd.CurrentResult.HttpStatusCode, executionState.Cmd.CurrentResult.ServiceRequestID, executionState.Cmd.CurrentResult.ContentMd5, executionState.Cmd.CurrentResult.Etag);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogWarning(executionState.OperationContext, SR.TraceGenericError, ex.Message);

                            // Store exception and invoke callback here. All operations in this try would be non-retryable by default
                            if (executionState.ExceptionRef == null || !(executionState.ExceptionRef is StorageException))
                            {
                                executionState.ExceptionRef = ExecutorBase.TranslateDataServiceExceptionBasedOnParseError(ex, executionState.Cmd.CurrentResult, executionState.Cmd.ParseDataServiceError);
                            }

                            executionState.Result = cmd.ParseResponse(tempResult, executionState.Cmd.CurrentResult, cmd);

                            // clear exception
                            executionState.ExceptionRef = null;
                        }

                        TableExecutor.FinishRequestAttempt(executionState);

                        Logger.LogInformational(executionState.OperationContext, SR.TraceSuccess);
                        return(executionState.Result);
                    }
                    catch (Exception e)
                    {
                        TableExecutor.FinishRequestAttempt(executionState);

                        StorageException translatedException = ExecutorBase.TranslateDataServiceExceptionBasedOnParseError(e, executionState.Cmd.CurrentResult, executionState.Cmd.ParseDataServiceError);
                        executionState.ExceptionRef = translatedException;
                        Logger.LogInformational(executionState.OperationContext, SR.TraceRetryCheck, executionState.RetryCount, executionState.Cmd.CurrentResult.HttpStatusCode, translatedException.IsRetryable ? "yes" : "no", translatedException.Message);

                        shouldRetry = false;
                        if (translatedException.IsRetryable && (executionState.RetryPolicy != null))
                        {
                            shouldRetry = executionState.RetryPolicy.ShouldRetry(
                                executionState.RetryCount++,
                                executionState.Cmd.CurrentResult.HttpStatusCode,
                                executionState.ExceptionRef,
                                out delay,
                                executionState.OperationContext);

                            if ((delay < TimeSpan.Zero) || (delay > Constants.MaximumRetryBackoff))
                            {
                                delay = Constants.MaximumRetryBackoff;
                            }
                        }
                    }

                    if (!shouldRetry || (executionState.OperationExpiryTime.HasValue && (DateTime.Now + delay).CompareTo(executionState.OperationExpiryTime.Value) > 0))
                    {
                        Logger.LogError(executionState.OperationContext, shouldRetry ? SR.TraceRetryDecisionTimeout : SR.TraceRetryDecisionPolicy, executionState.ExceptionRef.Message);
                        throw executionState.ExceptionRef;
                    }
                    else
                    {
                        if (executionState.Cmd.RecoveryAction != null)
                        {
                            // I.E. Rewind stream etc.
                            executionState.Cmd.RecoveryAction(executionState.Cmd, executionState.ExceptionRef, executionState.OperationContext);
                        }

                        Logger.LogInformational(executionState.OperationContext, SR.TraceRetryDelay, (int)delay.TotalMilliseconds);
                        if (delay > TimeSpan.Zero)
                        {
                            Thread.Sleep(delay);
                        }

                        Logger.LogInformational(executionState.OperationContext, SR.TraceRetry);
                    }
                }while (shouldRetry);

                // should never get here, either return, or throw;
                throw new NotImplementedException(SR.InternalStorageError);
            }
            finally
            {
                ReleaseContext(cmd.Context);
            }
        }
 /// <summary>Initializes a new instance of the <see cref="T:Microsoft.OData.Client.DataServiceQueryException" /> class. </summary>
 /// <param name="message">The string value that contains the error message.</param>
 /// <param name="innerException">The inner exception object.</param>
 /// <param name="response">The <see cref="T:Microsoft.OData.Client.QueryOperationResponse" /> object.</param>
 public DataServiceQueryException(string message, Exception innerException, QueryOperationResponse response)
     : base(message, innerException)
 {
     this.response = response;
 }
Beispiel #19
0
        private static long GetTotalCount(QueryOperationResponse<V2FeedPackage> response, PackageMetadata[] packageMetadatas)
        {
            // TotalCount may be missing. When this is the case, we default
            // to the number of package meta's we got.

            try
            {
                return response.TotalCount;
            }
            catch (InvalidOperationException)
            {
                return packageMetadatas.Length;
            }
        }