/// <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);
        }
        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
        }
        /// <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
            }
        }
        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 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();
            });
        }
        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);
        }
        /// <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
        }
        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);
            }
        }
Esempio n. 9
0
        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);
        }
Esempio n. 10
0
        /// <summary>
        /// Verifies the named streams.
        /// </summary>
        /// <param name="dataContext">The data context.</param>
        /// <param name="queryEntityValue">The query entity value.</param>
        /// <param name="streamProperty">The stream property.</param>
        /// <param name="ed">The entity descriptor</param>
        /// <param name="continuation">The stream descriptor continuation.</param>
        private void VerifyNamedStreams(DataServiceContext dataContext, QueryStructuralValue queryEntityValue, QueryProperty streamProperty, EntityDescriptor ed, IAsyncContinuation continuation)
        {
            var expectedStreamValue = queryEntityValue.GetStreamValue(streamProperty.Name);
            var streamDescriptor    = ed.StreamDescriptors.SingleOrDefault(s => s.StreamLink.Name == streamProperty.Name);

            this.Assert.IsNotNull(streamDescriptor, "Entity missing stream descriptor for stream '{0}'", streamProperty.Name);
            this.VerifyStreamLink(expectedStreamValue, streamDescriptor.StreamLink);

            var expectedReadStreamUri = GetExpectedReadStreamUri(expectedStreamValue);

            Uri readStreamUri = dataContext.GetReadStreamUri(ed.Entity, streamProperty.Name);

            this.Assert.AreEqual(expectedReadStreamUri, readStreamUri, "Read stream uri did not match for stream '{0}'", streamProperty.Name);

            dataContext.GetReadStream(
                continuation,
                this.isAsynchronous,
                ed.Entity,
                streamProperty.Name,
                new DataServiceRequestArgs()
            {
            },
                response =>
            {
                UpdateStreamValueFromHeaders(expectedStreamValue, response);
                this.VerifyStreamLink(expectedStreamValue, streamDescriptor.StreamLink);
                // skip this verification when using payload driven verification since we don't have the expected content for streams
                if (!this.DataProviderSettings.UsePayloadDrivenVerification)
                {
                    this.Assert.IsTrue(this.VerifyStreams(expectedStreamValue, response), "Failed to compare value of stream '{0}'", streamProperty.Name);
                }

                continuation.Continue();
            });
        }
Esempio n. 11
0
        /// <summary>
        /// Verifies the default stream.
        /// </summary>
        /// <param name="dataContext">The data context.</param>
        /// <param name="queryEntityValue">The query entity value.</param>
        /// <param name="ed">The entity descriptor.</param>
        /// <param name="continuation">The stream descriptor continuation.</param>
        private void VerifyDefaultStream(DataServiceContext dataContext, QueryStructuralValue queryEntityValue, EntityDescriptor ed, IAsyncContinuation continuation)
        {
            var expectedStreamValue = queryEntityValue.GetDefaultStreamValue();

            this.VerifyStreamDescriptorValues(expectedStreamValue, null, null, ed.StreamETag, ed.EditStreamUri, ed.ReadStreamUri);

            var expectedReadStreamUri = GetExpectedReadStreamUri(expectedStreamValue);

            Uri readStreamUri = dataContext.GetReadStreamUri(ed.Entity);

            this.Assert.AreEqual(expectedReadStreamUri, readStreamUri, "Read stream uri did not match for default stream");

            dataContext.GetReadStream(
                continuation,
                this.isAsynchronous,
                ed.Entity,
                null,
                new DataServiceRequestArgs()
            {
            },
                response =>
            {
                UpdateStreamValueFromHeaders(expectedStreamValue, response);

                this.VerifyStreamDescriptorValues(expectedStreamValue, null, null, ed.StreamETag, ed.EditStreamUri, ed.ReadStreamUri);

                // skip this verification when using payload driven verification since we don't have the expected content for streams
                if (!this.DataProviderSettings.UsePayloadDrivenVerification)
                {
                    this.Assert.IsTrue(this.VerifyStreams(expectedStreamValue, response), "Failed to compare the default stream");
                }

                continuation.Continue();
            });
        }
Esempio n. 12
0
        /// <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 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();
                });
            }
        }
Esempio n. 14
0
        /// <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>
        /// 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();
        }
Esempio n. 16
0
        /// <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>
        /// 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
        }
Esempio n. 18
0
 /// <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)));
 }
        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>
        /// 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();
        }
Esempio n. 21
0
        /// <summary>
        /// Helper method for emulating while-loops asynchronously using recursion
        /// </summary>
        /// <param name="continuation">The continuation to call when the condition is false</param>
        /// <param name="condition">The condition to check before starting the next iteration</param>
        /// <param name="action">The action to call for each iteration.</param>
        public static void AsyncWhile(this IAsyncContinuation continuation, Func <bool> condition, Action <IAsyncContinuation> action)
        {
            var wrappedContinuation = CreateContinuation(
                () => AsyncWhile(continuation, condition, action),
                e => continuation.Fail(e));

            if (condition())
            {
                CatchErrors(wrappedContinuation, () => action(wrappedContinuation));
            }
            else
            {
                continuation.Continue();
            }
        }
Esempio n. 22
0
        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            instance       = feedInstance.SingleOrDefault();
                    EntityInstance entityInstance = instance as EntityInstance;
                    if (entityInstance != null)
                    {
                        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;
            }
        }
Esempio n. 23
0
 /// <summary>
 /// Wraps the given continuation with one that performs the given cleanup logic on both success and failure
 /// </summary>
 /// <param name="continuation">The continuation to wrap</param>
 /// <param name="cleanup">The cleanup logic to invoke in both cases, which takes a value indicating whether an exception was caught</param>
 /// <returns>A wrapping continuation with the cleanup logic</returns>
 public static IAsyncContinuation OnContinueOrFail(this IAsyncContinuation continuation, Action <bool> cleanup)
 {
     ExceptionUtilities.CheckArgumentNotNull(continuation, "continuation");
     ExceptionUtilities.CheckArgumentNotNull(cleanup, "cleanup");
     return(CreateContinuation(
                () =>
     {
         AsyncHelpers.CatchErrors(continuation, () => cleanup(false));
         continuation.Continue();
     },
                e =>
     {
         AsyncHelpers.CatchErrors(continuation, () => cleanup(true));
         continuation.Fail(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");

            var compileUnit = new CodeCompileUnit();
            this.GenerateObjectLayer(compileUnit, model);
            this.GenerateContextType(compileUnit, model);

            string clientCode = language.CreateCodeGenerator().GenerateCodeFromCompileUnit(compileUnit);

            onCompletion(clientCode);
            continuation.Continue();
        }
Esempio n. 25
0
        /// <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();
        }
Esempio n. 26
0
        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();
                }
            });
        }
Esempio n. 27
0
        /// <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();
            }
        }
Esempio n. 28
0
        /// <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();
        }
Esempio n. 29
0
        /// <summary>
        /// Initializes the verifier's state based on its inputs
        /// </summary>
        /// <param name="continuation">The async continuation</param>
        protected virtual void InitializeState(IAsyncContinuation continuation)
        {
            this.State = new VerifierState();

            this.State.UsedOptions = this.Input.Options.HasValue ? this.Input.Options.Value : this.Input.Context.SaveChangesDefaultOptions.ToTestEnum();

            this.State.ContextDataBeforeChanges = this.Input.ContextData.Clone();

            this.State.Response = null;
            this.State.EnumeratedOperationResponses.Clear();

            this.State.CachedPropertyValuesBeforeSave.Clear();
            foreach (var entityDescriptorData in this.State.ContextDataBeforeChanges.EntityDescriptorsData.Where(e => e.Entity != null))
            {
                var entityType = this.ModelSchema.EntityTypes.Single(t => t.FullName == entityDescriptorData.EntityClrType.FullName);
                this.State.CachedPropertyValuesBeforeSave[entityDescriptorData.Entity] = this.ObjectServices.GetPropertiesValues(entityDescriptorData.Entity, entityType);
            }

            this.ServerStateVerifier.InitializeExpectedChanges(this.Input.ContextData, this.State.CachedPropertyValuesBeforeSave);

            continuation.Continue();
        }
Esempio n. 30
0
        /// <summary>
        /// Invokes the given async action and handles exceptions of a particular type using a callback
        /// </summary>
        /// <typeparam name="TException">The type of exceptions to handle</typeparam>
        /// <param name="continuation">The continuation to use</param>
        /// <param name="action">The async action to invoke</param>
        /// <param name="handleExceptionCallback">The callback for handling exceptions</param>
        public static void HandleException <TException>(this IAsyncContinuation continuation, Action <IAsyncContinuation> action, Action <TException> handleExceptionCallback) where TException : Exception
        {
            ExceptionUtilities.CheckArgumentNotNull(continuation, "continuation");
            ExceptionUtilities.CheckArgumentNotNull(action, "action");
            ExceptionUtilities.CheckArgumentNotNull(handleExceptionCallback, "handleExceptionCallback");

            var exceptionContinuation = CreateContinuation(
                () => continuation.Continue(),
                e =>
            {
                var exception = e as TException;
                if (exception != null)
                {
                    CatchErrors(continuation, () => handleExceptionCallback(exception));
                }
                else
                {
                    continuation.Fail(e);
                }
            });

            CatchErrors(exceptionContinuation, () => action(exceptionContinuation));
        }
        /// <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
        }
        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 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();
                    });
            }
        }
 /// <summary>
 /// Verifies the requests sent by the context
 /// </summary>
 /// <param name="continuation">The async continuation</param>
 protected override void VerifyRequests(IAsyncContinuation continuation)
 {
     this.State.ExpectedResponse = this.Emulator.ValidateAndTrackChanges(this.Input.ContextData, this.State.CachedPropertyValuesBeforeSave, this.State.UsedOptions, this.httpLog);
     continuation.Continue();
 }
Esempio n. 35
0
 /// <summary>
 /// Verifies the requests sent by the context
 /// </summary>
 /// <param name="continuation">The async continuation</param>
 protected override void VerifyRequests(IAsyncContinuation continuation)
 {
     this.State.ExpectedResponse = this.Emulator.ValidateAndTrackChanges(this.Input.ContextData, this.State.CachedPropertyValuesBeforeSave, this.State.UsedOptions, this.httpLog);
     continuation.Continue();
 }
        /// <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();
        }
Esempio n. 37
0
        /// <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 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
        }
Esempio n. 39
0
        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();
                    }
                });
        }
Esempio n. 40
0
        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;
            }
        }
        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
        }
Esempio n. 42
0
 private void MarkStreamServicesDataSetupOnWorkspace(IAsyncContinuation continuation)
 {
     this.Workspace.StreamsDataAlreadyAdd = true;
     continuation.Continue();
 }
        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();
        }
        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);
            }
        }
        /// <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);
        }
Esempio n. 46
0
        /// <summary>
        /// Verifies the descriptor after execute.
        /// </summary>
        /// <param name="continuation">The continuation.</param>
        /// <param name="dataContext">The data context.</param>
        /// <param name="entityPayloads">The list of entities</param>
        /// <param name="expectedValue">The expected value.</param>
        protected void VerifyDescriptorAfterExecute(IAsyncContinuation continuation, DataServiceContext dataContext, IEnumerable <object> entityPayloads, QueryValue expectedValue)
        {
            // If no streams were generated as part of the test initialization then this block of verification is needed
            if (this.SkipGenerateNamedStream)
            {
                continuation.Continue();
            }
            else
            {
                object[] entities = entityPayloads.ToArray();
                if (this.DataProviderSettings.UsePayloadDrivenVerification)
                {
                    expectedValue = this.baselineQueryValue;
                }

                var expectedEntities = expectedValue as QueryCollectionValue;
                QueryStructuralValue element;

                if (expectedEntities == null)
                {
                    continuation.Continue();
                }
                else
                {
                    AsyncHelpers.AsyncForEach(
                        expectedEntities.Elements.ToList(),
                        continuation,
                        (qv, entityContinuation) =>
                    {
                        // NOTE: The results could be a list of AnonTypes at which point these wouldn't be have descriptors so
                        // no need to verify
                        element = qv as QueryStructuralValue;

                        var queryEntityType = element.Type as QueryEntityType;
                        if (queryEntityType == null)
                        {
                            entityContinuation.Continue();
                        }
                        else
                        {
                            var queryEntityValue        = element as QueryEntityValue;
                            QueryKeyStructuralValue key = queryEntityValue.Key();

                            // This handles the expand scenario (Orders(1)?$expand=Customer) where the entity in the list doesn't have a corresponding QueryStructuralValue
                            object entity = entities.Where(upe => queryEntityType.ClrType.IsAssignableFrom(upe.GetType()) && queryEntityType.GetEntityInstanceKey(upe).Equals(key)).FirstOrDefault();

                            if (entity == null)
                            {
                                entityContinuation.Continue();
                            }
                            else
                            {
                                EntityDescriptor ed  = dataContext.GetEntityDescriptor(entity);
                                var streamProperties = queryEntityType.Properties.Where(p => p.IsStream()).ToList();          // intentionally include the default stream
                                int expectedStreamDescriptorCount = streamProperties.Count(p => p.Name != AstoriaQueryStreamType.DefaultStreamPropertyName);
                                this.Assert.AreEqual(expectedStreamDescriptorCount, ed.StreamDescriptors.Count, "Entity descriptor had unexpected number of stream descriptors");

                                AsyncHelpers.AsyncForEach(
                                    streamProperties,
                                    entityContinuation,
                                    (streamProperty, streamDescriptorContinuation) =>
                                {
                                    if (streamProperty.Name == AstoriaQueryStreamType.DefaultStreamPropertyName)
                                    {
                                        this.VerifyDefaultStream(dataContext, element, ed, streamDescriptorContinuation);
                                    }
                                    else
                                    {
                                        this.VerifyNamedStreams(dataContext, element, streamProperty, ed, streamDescriptorContinuation);
                                    }
                                });
                            }
                        }
                    });
                }
            }
        }
Esempio n. 47
0
        /// <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();
            }
        }
        /// <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();
        }
Esempio n. 49
0
        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);
        }
        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>
        /// Builds the data service
        /// </summary>
        /// <param name="continuation">The async continuation</param>
        protected override void BuildDataService(IAsyncContinuation continuation)
        {
            var csdlGen = this.CsdlGenerator as CsdlContentGenerator;
            if (csdlGen != null)
            {
                csdlGen.GenerateTaupoAnnotations = true;
                csdlGen.IgnoreUnsupportedAnnotations = true;
            }

            var csdlContent = this.CsdlGenerator.Generate(this.EdmVersion, this.CurrentWorkspace.ConceptualModel).ToArray();
            var csdlContentStrings = csdlContent.Select(c => c.Contents.ToString()).ToArray();

            string errorMessage;
            var settings = this.BuildServiceBuilderParameters();

            string deployerName = this.DeploymentSettings.ServiceDeployerKind;
            if (this.ShouldUseRelayService())
            {
                deployerName = DeploymentSettings.RelayServiceDeployerPrefix + deployerName;
            }

#if !WIN8
            this.DataServiceBuilder.BeginCreateCustomDataService(
                csdlContentStrings,
                this.DataProviderSettings.DataProviderKind,
                deployerName,
                settings,
                result => AsyncHelpers.CatchErrors(
                    continuation,
                    () =>
                    {
                        this.CurrentWorkspace.WorkspaceInfo = this.DataServiceBuilder.EndCreateCustomDataService(out errorMessage, result);
                        
                        ExceptionUtilities.CheckObjectNotNull(this.CurrentWorkspace.WorkspaceInfo, "Cannot get workspace info after creation. Error:" + errorMessage);

                        string serviceUri = this.CurrentWorkspace.WorkspaceInfo.ServiceUri;   
                        if (serviceUri == null)
                        {
                            continuation.Fail(new TaupoInfrastructureException(errorMessage));
                            return;
                        }

                        this.Logger.WriteLine(LogLevel.Verbose, "Service URI: {0}", serviceUri);
                        var builder = this.DataServiceBuilder;

                        this.CurrentWorkspace.OnDispose += (sender, e) =>
                            {
                                if (!this.SkipDataServiceDispose)
                                {
                                    // begin removal of the data service - note that nobody is waiting
                                    // for this operation to complete
                                    this.Logger.WriteLine(LogLevel.Verbose, "Uninstalling service {0} asynchronously", serviceUri);
                                    builder.BeginUninstallDataService(serviceUri, null, null);
                                }
                            };

                        this.CurrentWorkspace.ServiceUri = new Uri(serviceUri);
                        continuation.Continue();
                    }),
                    null);
#else 
            var task = this.DataServiceBuilder.CreateCustomDataServiceAsync(
                new CreateCustomDataServiceRequest(
                    new ObservableCollection<string>(csdlContentStrings),
                    this.DataProviderSettings.DataProviderKind,
                    deployerName,
                    new ObservableCollection<ServiceBuilderParameter>(settings)));
            task.Wait();
            var result = task.Result;
            this.CurrentWorkspace.WorkspaceInfo = result.CreateCustomDataServiceResult;
            errorMessage = result.errorLog;

            ExceptionUtilities.CheckObjectNotNull(this.CurrentWorkspace.WorkspaceInfo, "Cannot get workspace info after creation. Error:" + errorMessage);

            string serviceUri = this.CurrentWorkspace.WorkspaceInfo.ServiceUri;
            if (serviceUri == null)
            {
                continuation.Fail(new TaupoInfrastructureException(errorMessage));
                return;
            }

            this.Logger.WriteLine(LogLevel.Verbose, "Service URI: {0}", serviceUri);
            var builder = this.DataServiceBuilder;

            this.CurrentWorkspace.OnDispose += (sender, e) =>
            {
                if (!this.SkipDataServiceDispose)
                {
                    // begin removal of the data service - note that nobody is waiting
                    // for this operation to complete
                    this.Logger.WriteLine(LogLevel.Verbose, "Uninstalling service {0} asynchronously", serviceUri);
                    builder.UninstallDataServiceAsync(serviceUri).Wait();
                }
            };

            this.CurrentWorkspace.ServiceUri = new Uri(serviceUri);
            continuation.Continue();
#endif
        }