Esempio n. 1
0
 private Task <T[]> LoadAsyncInternal <T>(string[] ids, string[] includes, MultiLoadOperation multiLoadOperation)
 {
     multiLoadOperation.LogOperation();
     using (multiLoadOperation.EnterMultiLoadContext())
     {
         return(AsyncDatabaseCommands.GetAsync(ids, includes)
                .ContinueWith(t =>
         {
             if (multiLoadOperation.SetResult(t.Result) == false)
             {
                 return Task.Factory.StartNew(() => multiLoadOperation.Complete <T>());
             }
             return LoadAsyncInternal <T>(ids, includes, multiLoadOperation);
         })
                .Unwrap());
     }
 }
Esempio n. 2
0
        private Task <T> CompleteLoadAsync <T>(string id, LoadOperation loadOperation)
        {
            loadOperation.LogOperation();
            using (loadOperation.EnterLoadContext())
            {
                return(AsyncDatabaseCommands.GetAsync(id)
                       .ContinueWith(task =>
                {
                    if (loadOperation.SetResult(task.Result) == false)
                    {
                        return Task.Factory.StartNew(() => loadOperation.Complete <T>());
                    }

                    return CompleteLoadAsync <T>(id, loadOperation);
                })
                       .Unwrap());
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Begins the async save changes operation
        /// </summary>
        /// <returns></returns>
        public async Task SaveChangesAsync(CancellationToken token = default(CancellationToken))
        {
            await asyncDocumentKeyGeneration.GenerateDocumentKeysForSaveChanges().WithCancellation(token);

            using (EntityToJson.EntitiesToJsonCachingScope())
            {
                var data = PrepareForSaveChanges();
                if (data.Commands.Count == 0)
                {
                    return;
                }

                IncrementRequestCount();

                var result = await AsyncDatabaseCommands.BatchAsync(data.Commands.ToArray(), token);

                UpdateBatchResults(result, data);
            }
        }
Esempio n. 4
0
        public async Task <IAsyncEnumerator <StreamResult <T> > > StreamAsync <T>(IAsyncDocumentQuery <T> query, Reference <QueryHeaderInformation> queryHeaderInformation, CancellationToken token = default(CancellationToken))
        {
            var ravenQueryInspector = ((IRavenQueryInspector)query);
            var indexQuery          = ravenQueryInspector.GetIndexQuery(true);

            if (indexQuery.WaitForNonStaleResults || indexQuery.WaitForNonStaleResultsAsOfNow)
            {
                throw new NotSupportedException(
                          "Since Stream() does not wait for indexing (by design), streaming query with WaitForNonStaleResults is not supported.");
            }


            var enumerator = await AsyncDatabaseCommands.StreamQueryAsync(ravenQueryInspector.AsyncIndexQueried, indexQuery, queryHeaderInformation, token).ConfigureAwait(false);

            var queryOperation = ((AsyncDocumentQuery <T>)query).InitializeQueryOperation();

            queryOperation.DisableEntitiesTracking = true;
            return(new QueryYieldStream <T>(this, enumerator, queryOperation, query, token));
        }
Esempio n. 5
0
        public Task <IEnumerable <TResult> > LoadStartingWithAsync <TTransformer, TResult>(string keyPrefix, string matches = null, int start = 0, int pageSize = 25,
                                                                                           string exclude = null, RavenPagingInformation pagingInformation = null,
                                                                                           Action <ILoadConfiguration> configure = null) where TTransformer : AbstractTransformerCreationTask, new()
        {
            var transformer = new TTransformer().TransformerName;

            var configuration = new RavenLoadConfiguration();

            if (configure != null)
            {
                configure(configuration);
            }

            return(AsyncDatabaseCommands.StartsWithAsync(keyPrefix, matches, start, pageSize, exclude: exclude,
                                                         pagingInformation: pagingInformation, transformer: transformer,
                                                         queryInputs: configuration.QueryInputs)
                   .ContinueWith(
                       task => (IEnumerable <TResult>)task.Result.Select(TrackEntity <TResult>).ToList()));
        }
Esempio n. 6
0
        public async Task <T[]> LoadUsingTransformerInternalAsync <T>(string[] ids, KeyValuePair <string, Type>[] includes, string transformer, Dictionary <string, RavenJToken> transformerParameters = null, CancellationToken token = default(CancellationToken))
        {
            if (transformer == null)
            {
                throw new ArgumentNullException("transformer");
            }
            if (ids.Length == 0)
            {
                return(new T[0]);
            }

            IncrementRequestCount();

            var includeNames = includes != null?includes.Select(x => x.Key).ToArray() : new string[0];

            var multiLoadResult = await AsyncDatabaseCommands.GetAsync(ids, includeNames, transformer, transformerParameters, token : token);

            return(new LoadTransformerOperation(this, transformer, ids).Complete <T>(multiLoadResult));
        }
Esempio n. 7
0
        /// <summary>
        /// Begins the async multi load operation
        /// </summary>
        public async Task <T[]> LoadAsyncInternal <T>(string[] ids, KeyValuePair <string, Type>[] includes)
        {
            IncrementRequestCount();
            var multiLoadOperation = new MultiLoadOperation(this, AsyncDatabaseCommands.DisableAllCaching, ids, includes);

            multiLoadOperation.LogOperation();
            var includePaths = includes != null?includes.Select(x => x.Key).ToArray() : null;

            MultiLoadResult result;

            do
            {
                multiLoadOperation.LogOperation();
                using (multiLoadOperation.EnterMultiLoadContext())
                {
                    result = await AsyncDatabaseCommands.GetAsync(ids, includePaths);
                }
            } while (multiLoadOperation.SetResult(result));
            return(multiLoadOperation.Complete <T>());
        }
Esempio n. 8
0
        private async Task <bool> ExecuteLazyOperationsSingleStep(ResponseTimeInformation responseTimeInformation)
        {
            var disposables = pendingLazyOperations.Select(x => x.EnterContext()).Where(x => x != null).ToList();

            try
            {
                var requests  = pendingLazyOperations.Select(x => x.CreateRequest()).ToArray();
                var responses = await AsyncDatabaseCommands.MultiGetAsync(requests);

                for (int i = 0; i < pendingLazyOperations.Count; i++)
                {
                    long totalTime;
                    long.TryParse(responses[i].Headers["Temp-Request-Time"], out totalTime);

                    responseTimeInformation.DurationBreakdown.Add(new ResponseTimeItem
                    {
                        Url      = requests[i].UrlAndQuery,
                        Duration = TimeSpan.FromMilliseconds(totalTime)
                    });
                    if (responses[i].RequestHasErrors())
                    {
                        throw new InvalidOperationException("Got an error from server, status code: " + responses[i].Status +
                                                            Environment.NewLine + responses[i].Result);
                    }
                    pendingLazyOperations[i].HandleResponse(responses[i]);
                    if (pendingLazyOperations[i].RequiresRetry)
                    {
                        return(true);
                    }
                }
                return(false);
            }
            finally
            {
                foreach (var disposable in disposables)
                {
                    disposable.Dispose();
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Begins the async save changes operation
        /// </summary>
        /// <returns></returns>
        public Task SaveChangesAsync()
        {
            return(asyncDocumentKeyGeneration.GenerateDocumentKeysForSaveChanges()
                   .ContinueWith(keysTask =>
            {
                keysTask.AssertNotFailed();

                var cachingScope = EntityToJson.EntitiesToJsonCachingScope();
                try
                {
                    var data = PrepareForSaveChanges();
                    if (data.Commands.Count == 0)
                    {
                        cachingScope.Dispose();
                        return new CompletedTask();
                    }

                    IncrementRequestCount();

                    return AsyncDatabaseCommands.BatchAsync(data.Commands.ToArray())
                    .ContinueWith(task =>
                    {
                        try
                        {
                            UpdateBatchResults(task.Result, data);
                        }
                        finally
                        {
                            cachingScope.Dispose();
                        }
                    });
                }
                catch
                {
                    cachingScope.Dispose();
                    throw;
                }
            }).Unwrap());
        }
Esempio n. 10
0
        public Task <IEnumerable <TResult> > LoadStartingWithAsync <TTransformer, TResult>(string keyPrefix, string matches = null, int start = 0, int pageSize = 25,
                                                                                           string exclude = null, RavenPagingInformation pagingInformation = null,
                                                                                           Action <ILoadConfiguration> configure = null,
                                                                                           string skipAfter = null, CancellationToken token = default(CancellationToken)) where TTransformer : AbstractTransformerCreationTask, new()
        {
            var transformer = new TTransformer().TransformerName;

            var configuration = new RavenLoadConfiguration();

            if (configure != null)
            {
                configure(configuration);
            }
            var queryOperation = new QueryOperation(this, "Load/StartingWith", null, null, false, TimeSpan.Zero, null, null, false);

            return(AsyncDatabaseCommands.StartsWithAsync(keyPrefix, matches, start, pageSize, exclude: exclude,
                                                         pagingInformation: pagingInformation, transformer: transformer,
                                                         transformerParameters: configuration.TransformerParameters,
                                                         skipAfter: skipAfter, token: token)
                   .ContinueWith(
                       task => (IEnumerable <TResult>)task.Result.Select(x => queryOperation.Deserialize <TResult>(x.ToJson())).ToList(), token));
        }
Esempio n. 11
0
        /// <summary>
        /// Opens the session for a particular database
        /// </summary>
        public IDocumentSession OpenSession(string database)
        {
            EnsureNotClosed();

            var sessionId = Guid.NewGuid();

            currentSessionId = sessionId;
            try
            {
                var session = new DocumentSession(this, listeners, sessionId, DatabaseCommands.ForDatabase(database)
#if !NET_3_5
                                                  , AsyncDatabaseCommands.ForDatabase(database)
#endif
                                                  );
                AfterSessionCreated(session);
                return(session);
            }
            finally
            {
                currentSessionId = null;
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Begins the async load operation
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public Task <T> LoadAsync <T>(string id)
        {
            object entity;

            if (entitiesByKey.TryGetValue(id, out entity))
            {
                var tcs = new TaskCompletionSource <T>();
                tcs.TrySetResult((T)entity);
                return(tcs.Task);
            }

            IncrementRequestCount();

            return(AsyncDatabaseCommands.GetAsync(id)
                   .ContinueWith(task =>
            {
                JsonDocument documentFound;
                try
                {
                    documentFound = task.Result;
                }
                catch (WebException ex)
                {
                    var httpWebResponse = ex.Response as HttpWebResponse;
                    if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.NotFound)
                    {
                        return default(T);
                    }
                    throw;
                }
                if (documentFound == null)
                {
                    return default(T);
                }

                return TrackEntity <T>(documentFound);
            }));
        }
Esempio n. 13
0
        /// <summary>
        /// Opens the async session.
        /// </summary>
        /// <returns></returns>
        public IAsyncDocumentSession OpenAsyncSession(string databaseName)
        {
            EnsureNotClosed();

            var sessionId = Guid.NewGuid();

            currentSessionId = sessionId;
            try
            {
                if (AsyncDatabaseCommands == null)
                {
                    throw new InvalidOperationException("You cannot open an async session because it is not supported on embedded mode");
                }

                var session = new AsyncDocumentSession(this, AsyncDatabaseCommands.ForDatabase(databaseName), listeners, sessionId);
                AfterSessionCreated(session);
                return(session);
            }
            finally
            {
                currentSessionId = null;
            }
        }
Esempio n. 14
0
 /// <summary>
 /// Begins the async multi load operation
 /// </summary>
 /// <param name="ids">The ids.</param>
 /// <returns></returns>
 public Task <T[]> MultiLoadAsync <T>(string[] ids)
 {
     IncrementRequestCount();
     return(AsyncDatabaseCommands.MultiGetAsync(ids)
            .ContinueWith(task => task.Result.Select(TrackEntity <T>).ToArray()));
 }
Esempio n. 15
0
        private async Task <IAsyncEnumerator <StreamResult <T> > > StreamAsync <T>(Etag fromEtag, string startsWith, string matches, int start, int pageSize, RavenPagingInformation pagingInformation = null, string skipAfter = null, CancellationToken token = default(CancellationToken))
        {
            var enumerator = await AsyncDatabaseCommands.StreamDocsAsync(fromEtag, startsWith, matches, start, pageSize, pagingInformation : pagingInformation, skipAfter : skipAfter, token : token).ConfigureAwait(false);

            return(new DocsYieldStream <T>(this, enumerator, token));
        }
Esempio n. 16
0
 /// <summary>
 /// Load documents with the specified key prefix
 /// </summary>
 public Task <IEnumerable <T> > LoadStartingWithAsync <T>(string keyPrefix, string matches = null, int start = 0, int pageSize = 25, string exclude = null, RavenPagingInformation pagingInformation = null, string skipAfter = null, CancellationToken token = default(CancellationToken))
 {
     return(AsyncDatabaseCommands.StartsWithAsync(keyPrefix, matches, start, pageSize, exclude: exclude, pagingInformation: pagingInformation, skipAfter: skipAfter, token: token)
            .ContinueWith(task => (IEnumerable <T>)task.Result.Select(TrackEntity <T>).ToList(), token));
 }
Esempio n. 17
0
        private async Task <IAsyncEnumerator <StreamResult <T> > > StreamAsync <T>(Etag fromEtag, string startsWith, string matches, int start, int pageSize, RavenPagingInformation pagingInformation = null)
        {
            var enumerator = await AsyncDatabaseCommands.StreamDocsAsync(fromEtag, startsWith, matches, start, pageSize, pagingInformation : pagingInformation).ConfigureAwait(false);

            return(new DocsYieldStream <T>(this, enumerator));
        }
Esempio n. 18
0
 public Task <FacetResults[]> MultiFacetedSearchAsync(params FacetQuery[] queries)
 {
     IncrementRequestCount();
     return(AsyncDatabaseCommands.GetMultiFacetsAsync(queries));
 }
Esempio n. 19
0
        public async Task PrepareTransaction(string txId, Guid?resourceManagerId = null, byte[] recoveryInformation = null)
        {
            await AsyncDatabaseCommands.PrepareTransactionAsync(txId, resourceManagerId, recoveryInformation).ConfigureAwait(false);

            ClearEnlistment();
        }
Esempio n. 20
0
        /// <summary>
        /// Rollbacks the specified tx id.
        /// </summary>
        /// <param name="txId">The tx id.</param>
        public override async Task Rollback(string txId)
        {
            await AsyncDatabaseCommands.RollbackAsync(txId).ConfigureAwait(false);

            ClearEnlistment();
        }
Esempio n. 21
0
 /// <summary>
 /// Opens the async session.
 /// </summary>
 /// <returns></returns>
 public override IAsyncDocumentSession OpenAsyncSession(string databaseName)
 {
     return(OpenAsyncSessionInternal(AsyncDatabaseCommands.ForDatabase(databaseName)));
 }
Esempio n. 22
0
        public async Task <T[]> LoadAsyncInternal <T>(string[] ids, KeyValuePair <string, Type>[] includes, string transformer, Dictionary <string, RavenJToken> transformerParameters = null)
        {
            if (ids.Length == 0)
            {
                return(new T[0]);
            }

            IncrementRequestCount();

            var includePaths = includes != null?includes.Select(x => x.Key).ToArray() : null;

            if (typeof(T).IsArray)
            {
                // Returns array of arrays, public APIs don't surface that yet though as we only support Transform
                // With a single Id
                var arrayOfArrays = (await AsyncDatabaseCommands.GetAsync(ids, includePaths, transformer, transformerParameters).ConfigureAwait(false))
                                    .Results
                                    .Select(x => x.Value <RavenJArray>("$values").Cast <RavenJObject>())
                                    .Select(values =>
                {
                    var array = values.Select(y =>
                    {
                        HandleInternalMetadata(y);
                        return(ConvertToEntity(typeof(T), null, y, new RavenJObject()));
                    }).ToArray();
                    var newArray = Array.CreateInstance(typeof(T).GetElementType(), array.Length);
                    Array.Copy(array, newArray, array.Length);
                    return(newArray);
                })
                                    .Cast <T>()
                                    .ToArray();

                return(arrayOfArrays);
            }

            var getResponse = (await AsyncDatabaseCommands.GetAsync(ids, includePaths, transformer, transformerParameters).ConfigureAwait(false));
            var items       = new List <T>();

            foreach (var result in getResponse.Results)
            {
                if (result == null)
                {
                    items.Add(default(T));
                    continue;
                }
                var transformedResults = result.Value <RavenJArray>("$values").ToArray()
                                         .Select(JsonExtensions.ToJObject)
                                         .Select(x =>
                {
                    HandleInternalMetadata(x);
                    return(ConvertToEntity(typeof(T), null, x, new RavenJObject()));
                })
                                         .Cast <T>();


                items.AddRange(transformedResults);
            }

            if (items.Count > ids.Length)
            {
                throw new InvalidOperationException(String.Format("A load was attempted with transformer {0}, and more than one item was returned per entity - please use {1}[] as the projection type instead of {1}",
                                                                  transformer,
                                                                  typeof(T).Name));
            }

            return(items.ToArray());
        }