/// <summary> /// Wraps query Execution action sync or async and verifies exceptions /// </summary> /// <param name="continuation">Continuation token to register success or failure to</param> /// <param name="expectedValue">Expected Value of the Query</param> /// <param name="dataContext">Content the Query is executed on</param> /// <param name="clientExpectedError">Expected Error the query is executed on</param> /// <param name="executeAction">Action to execute specified query</param> private void ExecuteQueryAction( IAsyncContinuation continuation, QueryValue expectedValue, DataServiceContext dataContext, ExpectedClientErrorBaseline clientExpectedError, Action <List <object>, IAsyncContinuation> executeAction) { ExceptionUtilities.CheckAllRequiredDependencies(this); this.clientExceptionVerified = false; continuation = continuation.OnFail(() => this.expressionQueue.Clear()); continuation = continuation.OnContinue(() => this.expressionQueue.TryDequeue()); AsyncHelpers.HandleException <Exception>( continuation, exceptionHandlerContinuation => { List <object> entityPayloads = new List <object>(); if (this.DataProviderSettings.UsePayloadDrivenVerification && clientExpectedError == null) { #if !WINDOWS_PHONE this.HttpTracker.RegisterHandler(dataContext, this.BuildBaselineValueFromResponse); exceptionHandlerContinuation = AsyncHelpers.OnContinueOrFail( exceptionHandlerContinuation, () => this.HttpTracker.UnregisterHandler(dataContext, this.BuildBaselineValueFromResponse, !this.clientExceptionVerified)); #endif if (dataContext != this.currentContext) { this.currentContext = dataContext; } } exceptionHandlerContinuation = exceptionHandlerContinuation.OnContinue( () => { if (clientExpectedError != null && !this.clientExceptionVerified) { continuation.Fail(new TaupoInvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Expected a client exception with resource id '{0}' and of exception type '{1}'.", clientExpectedError.ExpectedExceptionMessage.ResourceIdentifier, clientExpectedError.ExpectedExceptionType.FullName))); } }); executeAction(entityPayloads, exceptionHandlerContinuation); }, e => { if (this.DataProviderSettings.UsePayloadDrivenVerification && this.baselineQueryValue != null && this.baselineQueryValue.EvaluationError != null) { ExceptionUtilities.Assert(e.GetType() == typeof(DataServiceQueryException), "Expected DataServiceQueryException, received " + e.GetType().ToString()); this.Logger.WriteLine(LogLevel.Verbose, this.baselineQueryValue.EvaluationError.ToString()); } else { this.CompareClientOrEvaluationException(expectedValue, clientExpectedError, e); } continuation.Continue(); }); }
/// <summary> /// Constructs an OData request body using the given settings /// </summary> /// <param name="contentType">The content type of the body</param> /// <param name="uri">The request uri</param> /// <param name="rootElement">The root payload element</param> /// <returns>An OData request body</returns> public ODataPayloadBody BuildBody(string contentType, ODataUri uri, ODataPayloadElement rootElement) { ExceptionUtilities.CheckArgumentNotNull(contentType, "contentType"); ExceptionUtilities.CheckArgumentNotNull(rootElement, "rootElement"); ExceptionUtilities.CheckAllRequiredDependencies(this); string charset = HttpUtilities.GetContentTypeCharsetOrNull(contentType); byte[] serializedBody = null; var batchRequestPayload = rootElement as BatchRequestPayload; if (batchRequestPayload != null) { string boundary; ExceptionUtilities.Assert(HttpUtilities.TryGetContentTypeParameter(contentType, HttpHeaders.Boundary, out boundary), "Could not find boundary in content type for batch payload. Content type was: '{0}'", contentType); serializedBody = this.BatchSerializer.SerializeBatchPayload(batchRequestPayload, boundary, charset); } else { IProtocolFormatStrategy strategy = this.FormatSelector.GetStrategy(contentType, uri); ExceptionUtilities.CheckObjectNotNull(strategy, "Strategy selector did not return a strategy for content type '{0}'", contentType); IPayloadSerializer serializer = strategy.GetSerializer(); ExceptionUtilities.CheckObjectNotNull(serializer, "Strategy returned a null serializer"); serializedBody = serializer.SerializeToBinary(rootElement, charset); } return(new ODataPayloadBody(serializedBody, rootElement)); }
/// <summary> /// Compares the ClientExpectedException to the provided exception and verifies the exception is correct /// </summary> /// <param name="expectedClientException">Expected Client Exception</param> /// <param name="exception">Actual Exception</param> public void Compare(ExpectedClientErrorBaseline expectedClientException, Exception exception) { ExceptionUtilities.CheckAllRequiredDependencies(this); if (expectedClientException == null) { string exceptionMessage = null; if (exception != null) { exceptionMessage = exception.ToString(); } this.Assert.IsNull(exception, "Expected to not recieve an exception:" + exceptionMessage); return; } this.Assert.IsNotNull(exception, "Expected Exception to not be null"); this.Assert.AreEqual(expectedClientException.ExpectedExceptionType, exception.GetType(), string.Format(CultureInfo.InvariantCulture, "ExceptionType is not equal, receieved the following exception: {0}", exception.ToString())); if (expectedClientException.HasServerSpecificExpectedMessage) { if (this.ShouldVerifyServerMessageInClientException) { this.Assert.IsNotNull(exception.InnerException, "Expected Inner Exception to contain ODataError"); byte[] byteArrPayload = HttpUtilities.DefaultEncoding.GetBytes(exception.InnerException.Message); ODataErrorPayload errorPayload = this.ProtocolFormatStrategySelector.DeserializeAndCast <ODataErrorPayload>(null, MimeTypes.ApplicationXml, byteArrPayload); expectedClientException.ExpectedExceptionMessage.VerifyMatch(this.systemDataServicesVerifier, errorPayload.Message, true); } } else { expectedClientException.ExpectedExceptionMessage.VerifyMatch(this.systemDataServicesClientVerifier, exception.Message, true); } }
/// <summary> /// Verifies the data service response. /// </summary> /// <param name="responseData">The expected data for the response.</param> /// <param name="response">The response to verify.</param> /// <param name="cachedOperationsFromResponse">The individual operation responses, pre-enumerated and cached</param> /// <exception cref="TaupoNotSupportedException"> /// When exception is expected in the response data /// </exception> public void VerifyDataServiceResponse(DataServiceResponseData responseData, DataServiceResponse response, IList <OperationResponse> cachedOperationsFromResponse) { ExceptionUtilities.CheckArgumentNotNull(responseData, "responseData"); ExceptionUtilities.CheckArgumentNotNull(response, "response"); ExceptionUtilities.CheckArgumentNotNull(cachedOperationsFromResponse, "cachedOperationsFromResponse"); ExceptionUtilities.CheckAllRequiredDependencies(this); this.Assert.AreEqual(responseData.IsBatchResponse, response.IsBatchResponse, "Verifying if it's a batch response."); this.Assert.AreEqual(responseData.BatchStatusCode, response.BatchStatusCode, "Verifying batch status code."); //// No batch headers verification //// Note: verifying order of operation responses as well as the content. this.Assert.AreEqual(responseData.Count, cachedOperationsFromResponse.Count, "Unexpected number of operation responses in data service response"); for (int responseOrder = 0; responseOrder < responseData.Count; responseOrder++) { var operationResponseData = responseData[responseOrder]; var currentResponse = cachedOperationsFromResponse[responseOrder]; ChangeOperationResponseData changeResponseData = operationResponseData as ChangeOperationResponseData; if (changeResponseData != null) { ChangeOperationResponse changeResponse = currentResponse as ChangeOperationResponse; this.Assert.IsNotNull(changeResponse, GetVerificationFailureMessage(responseOrder, "Unexpected type of the operation response.\r\nExpected: {0}\r\nActual: {1}", typeof(ChangeOperationResponse).FullName, currentResponse)); this.VerifyChangeOperationResponse(changeResponseData, changeResponse, responseOrder); } else { throw new TaupoNotSupportedException( GetVerificationFailureMessage(responseOrder, "Verification for the operation response data of type '{0}' is not supported by this verifier.", operationResponseData.GetType().FullName)); } } }
/// <summary> /// Tries to convert the value if it is spatial. Adds OData-specific fields to GeoJSON microformat. /// </summary> /// <param name="value">The value that might be spatial.</param> /// <param name="jsonObject">The converted json object.</param> /// <returns>Whether the value was spatial and could be converted</returns> public bool TryConvertIfSpatial(PrimitiveValue value, out JsonObject jsonObject) { ExceptionUtilities.CheckArgumentNotNull(value, "value"); ExceptionUtilities.CheckAllRequiredDependencies(this); IDictionary <string, object> dictionary; if (this.GeoJsonFormatter.TryConvert(value.ClrValue, out dictionary)) { jsonObject = this.DictionaryConverter.Convert(dictionary); if (value.FullTypeName != null) { jsonObject.Insert(0, new JsonProperty(ODataConstants.JsonMetadataPropertyName, new JsonObject() { new JsonProperty(ODataConstants.TypeAttributeName, new JsonPrimitiveValue(value.FullTypeName)) })); } return(true); } jsonObject = null; return(false); }
/// <summary> /// Verifies the query generated by the PHPCodeGenerator /// </summary> /// <param name="expression">The expression used to verify the query</param> public void Verify(QueryExpression expression) { ExceptionUtilities.CheckArgumentNotNull(expression, "expression"); ExceptionUtilities.CheckAllRequiredDependencies(this); if (this.DataServicePhpFileName == null) { this.DataServicePhpFileName = this.PhpWorkingDirectory + "\\" + this.Service.ConceptualModel.EntityContainers.First().Name + ".php"; } if (!File.Exists(this.DataServicePhpFileName)) { string commandToGenerateConatinerClass = string.Format(CultureInfo.InvariantCulture, "{0}{1} /ups=no", "PHPDataSvcUtil.php /uri=", this.Service.ServiceUri.AbsoluteUri); this.CodeExecutor.ExecuteCode(commandToGenerateConatinerClass); } var fileName = string.Format(CultureInfo.InvariantCulture, "{0}{1}.php", DateTime.Now.Day.ToString(CultureInfo.InvariantCulture), DateTime.Now.TimeOfDay.ToString().Replace(':', '.')); string phpCode = this.CodeGenerator.GenerateCode(expression); #if !SILVERLIGHT File.WriteAllText(string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", this.PhpWorkingDirectory, fileName), phpCode); #endif string result = this.CodeExecutor.ExecuteCode(fileName); if (!result.Equals("Passed")) { Logger.WriteLine(LogLevel.Verbose, CultureInfo.InvariantCulture, "Execution of the Php query failed"); throw new DataComparisonException(string.Format(CultureInfo.InvariantCulture, "The Php query failed\n Generated Php Code :\n{0}\n Error : {1}", phpCode, result)); } }
/// <summary> /// Creates structural data services for the entity model. /// </summary> /// <param name="modelSchema">Entity model schema.</param> /// <returns> /// An <see cref="IEntityModelConceptualDataServices"/>. /// </returns> public IEntityModelConceptualDataServices CreateConceptualDataServices(EntityModelSchema modelSchema) { ExceptionUtilities.CheckArgumentNotNull(modelSchema, "modelSchema"); ExceptionUtilities.CheckAllRequiredDependencies(this); try { this.structuralGenerators = new ConceptualDataServices(); foreach (ComplexType complexType in modelSchema.ComplexTypes) { this.GetOrCreateAndRegisterStructuralDataGeneratorForComplexType(complexType); } foreach (EntityContainer entityContainer in modelSchema.EntityContainers) { foreach (var entitySet in entityContainer.EntitySets) { this.CreateAndRegisterStructuralDataGeneratorsForEntitySet(entitySet); } } return(this.structuralGenerators); } finally { this.structuralGenerators = null; } }
/// <summary> /// Generates data for members for which data generators are added. /// </summary> /// <returns>Key-value pairs where key is a member path and value is a member value.</returns> /// <remarks>If there is a loop in the data generators, it will randomly decide how deep to recurse.</remarks> public override IList <NamedValue> GenerateData() { ExceptionUtilities.CheckAllRequiredDependencies(this); if (this.currentRecursionDepth > this.recursionLimit) { // TODO: should this be null instead? return(new List <NamedValue>()); } if (this.currentRecursionDepth == 0) { this.recursionLimit = this.random.Next(MaxRecursionLimit); } try { this.currentRecursionDepth++; var result = new List <NamedValue>(); foreach (string currentMemberPath in this.membersDataGenerators.Keys) { IDataGenerator memberDataGenerator = this.GetMemberDataGenerator(currentMemberPath); var memberData = memberDataGenerator.GenerateData(); result.AddMemberData(currentMemberPath, memberData); } return(result); } finally { this.currentRecursionDepth--; } }
/// <summary> /// Generates a code expression to initialize an object. /// </summary> /// <param name="value">The object to generate an expression for.</param> /// <param name="initializationExpression">An initialize expression for the specified object.</param> /// <returns>True if initialization expression was generated, false otherwise.</returns> public bool TryGenerateInitialization(object value, out CodeExpression initializationExpression) { initializationExpression = null; var spatialInstance = value as ISpatial; if (spatialInstance == null) { return(false); } if (!spatialInstance.IsEmpty) { if (TryCallGeographyPointCreate(spatialInstance, out initializationExpression) || TryCallGeometryPointCreate(spatialInstance, out initializationExpression)) { return(true); } } ExceptionUtilities.CheckAllRequiredDependencies(this); string asWellKnownText = this.WellKnownTextFormatter.Convert(spatialInstance); //// WellKnownTextSqlFormatter.Create().Parse<Geography>(new StringReader("<WKT>")); initializationExpression = Code.Type(typeof(WellKnownTextSqlFormatter).FullName) .Call("Create") .Call( "Read", new[] { Code.TypeRef(spatialInstance.GetType().GetBaseType()) }, Code.New(typeof(StringReader), Code.Primitive(asWellKnownText))); return(true); }
/// <summary> /// Creates a default wrapped data service context without registering SendingRequest(2) event. /// </summary> /// <param name="scope">DataServiceContext TrackingScope</param> /// <param name="dataServiceContextType">The type of the DataServiceContext instance to be created</param> /// <param name="serviceBaseUri">service BaseUri</param> /// <returns>Wrapped DataServiceContext</returns> public WrappedDataServiceContext CreateContextWithoutSendingRequest(IWrapperScope scope, Type dataServiceContextType, Uri serviceBaseUri) { ExceptionUtilities.CheckAllRequiredDependencies(this); ExceptionUtilities.CheckArgumentNotNull(scope, "scope"); ExceptionUtilities.CheckArgumentNotNull(dataServiceContextType, "dataServiceContextType"); ExceptionUtilities.Assert(typeof(DataServiceContext).IsAssignableFrom(dataServiceContextType), "Given type did not derive from DataServiceContext"); WrappedDataServiceContext ctx = scope.CreateDataServiceContext(dataServiceContextType, serviceBaseUri, this.MaxProtocolVersion); DataServiceContext context = ctx.Product as DataServiceContext; this.SetCredentials(context); this.authenticationHeaders = this.AuthenticationProvider.GetAuthenticationHeaders(); this.SetAcceptAndContentTypeHeaders(context); //ctx.UndeclaredPropertyBehavior = this.UndeclaredPropertyBehavior; this.FormatApplier.Apply(context); if (this.FormatApplier.IsUsingContentType(MimeTypes.ApplicationJsonLight)) { // Setup the resolver. context.ResolveType = (name) => dataServiceContextType.Assembly.GetType(name); context.ResolveName = (type) => type.Namespace + "." + type.Name; } #if !WINDOWS_PHONE if (this.EntitySetResolver != null) { ctx.ResolveEntitySet = this.EntitySetResolver.ResolveEntitySetUri; } #endif return(ctx); }
/// <summary> /// Builds the QueryOptions /// </summary> /// <param name="expression">The expression to convert</param> /// <returns>returns the query option for the PHP client library</returns> public PhpQueryOptions Convert(QueryExpression expression) { ExceptionUtilities.CheckAllRequiredDependencies(this); var odataUri = this.ExpressionConverter.ComputeUri(expression); var options = new PhpQueryOptions() { Filter = odataUri.Filter, OrderBy = odataUri.OrderBy, Count = odataUri.IsCount(), InlineCount = odataUri.InlineCount == QueryOptions.InlineCountAllPages, }; string inlineCount; if (odataUri.CustomQueryOptions.TryGetValue(QueryOptions.InlineCount, out inlineCount)) { options.InlineCount = inlineCount == QueryOptions.InlineCountAllPages; } if (odataUri.Skip.HasValue) { options.Skip = odataUri.Skip.Value.ToString(CultureInfo.InvariantCulture); } if (odataUri.Top.HasValue) { options.Top = odataUri.Top.Value.ToString(CultureInfo.InvariantCulture); } if (odataUri.ExpandSegments.Count > 0) { options.Expand = this.UriToStringConverter.ConcatenateSegments(odataUri.ExpandSegments); } if (odataUri.SelectSegments.Count > 0) { options.Select = this.UriToStringConverter.ConcatenateSegments(odataUri.SelectSegments); } EntitySet expectedEntitySet; if (odataUri.TryGetExpectedEntitySet(out expectedEntitySet)) { options.EntityContainer = expectedEntitySet.Container.Name; options.EntitySet = expectedEntitySet.Name; } if (odataUri.IsEntity()) { var key = odataUri.Segments.OfType <KeyExpressionSegment>().LastOrDefault(); if (key != null) { options.PrimaryKey = this.UriToStringConverter.ConvertToString(key); } } return(options); }
protected QueryExpression ResolveExpressionAndGetResponse(QueryExpression expression, out Contracts.OData.ODataRequest request, out Contracts.OData.ODataResponse response) { ExceptionUtilities.CheckArgumentNotNull(expression, "expression"); ExceptionUtilities.CheckAllRequiredDependencies(this); expression = this.QueryResolver.Resolve(expression); var uri = this.ProtocolTestServices.QueryToUriConverter.GenerateUriFromQuery(expression, this.ServiceRoot); var headers = new HttpHeaderCollection(); headers.Accept = DetermineAcceptType(uri, this.DefaultAcceptType); if (this.DataServiceVersion != DataServiceProtocolVersion.Unspecified) { headers.DataServiceVersion = this.DataServiceVersion.ConvertToHeaderFormat(); } if (this.MaxDataServiceVersion != DataServiceProtocolVersion.Unspecified) { headers.MaxDataServiceVersion = this.MaxDataServiceVersion.ConvertToHeaderFormat(); } SetupProtocolRequest(expression, this.ProtocolTestServices.RequestManager, this.QueryToODataPayloadConverter, uri, headers, this.GetActionContentType(), out request); response = this.GetResponse(expression, request); return(expression); }
/// <summary> /// Returns a fixup specific to the dictionary provider /// </summary> /// <returns>The fixup for the dictionary provider</returns> public override IEntityModelFixup GetProviderSpecificModelFixup() { ExceptionUtilities.CheckAllRequiredDependencies(this); var metadataFixup = this.TypingStrategy.GetModelFixup(); return(new CompositeEntityModelFixup(metadataFixup, this.CollectionTypesFixup, this.NullableDataTypesFixup, this.AssociationsFixup, this.MakeNamesUniqueFixup)); }
/// <summary> /// Builds the workspace asynchronously. /// </summary> /// <param name="workspace">The workspace to populate.</param> /// <param name="continuation">The continuation to invoke at the end of the build operation.</param> public void BuildWorkspaceAsync(AstoriaWorkspace workspace, IAsyncContinuation continuation) { ExceptionUtilities.CheckAllRequiredDependencies(this); this.CurrentWorkspace = workspace; this.Logger.WriteLine(LogLevel.Verbose, "Initializing model..."); this.InitializeModel(workspace); #if WIN8 this.clientLayerAssembly = typeof(DefaultNamespace.DefaultContainer).GetAssembly(); this.dataServiceContextType = this.clientLayerAssembly.GetType(this.DataServiceContextTypeName); ExceptionUtilities.CheckObjectNotNull(dataServiceContextType, "The DataServiceContext type was not found."); #endif this.Logger.WriteLine(LogLevel.Verbose, "Building workspace asynchronously."); AsyncHelpers.RunActionSequence( continuation, this.BuildDataService, this.UpdateEntityModel, this.InitializeResourceStringVerifiers, this.GenerateClientLayerCode, this.CompileClientLayerCode, this.BuildEntitySetResolver, this.RegisterServiceUri, this.BuildEdmModel, this.DownloadData, this.FindDataServiceContext); }
/// <summary> /// Initializes the converter /// </summary> internal void Initialize() { if (!this.initialized) { ExceptionUtilities.CheckAllRequiredDependencies(this); this.initialized = true; var types = EdmDataTypes.GetAllPrimitiveTypes(EdmVersion.Latest).ToList(); foreach (PrimitiveDataType type in types) { string edmTypeName = EdmDataTypes.GetEdmFullName(type); Type clrType; var spatialType = type as SpatialDataType; if (spatialType != null) { clrType = this.SpatialResolver.GetClrType(spatialType); } else { clrType = type.GetFacetValue <PrimitiveClrTypeFacet, Type>(null); } ExceptionUtilities.CheckObjectNotNull(clrType, "Could not determine clr type for edm data type: '{0}", edmTypeName); this.clrToEdm[clrType] = type; this.edmNameToClr[edmTypeName] = clrType; } } }
/// <summary> /// Converts the given uri into a string /// </summary> /// <param name="uri">The uri to convert</param> /// <returns>The converted uri string</returns> public string ConvertToString(ODataUri uri) { ExceptionUtilities.CheckArgumentNotNull(uri, "uri"); ExceptionUtilities.CheckAllRequiredDependencies(this); return(this.ConcatenateSegmentsAndQueryOptions(uri.Segments, this.GetSortedQueryOptions(uri))); }
/// <summary> /// Synchronizes the data for the entity with the given set name and key values /// </summary> /// <param name="continuation">The asynchronous continuation to report failure/completion on</param> /// <param name="entitySetName">The entity set the entity belongs to</param> /// <param name="keyValues">The key values of the entity</param> public void SynchronizeEntityInstanceGraph(IAsyncContinuation continuation, string entitySetName, IEnumerable <NamedValue> keyValues) { ExceptionUtilities.CheckArgumentNotNull(continuation, "continuation"); ExceptionUtilities.CheckArgumentNotNull(entitySetName, "entitySetName"); ExceptionUtilities.CheckCollectionNotEmpty(keyValues, "keyValues"); ExceptionUtilities.CheckAllRequiredDependencies(this); this.OracleServiceClient.BeginGetEntity( entitySetName, keyValues.Select(v => new SerializableNamedValue() { Name = v.Name, Value = v.Value }).ToList(), result => AsyncHelpers.CatchErrors( continuation, delegate { string error; var entity = this.OracleServiceClient.EndGetEntity(out error, result); if (error != null) { continuation.Fail(new Exception(error)); return; } this.UnderlyingSynchronizer.SynchronizeEntityInstanceGraph(entity); continuation.Continue(); }), null); }
/// <summary> /// Verifies the given OData request/response pair /// </summary> /// <param name="request">The request to verify</param> /// <param name="response">The response to verify</param> public virtual void Verify(ODataRequest request, ODataResponse response) { ExceptionUtilities.CheckArgumentNotNull(request, "request"); ExceptionUtilities.CheckArgumentNotNull(response, "response"); ExceptionUtilities.CheckAllRequiredDependencies(this); ExceptionUtilities.CheckObjectNotNull(this.Logger, "Cannot run verifier without logger"); }
/// <summary> /// Synchronizes the data for the entity set with the given name /// </summary> /// <param name="continuation">The asynchronous continuation to report failure/completion on</param> /// <param name="entitySetName">The name of the entity set to refresh</param> public void SynchronizeEntireEntitySet(IAsyncContinuation continuation, string entitySetName) { ExceptionUtilities.CheckArgumentNotNull(continuation, "continuation"); ExceptionUtilities.CheckArgumentNotNull(entitySetName, "entitySetName"); ExceptionUtilities.CheckAllRequiredDependencies(this); this.OracleServiceClient.BeginGetEntitySet( entitySetName, result => AsyncHelpers.CatchErrors( continuation, delegate { string error; var entities = this.OracleServiceClient.EndGetEntitySet(out error, result); if (error != null) { continuation.Fail(new Exception(error)); return; } this.UnderlyingSynchronizer.SynchronizeEntireEntitySet(entitySetName, entities); continuation.Continue(); }), null); }
public virtual bool TryDeserializeErrorPayload(byte[] serialized, string encodingName, out ODataPayloadElement errorPayload) { ExceptionUtilities.CheckArgumentNotNull(serialized, "serialized"); ExceptionUtilities.CheckAllRequiredDependencies(this); // get the encoding based on the given encoding name var encoding = HttpUtilities.GetEncodingOrDefault(encodingName); using (StreamReader streamReader = new StreamReader(new MemoryStream(serialized), encoding)) { using (XmlReader reader = XmlReader.Create(streamReader)) { bool foundErrorPayload = false; while (reader.Read()) { if (reader.IsStartElement(ODataConstants.ErrorElementName, ODataConstants.DataServicesMetadataNamespaceName)) { foundErrorPayload = true; break; } } if (!foundErrorPayload) { errorPayload = null; return(false); } errorPayload = this.ParseErrorFragment(reader); return(true); } } }
/// <summary> /// Initializes this object (after construction and property assignment but before use). /// </summary> public void Initialize() { if (this.random == null) { ExceptionUtilities.CheckAllRequiredDependencies(this); this.Logger.WriteLine(LogLevel.Verbose, "Initializing random number generator with seed: {0}", this.InitialSeed); this.random = new Random(this.InitialSeed); } }
public ODataResponse GetResponse(ODataRequest request) { ExceptionUtilities.CheckArgumentNotNull(request, "request"); ExceptionUtilities.CheckAllRequiredDependencies(this); HttpResponseData underlyingResponse = this.HttpImplementation.GetResponse(request); return(this.BuildResponse(request, underlyingResponse)); }
/// <summary> /// Build QueryValue from query expresion and server response. /// </summary> /// <param name="expression">The query expresion of client request.</param> /// <param name="response">The http response from the server.</param> /// <returns>The baseline QueryValue converted from payload.</returns> public QueryValue BuildQueryValue(QueryExpression expression, HttpResponseData response) { ExceptionUtilities.CheckArgumentNotNull(expression, "expression"); ExceptionUtilities.CheckArgumentNotNull(response, "response"); ExceptionUtilities.CheckAllRequiredDependencies(this); // get type resolver and payload deserializer. var typeResolver = new LinqToAstoriaTypeResolutionVisitor(this.TypeLibrary); // if the response has an error if (response.StatusCode != HttpStatusCode.OK) { return(expression.ExpressionType.CreateErrorValue(new QueryError("Response from server has an error!"))); } string contentType; ExceptionUtilities.Assert(response.Headers.TryGetValue(HttpHeaders.ContentType, out contentType), "Cannot get content type from response."); var deserializer = this.StrategySelector.GetStrategy(contentType, null).GetDeserializer(); this.currentExpression = expression; var expressionForUri = this.ClientSideProjectionReplacer.ReplaceClientSideProjections(expression); ODataUri queryUri = this.QueryToODataUriConverter.ComputeUri(expressionForUri); queryUri.Segments.Insert(0, ODataUriBuilder.Root(this.Workspace.ServiceUri)); // deserialize byte array payload to OData payload element. ODataPayloadElement payload = this.DeserializePayloadData(deserializer, response, queryUri); this.PayloadElementMetadataResolver.ResolveMetadata(payload, queryUri); var normalizer = this.StrategySelector.GetStrategy(contentType, null).GetPayloadNormalizer(); payload = normalizer.Normalize(payload); if (this.ShouldUsePayloadDrivenVerification(queryUri)) { return(this.BuildQueryValueForActionResponse(payload, expression.ExpressionType)); } else { // build query data set from payload for evaluation. It's a different data set from the initial one of current workspace. IQueryDataSet dataSet = this.BuildQueryDataSet(payload); // filter the query and resolve types. Need to remove expressions such as $top, $skip, $orderby, $filter because the returned payload is already the result of performing these expressions. // need to keep root expression, key expression, $expand and $select to have correct anonymous type. var filteredQuery = this.FilterExpression(expression); filteredQuery = typeResolver.ResolveTypes(filteredQuery, this.EvaluationStrategy); // replace the evaluator's query-data-set with the one generated in the payload using (this.Evaluator.WithTemporaryDataSet(dataSet)) { return(this.Evaluator.Evaluate(filteredQuery)); } } }
/// <summary> /// Builds the workspace. /// </summary> /// <returns> /// Returns instance of a class which derives from <see cref="Workspace"/>. The instance is not fully /// initialized until the current method (Init() or variation) completes asynchronously. /// </returns> public AstoriaWorkspace BuildWorkspace() { ExceptionUtilities.CheckAllRequiredDependencies(this); var workspace = new AstoriaWorkspace(this); AsyncExecutionContext.EnqueueAsynchronousAction(cb => this.BuildWorkspaceAsync(workspace, cb)); return(workspace); }
/// <summary> /// Prints an entity graph /// </summary> /// <param name="rootElement">The root element of the payload</param> /// <returns> an entity graph to visualize</returns> public string PrettyPrint(ODataPayloadElement rootElement) { ExceptionUtilities.CheckArgumentNotNull(rootElement, "rootElement"); ExceptionUtilities.CheckAllRequiredDependencies(this); this.builder = new StringBuilder(); this.currentDepth = 0; this.Recurse(rootElement); return(this.builder.ToString()); }
/// <summary> /// Synchronizes an entity and its related subgraph given the output from a data oracle /// </summary> /// <param name="entity">The entity returned from the oracle</param> public void SynchronizeEntityInstanceGraph(SerializableEntity entity) { ExceptionUtilities.CheckAllRequiredDependencies(this); // reset the cache this.synchronizationCache.Clear(); // this will add a item or synchronizing an existing one this.FindAndSynchronizeEntity(entity); }
/// <summary> /// Resolves service method body. /// </summary> /// <param name="serviceMethod">the service method</param> public void ResolveServiceMethodBody(Function serviceMethod) { ExceptionUtilities.CheckAllRequiredDependencies(this); FunctionBodyAnnotation body = serviceMethod.Annotations.OfType <FunctionBodyAnnotation>().SingleOrDefault(); if (body != default(FunctionBodyAnnotation) && body.FunctionBodyGenerator != null) { body.FunctionBody = body.FunctionBodyGenerator(serviceMethod.Model); } }
/// <summary> /// Returns a composite verifier with all standard verifiers attached /// </summary> /// <param name="expectedStatusCode">The expected status code of the response</param> /// <returns>A composite verifier</returns> public IResponseVerifier GetStandardVerifier(HttpStatusCode expectedStatusCode) { ExceptionUtilities.CheckObjectNotNull(this.BuildStandardVerifierFunc, "Delegate for building standard verifier cannot be null"); ExceptionUtilities.CheckAllRequiredDependencies(this); var verifier = this.BuildStandardVerifierFunc(expectedStatusCode); this.Injector.InjectDependenciesInto(verifier); verifier.Verifiers.ForEach(v => this.Injector.InjectDependenciesInto(v)); return(verifier); }
/// <summary> /// Resolves Linq expression. /// </summary> /// <param name="expression">Expression to resolve.</param> /// <returns>Resolved expression.</returns> public QueryExpression Resolve(QueryExpression expression) { ExceptionUtilities.CheckArgumentNotNull(expression, "expression"); ExceptionUtilities.CheckAllRequiredDependencies(this); var resolvedExpression = this.customFunctionResolutionVisitor.ResolveCustomFunctions(expression, this.QueryEvaluationStrategy); resolvedExpression = this.parameterNameResolutionVisitor.ResolveParameterNames(expression); resolvedExpression = this.typeResolver.ResolveTypes(resolvedExpression, this.QueryEvaluationStrategy); return(resolvedExpression); }
/// <summary> /// Prints an entity graph /// </summary> /// <param name="rootQueryValue">The root element of the Query</param> /// <param name="maximumPayloadDepth">Indicates how far within the payload graph to traverse.</param> /// <returns>Returns a string to help visualize the Entity graph</returns> public string PrettyPrint(QueryValue rootQueryValue, int maximumPayloadDepth) { this.maxDepth = maximumPayloadDepth; ExceptionUtilities.CheckArgumentNotNull(rootQueryValue, "rootQueryValue"); ExceptionUtilities.CheckAllRequiredDependencies(this); this.builder = new StringBuilder(); this.currentDepth = 0; rootQueryValue.Accept(this); return(this.builder.ToString()); }