/// <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(); }); }
private void CompileClientLayerCode(IAsyncContinuation continuation) { if (this.SkipClientCodeGeneration) { continuation.Continue(); return; } this.Logger.WriteLine(LogLevel.Verbose, "Compiling Client Source Code...."); var languageSpecificReferences = GetClientReferenceAssemblies(this.CurrentWorkspace.ConceptualModel, this.Language); string assemblyBaseName = "DataServiceClient" + Guid.NewGuid().ToString("N"); this.Language.CompileAssemblyAsync( assemblyBaseName, new[] { this.clientLayerCode }, languageSpecificReferences.ToArray(), (asm, error) => { if (error != null) { continuation.Fail(error); return; } this.CurrentWorkspace.Assemblies.Add(new FileContents <Assembly>(assemblyBaseName + ".dll", asm)); continuation.Continue(); }); }
public static void CatchErrors(this IAsyncContinuation continuation, Action action, Action final) { #if SILVERLIGHT && !WIN8 Deployment.Current.Dispatcher.BeginInvoke(() => { #endif try { action(); } catch (Exception ex) { if (ExceptionUtilities.IsCatchable(ex)) { continuation.Fail(ex); } } finally { if (final != null) { CatchErrors(continuation, final); } } #if SILVERLIGHT && !WIN8 }); #endif }
/// <summary> /// Call's the product API for save changes /// </summary> /// <param name="continuation">The async continuation</param> protected virtual void CallProductApi(IAsyncContinuation continuation) { this.SetupBeforeProductCall(); if (this.Asynchronous) { continuation = continuation.OnContinueOrFail(this.CleanupAfterProductCall); // the product API continuation AsyncCallback productApiCallback = result => { AsyncHelpers.CatchErrors( continuation, () => { this.Assert.AreSame(this.State, result.AsyncState, "AsyncState was incorrect"); this.State.Response = this.Input.Context.EndSaveChanges(result); this.OnProductCallSuccess(); continuation.Continue(); }); }; // call one of the two BeginSaveChanges overloads based on whether there was a SaveChangesOptions value given if (this.Input.Options.HasValue) { this.Input.Context.BeginSaveChanges(this.Input.Options.Value.ToProductEnum(), productApiCallback, this.State); } else { this.Input.Context.BeginSaveChanges(productApiCallback, this.State); } } else { #if SILVERLIGHT throw new TaupoNotSupportedException("Silverlight does not support synchronous operations"); #else // in the sync case we can use a simple try-finally block rather than wrapping the continuation try { // call one of the two SaveChanges overloads based on whether there was a SaveChangesOptions value given if (this.Input.Options.HasValue) { this.State.Response = this.Input.Context.SaveChanges(this.Input.Options.Value.ToProductEnum()); } else { this.State.Response = this.Input.Context.SaveChanges(); } } finally { this.CleanupAfterProductCall(); } this.OnProductCallSuccess(); continuation.Continue(); #endif } }
/// <summary> /// Builds the Edm Model /// </summary> /// <param name="continuation">The async continuation</param> protected override void BuildEdmModel(IAsyncContinuation continuation) { if (this.SkipEdmModelDownload) { continuation.Continue(); return; } var serviceMetadataUri = new Uri(this.CurrentWorkspace.ServiceUri.AbsoluteUri + "/$metadata", UriKind.Absolute); this.Logger.WriteLine(LogLevel.Trace, "Retrieve metadata of service: {0}", serviceMetadataUri.AbsoluteUri); #if SILVERLIGHT var httpWebRequest = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(serviceMetadataUri); #else var httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(serviceMetadataUri); #endif httpWebRequest.Accept = MimeTypes.ApplicationXml; httpWebRequest.BeginGetResponse( (asyncResult) => { AsyncHelpers.CatchErrors( continuation, () => { var webResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult); ExceptionUtilities.Assert(webResponse.StatusCode == HttpStatusCode.OK, "Cannot query $metadata getting non OK status code '{0}'", webResponse.StatusCode); var stream = webResponse.GetResponseStream(); this.CurrentWorkspace.EdmModel = GetEdmModelFromEdmxStream(stream); continuation.Continue(); }); }, null); }
/// <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> /// 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); }
private static void SendStreamValueToServer(IAsyncContinuation continuation, bool async, string editLinkString, string contentType, string etag, byte[] streamData) { HttpWebRequest streamPutRequest; streamPutRequest = (HttpWebRequest)HttpWebRequest.Create(editLinkString); // using verb-tunneling streamPutRequest.Method = "POST"; streamPutRequest.Headers[HttpHeaders.HttpMethod] = HttpVerb.Put.ToHttpMethod(); streamPutRequest.ContentType = contentType; if (etag != null) { streamPutRequest.Headers[HttpHeaders.IfMatch] = etag; } streamPutRequest.AllowWriteStreamBuffering = false; streamPutRequest.ContentLength = streamData.Length; streamPutRequest.BeginGetRequestStream( (requestStreamResult) => { var requestStream = streamPutRequest.EndGetRequestStream(requestStreamResult); requestStream.Write(streamData, 0, streamData.Length); requestStream.Close(); streamPutRequest.GetResponse <HttpWebResponse>( async, continuation, (streamResponse) => { ExceptionUtilities.Assert(streamResponse.StatusCode == HttpStatusCode.NoContent, "Named stream update failed"); continuation.Continue(); }); }, null); }
/// <summary> /// Invokes either the given sync or async method call based on the given parameter /// Note: Will not call .Continue on the continuation, ensure that this is done in the completion delegate /// </summary> /// <typeparam name="TReturn">The return type of the method</typeparam> /// <param name="continuation">The async continuation</param> /// <param name="async">A value indicating whether to use the sync or async API</param> /// <param name="syncCall">The sync API call</param> /// <param name="beginAsyncCall">The 'begin' part of the async API</param> /// <param name="endAsyncCall">The 'end' part of the async API</param> /// <param name="onCompletion">Delegate to call with the method's return value</param> public static void InvokeSyncOrAsyncMethodCall <TReturn>(this IAsyncContinuation continuation, bool async, Func <TReturn> syncCall, Action <AsyncCallback> beginAsyncCall, Func <IAsyncResult, TReturn> endAsyncCall, Action <TReturn> onCompletion) { ExceptionUtilities.CheckArgumentNotNull(continuation, "continuation"); ExceptionUtilities.CheckArgumentNotNull(syncCall, "syncCall"); ExceptionUtilities.CheckArgumentNotNull(beginAsyncCall, "beginAsyncCall"); ExceptionUtilities.CheckArgumentNotNull(endAsyncCall, "endAsyncCall"); ExceptionUtilities.CheckArgumentNotNull(onCompletion, "onCompletion"); if (async) { beginAsyncCall( result => { AsyncHelpers.CatchErrors( continuation, () => { var returnValue = endAsyncCall(result); onCompletion(returnValue); }); }); } else { AsyncHelpers.CatchErrors( continuation, () => { var returnValue = syncCall(); onCompletion(returnValue); }); } }
/// <summary> /// Adds a continuation to be executed after the operation has completed. If the operation is completed <paramref name="continuation"/> /// is invoked on the <paramref name="syncContext"/> specified. /// </summary> /// <remarks> /// The <paramref name="continuation"/> is invoked on a <see cref="SynchronizationContext"/> specified. Throwing an exception from the callback might cause unspecified behaviour. /// </remarks> /// <param name="continuation">The callback to be executed when the operation has completed.</param> /// <param name="syncContext">If not <see langword="null"/> method attempts to marshal the continuation to the synchronization context. /// Otherwise the callback is invoked on a thread that initiated the operation completion. /// </param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="continuation"/> is <see langword="null"/>.</exception> /// <exception cref="ObjectDisposedException">Thrown is the operation has been disposed.</exception> public void AddCompletionCallback(IAsyncContinuation continuation, SynchronizationContext syncContext) { if (!TryAddCompletionCallback(continuation, syncContext)) { InvokeCompletionCallback(continuation, syncContext); } }
private void VerifyChangeOnServer(ChangeData change, IAsyncContinuation continuation) { //// For now use different data service context to re-query and verify entities and links. //// In the future consider using an 'Oracle' component to re-query the changes if/when it comes online. using (IWrapperScope scope = new NullWrapperScope()) { WrappedDataServiceContext otherContext = this.DataServiceContextCreator.CreateContext(scope, this.currentContextData.ContextType, this.currentContextData.BaseUri); otherContext.ResolveName = this.currentContextData.ResolveName; otherContext.ResolveType = this.currentContextData.ResolveType; otherContext.IgnoreResourceNotFoundException = true; var uri = change.GetUriForRequery(); otherContext.Execute <WrappedObject>( continuation, this.Asynchronous, change.ClrTypeForRequery, uri, results => { var result = results.ToList(); VerifyChangeOnServer(change, otherContext, result); continuation.Continue(); }); } }
private void DownloadData(IAsyncContinuation continuation) { this.Logger.WriteLine(LogLevel.Verbose, "Downloading entity container data from {0}", this.CurrentWorkspace.OracleServiceUri); var dataOracleClient = this.ServiceReferenceFactory.CreateInstance <IDataOracleService>(this.CurrentWorkspace.OracleServiceUri); if (this.SkipDataDownload) { // Must create an empty one other wise failures will occur afterwards // TODO: handle multiple entity containers this.CurrentWorkspace.DownloadedEntityContainerData = new EntityContainerData(this.CurrentWorkspace.ConceptualModel.EntityContainers.Single()); continuation.Continue(); return; } dataOracleClient.BeginGetContainerData( result => AsyncHelpers.CatchErrors( continuation, () => { string errorMessage; var container = dataOracleClient.EndGetContainerData(out errorMessage, result); if (container == null) { continuation.Fail(new TaupoInfrastructureException(errorMessage)); return; } this.Logger.WriteLine(LogLevel.Verbose, "Got container with {0} entities.", container.Entities.Count); this.CurrentWorkspace.DownloadedEntityContainerData = this.DataOracleConverter.Convert(this.CurrentWorkspace.ConceptualModel, container); continuation.Continue(); }), null); }
private void FindDataServiceContext(IAsyncContinuation continuation) { if (this.SkipClientCodeGeneration) { continuation.Continue(); return; } #if WIN8 this.CurrentWorkspace.ContextType = this.dataServiceContextType; continuation.Continue(); #else foreach (var asm in this.CurrentWorkspace.Assemblies.Select(c => c.Contents)) { var contextType = asm.GetExportedTypes().Where(t => typeof(DataServiceContext).IsAssignableFrom(t)).SingleOrDefault(); if (contextType != null) { this.CurrentWorkspace.ContextType = contextType; this.Logger.WriteLine(LogLevel.Verbose, "Data Service Context: {0}", this.CurrentWorkspace.ContextType.AssemblyQualifiedName); } } ExceptionUtilities.Assert(this.CurrentWorkspace.ContextType != null, "DataServiceContext was not found in the compiled assembly."); continuation.Continue(); #endif }
private void GenerateClientLayerCode(IAsyncContinuation continuation) { if (this.SkipClientCodeGeneration) { continuation.Continue(); return; } this.Logger.WriteLine(LogLevel.Verbose, "Generating client source code..."); AsyncHelpers.CatchErrors( continuation, () => { this.ClientCodeLayerGenerator.GenerateClientCode( continuation, this.CurrentWorkspace.ServiceUri, this.CurrentWorkspace.ConceptualModel, this.Language, code => { this.clientLayerCode = code; this.Logger.WriteLine(LogLevel.Trace, "Generated Code: {0}", this.clientLayerCode); }); }); }
/// <summary> /// Verify all queries. /// </summary> /// <param name="continuation">The continuation.</param> protected virtual void VerifyAllQueries(IAsyncContinuation continuation) { var pending = this.pendingQueries; this.pendingQueries = new List <QueryExpression>(); var code = this.PrepareCodeBuilder(); var contextType = this.GetClientContextType(); var dataServiceContext = this.DataServiceContextCreator.CreateContext(this.DataServiceContextScope, contextType, this.workspace.ServiceUri); dataServiceContext.MergeOption = this.DataServiceContextScope.Wrap <WrappedEnum>(MergeOption.OverwriteChanges); var context = dataServiceContext.Product as DataServiceContext; var contextVariable = code.AddExternalProperty("Context", new CodeTypeReference(context.GetType()), context); var resultComparerVariable = code.AddExternalProperty("ResultComparer", this.ResultComparer); if (this.UseSendingRequestEventVerifier) { this.SendingRequestEventVerifier.RegisterEventHandler(context); continuation = continuation.OnContinueOrFail(isError => this.SendingRequestEventVerifier.UnregisterEventHandler(context, isError)); } for (int i = 0; i < pending.Count; ++i) { var query = this.LinqQueryResolver.Resolve(pending[i]); this.ResultComparer.EnqueueNextQuery(query); this.BuildSingleVariation(contextVariable, resultComparerVariable, query, dataServiceContext); } code.RunVariations(continuation); }
/// <summary> /// Update entity model based on csdl sent back from server. /// </summary> /// <param name="continuation">The async continuation</param> protected override void UpdateEntityModel(IAsyncContinuation continuation) { #if !SILVERLIGHT // get CSDL contents List <string> csdlContent = new List <string>(); foreach (var key in this.CurrentWorkspace.WorkspaceInfo.AdditionalProviderInfo.Keys.Where(k => k.StartsWith(AstoriaWorkspaceInfoConstants.CsdlKeyPrefix, StringComparison.OrdinalIgnoreCase))) { string content; ExceptionUtilities.Assert(this.CurrentWorkspace.WorkspaceInfo.AdditionalProviderInfo.TryGetValue(key, out content), "Cannot get csdl content with key {0}.", key); csdlContent.Add(content); } // preserve Annotations which were not serialised var functionAnnotationPreserver = new FunctionAnnotationPreserver(); functionAnnotationPreserver.PreserveFunctionAnnotations(this.CurrentWorkspace.ConceptualModel.Functions); // parse CSDL into EntityModelSchema XElement[] xelements = csdlContent.Select(XElement.Parse).ToArray(); this.CurrentWorkspace.ConceptualModel = this.CsdlParser.Parse(xelements); CustomAnnotationConverter customAnnotationConverter = new CustomAnnotationConverter(); customAnnotationConverter.AnnotationAssemblies.Add(typeof(TypeBackedAnnotation).GetAssembly()); customAnnotationConverter.AnnotationNamespaces.Add(typeof(TypeBackedAnnotation).Namespace); customAnnotationConverter.ConvertAnnotations(this.CurrentWorkspace.ConceptualModel); functionAnnotationPreserver.RestoreFunctionAnnotations(this.CurrentWorkspace.ConceptualModel.Functions); #endif base.UpdateEntityModel(continuation); }
/// <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> /// Update entity model schema based on csdl sent back from server. /// </summary> /// <param name="continuation">The continuation to invoke at the end of the build operation.</param> protected virtual void UpdateEntityModel(IAsyncContinuation continuation) { // resolve the primitive types in case the model coming back from the service builder doesn't have them resolved. this.PrimitiveTypeResolver.ResolveProviderTypes(this.CurrentWorkspace.ConceptualModel, this.EdmDataTypeResolver); // Do nothing by default. continuation.Continue(); }
/// <summary> /// Initializes a new instance of the Continuator class. /// </summary> /// <param name="enumerator">The enumerator.</param> /// <param name="userCallback">The user callback.</param> /// <param name="continuation">The continuation.</param> /// <param name="delayedFailures">If set to <c>true</c> the failures during enumeration will be delayed (and logged to the provider logger).</param> /// <param name="logger">The logger to log failures to.</param> public Continuator(IEnumerator <T> enumerator, Action <T, IAsyncContinuation> userCallback, IAsyncContinuation continuation, bool delayedFailures, Logger logger) { this.enumerator = enumerator; this.userCallback = userCallback; this.continuation = continuation; this.delayedFailures = delayedFailures; this.logger = logger; }
/// <summary> /// Removes an existing continuation. /// </summary> /// <param name="continuation">The continuation to remove. Can be <see langword="null"/>.</param> /// <returns>Returns <see langword="true"/> if <paramref name="continuation"/> was removed; <see langword="false"/> otherwise.</returns> public bool RemoveCompletionCallback(IAsyncContinuation continuation) { if (continuation != null) { return(TryRemoveCallback(continuation)); } return(false); }
/// <summary> /// Initializes the verifier's state based on its inputs /// </summary> /// <param name="continuation">The async continuation</param> protected override void InitializeState(IAsyncContinuation continuation) { #if WINDOWS_PHONE this.sendingRequestLog = new EventLogger <DSClient.SendingRequestEventArgs>(); #else this.sendingRequestLog = new EventLogger <DSClient.SendingRequest2EventArgs>(); #endif base.InitializeState(continuation); }
/// <summary> /// Runs the action sequence asynchronously. /// </summary> /// <param name="continuation">The continuation to be executed at the end of the action sequence.</param> /// <param name="sequence">The sequence of asynchronous actions.</param> public static void RunActionSequence(this IAsyncContinuation continuation, params Action <IAsyncContinuation>[] sequence) { AsyncForEach( sequence, continuation, (action, c) => { action(c); }); }
private void UpdateStreams(StreamData streamData, IAsyncContinuation continuation) { SendStreamValueToServer( continuation, this.Asynchronous, streamData.EditLink, streamData.ContentType, streamData.ETag, streamData.Content); }
/// <summary> /// Attempts to add a continuation to be executed after the operation has finished. If the operation is already completed /// the method does nothing and just returns <see langword="false"/>. /// </summary> /// <remarks> /// The <paramref name="continuation"/> is invoked on a <see cref="SynchronizationContext"/> specified. Throwing an exception from the callback might cause unspecified behaviour. /// </remarks> /// <param name="continuation">The cotinuation to be executed when the operation has completed.</param> /// <param name="syncContext">If not <see langword="null"/> method attempts to marshal the continuation to the synchronization context. /// Otherwise the callback is invoked on a thread that initiated the operation completion. /// </param> /// <returns>Returns <see langword="true"/> if the callback was added; <see langword="false"/> otherwise (the operation is completed).</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="continuation"/> is <see langword="null"/>.</exception> /// <exception cref="ObjectDisposedException">Thrown is the operation has been disposed.</exception> public bool TryAddCompletionCallback(IAsyncContinuation continuation, SynchronizationContext syncContext) { ThrowIfDisposed(); if (continuation == null) { throw new ArgumentNullException(nameof(continuation)); } return(TryAddCallback(continuation, syncContext, true)); }
public void ExecuteUriAndCompare <TResult>(IAsyncContinuation continuation, bool isAsync, string uriString, HttpVerb verb, OperationParameter[] inputParameters, bool singleResult, DataServiceContext dataContext, ExpectedClientErrorBaseline clientExpectedError) { this.isAsynchronous = isAsync; this.ExecuteQueryAction( continuation, null, dataContext, clientExpectedError, delegate(List <object> entityPayloads, IAsyncContinuation continuation2) { AsyncHelpers.CatchErrors( continuation2, () => { this.Logger.WriteLine(LogLevel.Verbose, "Executing Invoke Action, async:{0}, Uri:{1}:", isAsync, dataContext.BaseUri + "/" + uriString); Uri builtUri = new Uri(dataContext.BaseUri + "/" + uriString); #if !SILVERLIGHT EventHandler <SendingRequest2EventArgs> sendingRequest = delegate(object sender, SendingRequest2EventArgs args) { HttpRequestMessage request = ((HttpClientRequestMessage)args.RequestMessage).HttpRequestMessage; this.VerifyActionExecuteHeaders(verb, request.Headers, inputParameters); this.VerifyCommonExecuteHeaders(request.Headers); }; dataContext.SendingRequest2 += sendingRequest; #endif dataContext.ExecuteUri <TResult>( continuation2, isAsync, builtUri, verb, inputParameters, singleResult, delegate(QueryOperationResponse <TResult> results) { var savedRes = results.ToList(); if (singleResult) { // With singleResult=true, we expected 0/1 result item. Compare() will calculate and update the expected QueryValue to be non-NullValue. this.Compare(this.expressionQueue.Peek().ExpressionType.NullValue, () => savedRes.SingleOrDefault(), dataContext); } else { // With singleResult=false, we expected multiple result items. Compare() will calculate and update the expected QueryValue to be non-NullValue. this.Compare(this.expressionQueue.Peek().ExpressionType.NullValue, () => savedRes, dataContext); } dataContext.SendingRequest2 -= sendingRequest; continuation2.Continue(); }); }); }); }
/// <summary> /// Verifies the requests sent by the context /// </summary> /// <param name="continuation">The async continuation</param> protected override void VerifyRequests(IAsyncContinuation continuation) { if (this.State.UsedOptions != SaveChangesOptions.Batch) { var expectedRequests = this.RequestCalculator.CalculateSaveChangesRequestData(this.State.ContextDataBeforeChanges, this.Input.Context, this.State.UsedOptions, this.State.EnumeratedOperationResponses); var requestsSent = this.sendingRequestLog.Events.Select(e => e.Value).ToList(); this.RequestsVerifier.VerifyRequests(expectedRequests, requestsSent); } continuation.Continue(); }
/// <summary> /// Extension method to perform sync/async version of DataServiceContext.LoadProperty dynamically /// </summary> /// <param name="context">The context to call call load property on</param> /// <param name="continuation">The asynchronous continuation</param> /// <param name="async">A value indicating whether or not to use async API</param> /// <param name="entity">The entity to load a property on</param> /// <param name="propertyName">The name of the property to load</param> /// <param name="onCompletion">A callback for when the call completes</param> public static void LoadProperty(this DataServiceContext context, IAsyncContinuation continuation, bool async, object entity, string propertyName, Action <QueryOperationResponse> onCompletion) { ExceptionUtilities.CheckArgumentNotNull(context, "context"); AsyncHelpers.InvokeSyncOrAsyncMethodCall <QueryOperationResponse>( continuation, async, () => context.LoadProperty(entity, propertyName), c => context.BeginLoadProperty(entity, propertyName, c, null), r => context.EndLoadProperty(r), onCompletion); }
/// <summary> /// Wraps the given continuation with one that performs the given action on Continue /// </summary> /// <param name="continuation">The continuation to wrap</param> /// <param name="action">The action to invoke</param> /// <returns>A wrapping continuation</returns> public static IAsyncContinuation OnContinue(this IAsyncContinuation continuation, Action action) { ExceptionUtilities.CheckArgumentNotNull(continuation, "continuation"); ExceptionUtilities.CheckArgumentNotNull(action, "action"); return(CreateContinuation( () => { AsyncHelpers.CatchErrors(continuation, action); continuation.Continue(); }, e => continuation.Fail(e))); }
/// <summary> /// Extension method to perform sync/async version of DataServiceContext.GetReadStream dynamically /// </summary> /// <param name="context">The context to call get read stream on</param> /// <param name="continuation">The asynchronous continuation</param> /// <param name="async">A value indicating whether or not to use async API</param> /// <param name="entity">The entity to get the read stream for</param> /// <param name="streamName">The name of the stream or null to indicate the default stream</param> /// <param name="args">The args to the request</param> /// <param name="onCompletion">A callback for when the call completes</param> public static void GetReadStream(this DataServiceContext context, IAsyncContinuation continuation, bool async, object entity, string streamName, DataServiceRequestArgs args, Action <DataServiceStreamResponse> onCompletion) { ExceptionUtilities.CheckArgumentNotNull(context, "context"); if (streamName == null) { AsyncHelpers.InvokeSyncOrAsyncMethodCall <DataServiceStreamResponse>(continuation, async, () => context.GetReadStream(entity, args), c => context.BeginGetReadStream(entity, args, c, null), r => context.EndGetReadStream(r), onCompletion); } else { AsyncHelpers.InvokeSyncOrAsyncMethodCall <DataServiceStreamResponse>(continuation, async, () => context.GetReadStream(entity, streamName, args), c => context.BeginGetReadStream(entity, streamName, args, c, null), r => context.EndGetReadStream(r), onCompletion); } }
/// <summary> /// Extension method to perform sync/async version of DataServiceContext.SaveChanges dynamically /// </summary> /// <param name="context">The context to save changes on</param> /// <param name="continuation">The asynchronous continuation</param> /// <param name="async">A value indicating whether or not to use async API</param> /// <param name="options">The save changes options to use or null to use the overload without options</param> /// <param name="onCompletion">A callback for when the call completes</param> public static void SaveChanges(this DataServiceContext context, IAsyncContinuation continuation, bool async, SaveChangesOptions?options, Action <DataServiceResponse> onCompletion) { ExceptionUtilities.CheckArgumentNotNull(context, "context"); if (options == null) { AsyncHelpers.InvokeSyncOrAsyncMethodCall <DataServiceResponse>(continuation, async, () => context.SaveChanges(), c => context.BeginSaveChanges(c, null), r => context.EndSaveChanges(r), onCompletion); } else { AsyncHelpers.InvokeSyncOrAsyncMethodCall <DataServiceResponse>(continuation, async, () => context.SaveChanges(options.Value), c => context.BeginSaveChanges(options.Value, c, null), r => context.EndSaveChanges(r), onCompletion); } }
/// <summary> /// Generates the client-side proxy classes then calls the given callback /// </summary> /// <param name="continuation">The async continuation to report completion on</param> /// <param name="serviceRoot">The root uri of the service</param> /// <param name="model">The model for the service</param> /// <param name="language">The language to generate code in</param> /// <param name="onCompletion">The action to invoke with the generated code</param> public void GenerateClientCode(IAsyncContinuation continuation, Uri serviceRoot, EntityModelSchema model, IProgrammingLanguageStrategy language, Action<string> onCompletion) { ExceptionUtilities.CheckArgumentNotNull(continuation, "continuation"); ExceptionUtilities.CheckArgumentNotNull(serviceRoot, "serviceRoot"); ExceptionUtilities.CheckArgumentNotNull(model, "model"); ExceptionUtilities.CheckArgumentNotNull(language, "language"); ExceptionUtilities.CheckArgumentNotNull(onCompletion, "onCompletion"); var compileUnit = new CodeCompileUnit(); this.GenerateObjectLayer(compileUnit, model); this.GenerateContextType(compileUnit, model); string clientCode = language.CreateCodeGenerator().GenerateCodeFromCompileUnit(compileUnit); onCompletion(clientCode); continuation.Continue(); }
/// <summary> /// Executes the variation asynchonously. /// </summary> /// <param name="continuation">The continuation.</param> public void ExecuteAsync(IAsyncContinuation continuation) { try { IEnumerable<Action<IAsyncContinuation>> actions = null; using (var context = AsyncExecutionContext.Begin()) { this.Execute(); actions = context.GetQueuedActions(); } AsyncHelpers.RunActionSequence(continuation, actions); } catch (TargetInvocationException ex) { continuation.Fail(ex.InnerException); } }
/// <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); #if !WIN8 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); #else var task = this.OracleServiceClient.GetEntitySetAsync(new GetEntitySetRequest(entitySetName)); task.Wait(); var result = task.Result; var entities = result.GetEntitySetResult; var error = result.errorMessage; if (error != null) { continuation.Fail(new Exception(error)); return; } this.UnderlyingSynchronizer.SynchronizeEntireEntitySet(entitySetName, entities); continuation.Continue(); #endif }
private void RegisterServiceUri(IAsyncContinuation continuation) { // We set the Oracle Service uri to point to the deployed service and not wherever the serviceBaseUri points to. this.CurrentWorkspace.OracleServiceUri = new Uri(this.CurrentWorkspace.ServiceUri.OriginalString.Replace("RelayService", null).Replace(".svc", "DataOracle.svc")); // If a ServiceBaseUri was passed in through the test parameters, we set the ServiceUri of the workspace to be that. if (!string.IsNullOrEmpty(this.ServiceBaseUri)) { this.CurrentWorkspace.ServiceUri = new Uri(this.ServiceBaseUri); } continuation.Continue(); }
/// <summary> /// Builds the Edm Model /// </summary> /// <param name="continuation">The async continuation</param> protected abstract void BuildEdmModel(IAsyncContinuation continuation);
private void ProcessEntityAndGenerateStreams(QueryStructuralValue queryStructuralValue, IAsyncContinuation continuation, HttpWebResponse response) { ExceptionUtilities.Assert(response.StatusCode == HttpStatusCode.OK, "Error generating stream data, response code incorrect:" + response.StatusCode.ToString()); var responseValue = new StreamReader(response.GetResponseStream()).ReadToEnd(); try { var existingEntityInXML = XElement.Parse(responseValue); var feedInstance = this.XmlToPayloadConverter.ConvertToPayloadElement(existingEntityInXML) as EntitySetInstance; ExceptionUtilities.CheckObjectNotNull(feedInstance, "Error generating stream data, cannot deserialize response:" + existingEntityInXML); var type = queryStructuralValue.Type as QueryEntityType; ExceptionUtilities.CheckObjectNotNull(type, "Type was not an entity type. Type was {0}", type.StringRepresentation); Func<AstoriaQueryStreamValue, bool> valueFilter = v => v.IsNull || v.Value.Length == 0; Func<QueryProperty, bool> propertyFilter = p => p.IsStream() && valueFilter(queryStructuralValue.GetStreamValue(p.Name)); var streamPropertiesToUpdate = type.Properties.Where(propertyFilter).ToList(); if (feedInstance.Count != 0) { var entityInstance = feedInstance.SingleOrDefault(); ExceptionUtilities.CheckObjectNotNull(entityInstance, "Payload did not contain a single entity instance"); var baseAddressAnnotation = feedInstance.Annotations.OfType<XmlBaseAnnotation>().SingleOrDefault(); foreach (var streamProperty in streamPropertiesToUpdate) { var streamPropertyType = streamProperty.PropertyType as AstoriaQueryStreamType; ExceptionUtilities.CheckObjectNotNull(streamPropertyType, "PropertyType is not an AstoriaQueryStreamType!", streamProperty.PropertyType); var streamData = this.GenerateStreamData(entityInstance, baseAddressAnnotation, streamProperty); this.streamsToUpdate.Add(streamData); } } continuation.Continue(); } catch (XmlException) { this.Logger.WriteLine(LogLevel.Error, "Error in Xml payload:" + responseValue); throw; } }
/// <summary> /// Initializes the resource string verifiers. /// </summary> /// <param name="continuation">The async continuation.</param> protected void InitializeResourceStringVerifiers(IAsyncContinuation continuation) { this.CurrentWorkspace.SystemDataServicesResourceLookup = this.BuildSystemDataServicesResourceLookup(); this.CurrentWorkspace.SystemDataServicesStringVerifier = new StringResourceVerifier(this.CurrentWorkspace.SystemDataServicesResourceLookup); var systemDataServicesClientResourceLookup = BuildSystemDataServicesClientResourceLookup(); this.CurrentWorkspace.SystemDataServicesClientStringVerifier = new StringResourceVerifier(systemDataServicesClientResourceLookup); var microsoftDataODataLookup = BuildMicrosoftDataODataResourceLookup(); this.CurrentWorkspace.MicrosoftDataODataStringVerifier = new StringResourceVerifier(microsoftDataODataLookup); continuation.Continue(); }
private void QueryEntityInstanceAndGenerateStreams(QueryStructuralValue queryStructuralValue, IAsyncContinuation continuation) { var rootQuery = (QueryExpression)this.queryStructuralValueToRootQueryLookup[queryStructuralValue]; var query = ODataQueryTestCase.GetExistingEntityQuery(rootQuery, queryStructuralValue); var requestUriString = this.QueryExpressionToUriConverter.ComputeUri(query); requestUriString = UriHelpers.ConcatenateUriSegments(this.Workspace.ServiceUri.OriginalString, requestUriString); HttpWebRequest requestForExistingEntity = (HttpWebRequest)HttpWebRequest.Create(requestUriString); requestForExistingEntity.GetResponse<HttpWebResponse>( this.Asynchronous, continuation, (response) => { ProcessEntityAndGenerateStreams(queryStructuralValue, continuation, response); }); }
/// <summary> /// Runs the compiled variations in a sequence. /// </summary> /// <param name="continuation">The continuation to invoke once the variations have completed.</param> private void RunCompiledVariations(IAsyncContinuation continuation) { ExceptionUtilities.Assert(this.compiledActions != null, "compiledActions must be not null at this stage."); AsyncHelpers.RunActionSequence(continuation, this.compiledActions); }
/// <summary> /// Compiles all this.variations that have been finalized /// </summary> /// <param name="continuation">The continuation to invoke once the variations have been compiled.</param> private void CompileVariations(IAsyncContinuation continuation) { ExceptionUtilities.Assert(this.generatedCode != null, "generatedCode must be not null at this stage."); this.CompileCodeUnitAsync(continuation); }
private void CompileClientLayerCode(IAsyncContinuation continuation) { if (this.SkipClientCodeGeneration) { continuation.Continue(); return; } #if WIN8 this.CurrentWorkspace.Assemblies.Add(new FileContents<Assembly>(this.clientLayerAssembly.FullName, this.clientLayerAssembly)); continuation.Continue(); #else this.Logger.WriteLine(LogLevel.Verbose, "Compiling Client Source Code...."); var languageSpecificReferences = GetClientReferenceAssemblies(this.CurrentWorkspace.ConceptualModel, this.Language); string assemblyBaseName = "DataServiceClient" + Guid.NewGuid().ToString("N"); this.Language.CompileAssemblyAsync( assemblyBaseName, new[] { this.clientLayerCode }, languageSpecificReferences.ToArray(), (asm, error) => { if (error != null) { continuation.Fail(error); return; } this.CurrentWorkspace.Assemblies.Add(new FileContents<Assembly>(assemblyBaseName + ".dll", asm)); continuation.Continue(); }); #endif }
/// <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); #if !WIN8 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); #else var task = this.OracleServiceClient.GetEntityAsync( new GetEntityRequest( entitySetName, keyValues.Select(v => new SerializableNamedValue() { Name = v.Name, Value = v.Value }).ToArray())); task.Wait(); var result = task.Result; var entity = result.GetEntityResult; var error = result.errorMessage; if (error != null) { continuation.Fail(new Exception(error)); return; } this.UnderlyingSynchronizer.SynchronizeEntityInstanceGraph(entity); continuation.Continue(); #endif }
/// <summary> /// Generates named stream data for the test /// </summary> /// <param name="continuation">continuation token</param> public virtual void PopulateStreamsData(IAsyncContinuation continuation) { if (!this.Workspace.StreamsDataAlreadyAdd) { ExceptionUtilities.CheckArgumentNotNull(continuation, "continuation"); this.streamsToUpdate = new List<object>(); this.queryStructuralValueToRootQueryLookup = new Dictionary<object, object>(); this.queryStructuralValuesToAddStreamsTo = new List<object>(); this.FindEntitiesWithStreams(this.QueryRepository); AsyncHelpers.RunActionSequence(continuation, this.GetEntityInstances, this.UpdateStreams, this.SynchronizeEntities, this.MarkStreamServicesDataSetupOnWorkspace); } else { continuation.Continue(); } }
private void DownloadData(IAsyncContinuation continuation) { this.Logger.WriteLine(LogLevel.Verbose, "Downloading entity container data from {0}", this.CurrentWorkspace.OracleServiceUri); var dataOracleClient = this.ServiceReferenceFactory.CreateInstance<IDataOracleService>(this.CurrentWorkspace.OracleServiceUri); if (this.SkipDataDownload) { // Must create an empty one other wise failures will occur afterwards // TODO: handle multiple entity containers this.CurrentWorkspace.DownloadedEntityContainerData = new EntityContainerData(this.CurrentWorkspace.ConceptualModel.EntityContainers.Single()); continuation.Continue(); return; } #if !WIN8 dataOracleClient.BeginGetContainerData( result => AsyncHelpers.CatchErrors( continuation, () => { string errorMessage; var container = dataOracleClient.EndGetContainerData(out errorMessage, result); if (container == null) { continuation.Fail(new TaupoInfrastructureException(errorMessage)); return; } this.Logger.WriteLine(LogLevel.Verbose, "Got container with {0} entities.", container.Entities.Count); this.CurrentWorkspace.DownloadedEntityContainerData = this.DataOracleConverter.Convert(this.CurrentWorkspace.ConceptualModel, container); continuation.Continue(); }), null); #else var task = dataOracleClient.GetContainerDataAsync(new GetContainerDataRequest()); task.Wait(); var result = task.Result; string errorMessage = result.errorMessage; var container = result.GetContainerDataResult; if (container == null) { continuation.Fail(new TaupoInfrastructureException(errorMessage)); return; } this.Logger.WriteLine(LogLevel.Verbose, "Got container with {0} entities.", container.Entities.Length); this.CurrentWorkspace.DownloadedEntityContainerData = this.DataOracleConverter.Convert(this.CurrentWorkspace.ConceptualModel, container); continuation.Continue(); #endif }
private void GenerateClientLayerCode(IAsyncContinuation continuation) { if (this.SkipClientCodeGeneration) { continuation.Continue(); return; } #if WIN8 continuation.Continue(); #else this.Logger.WriteLine(LogLevel.Verbose, "Generating client source code..."); AsyncHelpers.CatchErrors( continuation, () => { this.ClientCodeLayerGenerator.GenerateClientCode( continuation, this.CurrentWorkspace.ServiceUri, this.CurrentWorkspace.ConceptualModel, this.Language, code => { this.clientLayerCode = code; this.Logger.WriteLine(LogLevel.Trace, "Generated Code: {0}", this.clientLayerCode); }); }); #endif }
private void BuildEntitySetResolver(IAsyncContinuation continuation) { if (string.IsNullOrEmpty(this.ServiceDocumentUri)) { IEntitySetResolver defaultEntitySetResolver = new DefaultEntitySetResolver(); this.CurrentWorkspace.EntitySetResolver = defaultEntitySetResolver; continuation.Continue(); } else { WebRequest serviceDocRequest = WebRequest.Create(this.ServiceDocumentUri); #if !SILVERLIGHT if (this.AuthenticationProvider.UseDefaultCredentials) { serviceDocRequest.UseDefaultCredentials = true; } else if (this.AuthenticationProvider.GetAuthenticationCredentials() != null) { serviceDocRequest.Credentials = this.AuthenticationProvider.GetAuthenticationCredentials(); } IDictionary<string, string> authenticationHeaders = this.AuthenticationProvider.GetAuthenticationHeaders(); if (authenticationHeaders != null) { foreach (var header in authenticationHeaders) { serviceDocRequest.Headers[header.Key] = header.Value; } } // we will set the timeout to 5 seconds to avoid waiting forever for a Service doc request to complete. serviceDocRequest.Timeout = 5000; #endif serviceDocRequest.BeginGetResponse( (asyncResult) => { try { XDocument serviceDocument = XDocument.Load(serviceDocRequest.EndGetResponse(asyncResult).GetResponseStream()); IEntitySetResolver entitySetResolver = this.ServiceDocumentParser.ParseServiceDocument(serviceDocument.Root); this.CurrentWorkspace.EntitySetResolver = entitySetResolver; continuation.Continue(); } catch (WebException errorWhileDownload) { continuation.Fail(errorWhileDownload); } }, null); } }
private static void SendStreamValueToServer(IAsyncContinuation continuation, bool async, string editLinkString, string contentType, string etag, byte[] streamData) { HttpWebRequest streamPutRequest; #if SILVERLIGHT && !WIN8 streamPutRequest = CreateClientHttpWebRequest(editLinkString); #else streamPutRequest = (HttpWebRequest)HttpWebRequest.Create(editLinkString); #endif // using verb-tunneling streamPutRequest.Method = "POST"; streamPutRequest.Headers[HttpHeaders.HttpMethod] = HttpVerb.Put.ToHttpMethod(); streamPutRequest.ContentType = contentType; if (etag != null) { streamPutRequest.Headers[HttpHeaders.IfMatch] = etag; } #if !WINDOWS_PHONE && !WIN8 streamPutRequest.AllowWriteStreamBuffering = false; streamPutRequest.ContentLength = streamData.Length; #endif streamPutRequest.BeginGetRequestStream( (requestStreamResult) => { var requestStream = streamPutRequest.EndGetRequestStream(requestStreamResult); requestStream.Write(streamData, 0, streamData.Length); requestStream.Close(); streamPutRequest.GetResponse<HttpWebResponse>( async, continuation, (streamResponse) => { ExceptionUtilities.Assert(streamResponse.StatusCode == HttpStatusCode.NoContent, "Named stream update failed"); continuation.Continue(); }); }, null); }
/// <summary> /// Verify all queries. /// </summary> /// <param name="continuation">The continuation.</param> protected virtual void VerifyAllQueries(IAsyncContinuation continuation) { var pending = this.pendingQueries; this.pendingQueries = new List<QueryExpression>(); var code = this.PrepareCodeBuilder(); var contextType = this.GetClientContextType(); var dataServiceContext = this.DataServiceContextCreator.CreateContext(this.DataServiceContextScope, contextType, this.workspace.ServiceUri); dataServiceContext.MergeOption = this.DataServiceContextScope.Wrap<WrappedEnum>(MergeOption.OverwriteChanges); var context = dataServiceContext.Product as DataServiceContext; var contextVariable = code.AddExternalProperty("Context", new CodeTypeReference(context.GetType()), context); var resultComparerVariable = code.AddExternalProperty("ResultComparer", this.ResultComparer); if (this.UseSendingRequestEventVerifier) { this.SendingRequestEventVerifier.RegisterEventHandler(context); continuation = continuation.OnContinueOrFail(isError => this.SendingRequestEventVerifier.UnregisterEventHandler(context, isError)); } for (int i = 0; i < pending.Count; ++i) { var query = this.LinqQueryResolver.Resolve(pending[i]); this.ResultComparer.EnqueueNextQuery(query); this.BuildSingleVariation(contextVariable, resultComparerVariable, query, dataServiceContext); } code.RunVariations(continuation); }
private void MarkStreamServicesDataSetupOnWorkspace(IAsyncContinuation continuation) { this.Workspace.StreamsDataAlreadyAdd = true; continuation.Continue(); }
/// <summary> /// Builds the data service /// </summary> /// <param name="continuation">The async continuation</param> protected abstract void BuildDataService(IAsyncContinuation continuation);
private void GetEntityInstances(IAsyncContinuation continuation) { AsyncHelpers.AsyncForEach(this.queryStructuralValuesToAddStreamsTo.Cast<QueryStructuralValue>(), continuation, this.QueryEntityInstanceAndGenerateStreams); }
private void CompileCodeUnitAsync(IAsyncContinuation continuation) { string assemblyName = "CB" + Guid.NewGuid().ToString("N"); var combinedReferenceAssemblies = new List<string>(); // add assemblies specified by the user combinedReferenceAssemblies.AddRange(this.referenceAssemblies); #if SILVERLIGHT && !WIN8 combinedReferenceAssemblies.Add("Microsoft.Test.Taupo.SL.dll"); #else // fix paths for assembly references combinedReferenceAssemblies = this.ResolveTaupoReferencePaths(combinedReferenceAssemblies).ToList(); // get Taupo assembly location #if !WIN8 string taupoAssemblyLocation = this.GetAssemblyLocation(); // only add Taupo assembly if it is not added before if (!combinedReferenceAssemblies.Contains(Path.GetFileName(taupoAssemblyLocation))) { combinedReferenceAssemblies.Add(taupoAssemblyLocation); } #endif #endif this.language.CompileAssemblyAsync( assemblyName, new[] { this.generatedCode }, combinedReferenceAssemblies.ToArray(), (asm, error) => { if (error != null) { continuation.Fail(error); } else { this.compiledAssembly = asm; continuation.Continue(); } }); }
private void UpdateStreams(IAsyncContinuation continuation) { AsyncHelpers.AsyncForEach(this.streamsToUpdate.Cast<StreamData>(), continuation, this.UpdateStreams); }
/// <summary> /// Prepares compiled variations for execution. /// </summary> /// <param name="continuation">The continuation to invoke once the variations have been prepared.</param> private void PrepareCompiledVariations(IAsyncContinuation continuation) { ExceptionUtilities.Assert(this.compiledAssembly != null, "compiledAssembly must be not null at this stage."); // Load the compiled code var testClass = this.compiledAssembly.GetType("Tests.TestClass"); var testClassInstance = Activator.CreateInstance(testClass); this.injector.InjectDependenciesInto(testClassInstance); foreach (var externalProperty in this.externalProperties.Values) { PropertyInfo propertyInfo = testClass.GetProperty(externalProperty.PropertyName); propertyInfo.SetValue(testClassInstance, externalProperty.InitialValue, null); } // Build an action for each variation var actions = new List<Action<IAsyncContinuation>>(); foreach (var v in this.variations) { var testMethod = testClass.GetMethod(v.BlockName); var methodParams = testMethod.GetParameters(); if (methodParams.Length > 0 && methodParams[0].ParameterType == typeof(IAsyncContinuation)) { var asyncAction = (Action<IAsyncContinuation>)testMethod.CreateDelegate(typeof(Action<IAsyncContinuation>), testClassInstance); actions.Add(asyncAction); } else { Action syncAction = (Action)testMethod.CreateDelegate(typeof(Action), testClassInstance); Action<IAsyncContinuation> asyncAction = c => AsyncHelpers.TryCatch(c, syncAction); actions.Add(asyncAction); } } this.compiledActions = actions; continuation.Continue(); }
private void SynchronizeEntities(IAsyncContinuation continuation) { AsyncHelpers.AsyncForEach(this.queryStructuralValuesToAddStreamsTo.Cast<QueryStructuralValue>(), continuation, (e, c) => this.Synchronizer.SynchronizeEntity(c, e)); }
/// <summary> /// Generates the client-side proxy classes then calls the given callback /// </summary> /// <param name="continuation">The async continuation to report completion on</param> /// <param name="serviceRoot">The root uri of the service</param> /// <param name="model">The model for the service</param> /// <param name="language">The language to generate code in</param> /// <param name="onCompletion">The action to invoke with the generated code</param> public void GenerateClientCode(IAsyncContinuation continuation, Uri serviceRoot, EntityModelSchema model, IProgrammingLanguageStrategy language, Action<string> onCompletion) { ExceptionUtilities.CheckArgumentNotNull(continuation, "continuation"); ExceptionUtilities.CheckArgumentNotNull(serviceRoot, "serviceRoot"); ExceptionUtilities.CheckArgumentNotNull(model, "model"); ExceptionUtilities.CheckArgumentNotNull(language, "language"); ExceptionUtilities.CheckArgumentNotNull(onCompletion, "onCompletion"); ExceptionUtilities.CheckAllRequiredDependencies(this); // because the product code-gen does not produce this overload of the DataServiceContext constructor, we need to add it ourselves // namespace <contextNamespace> // { // partial class <contextType> // { // public <contextType>(Uri serviceUri, DataServiceProtocolVersion maxProtocolVersion) // : base(serviceUri, maxProtocolVersion) // { // } // } // } var compileUnit = new CodeCompileUnit(); var contextNamespace = compileUnit.AddNamespace(model.EntityTypes.First().NamespaceName); var contextType = contextNamespace.DeclareType(model.EntityContainers.Single().Name); contextType.IsPartial = true; contextType.AddConstructor() .WithArgument(Code.TypeRef<Uri>(), "serviceUri") .WithArgument(Code.TypeRef("Microsoft.OData.Client.ODataProtocolVersion"), "maxProtocolVersion") .WithBaseConstructorArgument(Code.Variable("serviceUri")) .WithBaseConstructorArgument(Code.Variable("maxProtocolVersion")); string constructorOverload = language.CreateCodeGenerator().GenerateCodeFromNamespace(contextNamespace); #if !WIN8 this.DataServiceBuilder.BeginGenerateClientLayerCode( serviceRoot.OriginalString, this.DesignVersion, this.ClientVersion, language.FileExtension, result => { AsyncHelpers.CatchErrors( continuation, () => { string errorMessage; string clientCode = this.DataServiceBuilder.EndGenerateClientLayerCode(out errorMessage, result); if (errorMessage != null) { throw new TaupoInfrastructureException(errorMessage); } // add the extra constructor overload we generated above clientCode = string.Concat(clientCode, Environment.NewLine, constructorOverload); onCompletion(clientCode); continuation.Continue(); }); }, null); #else var task = this.DataServiceBuilder.GenerateClientLayerCodeAsync( new GenerateClientLayerCodeRequest( serviceRoot.OriginalString, this.DesignVersion, this.ClientVersion, language.FileExtension)); task.Wait(); var result = task.Result; string clientCode = result.GenerateClientLayerCodeResult; string errorMessage = result.errorLog; if (errorMessage != null) { throw new TaupoInfrastructureException(errorMessage); } // add the extra constructor overload we generated above clientCode = string.Concat(clientCode, Environment.NewLine, constructorOverload); onCompletion(clientCode); continuation.Continue(); #endif }