Beispiel #1
0
        public virtual async Task <ContinuousChangesResponse> GetAsync(GetChangesRequest request, Action <string> onRead, CancellationToken cancellationToken)
        {
            Ensure.That(request, "request").IsNotNull();
            Ensure.That(onRead, "onRead").IsNotNull();
            if (!request.Feed.HasValue || request.Feed != ChangesFeed.Continuous)
            {
                throw new ArgumentException(ExceptionStrings.GetContinuousChangesInvalidFeed, "request");
            }

            using (var httpRequest = HttpRequestFactory.Create(request))
            {
                using (var httpResponse = await SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ForAwait())
                {
                    var response = ContinuousChangesResponseFactory.Create(httpResponse);
                    if (response.IsSuccess)
                    {
                        using (var content = await httpResponse.Content.ReadAsStreamAsync().ForAwait())
                        {
                            using (var reader = new StreamReader(content, MyCouchRuntime.DefaultEncoding))
                            {
                                while (!cancellationToken.IsCancellationRequested && !reader.EndOfStream)
                                {
                                    cancellationToken.ThrowIfCancellationRequested();
                                    onRead(reader.ReadLine());
                                }
                            }
                        }
                    }
                    return(response);
                }
            }
        }
Beispiel #2
0
        public virtual async Task <ContinuousChangesResponse> GetAsync(GetChangesRequest request, Func <string, Task> onRead, CancellationToken cancellationToken)
        {
            var httpRequest = ContinuousHttpRequestFactory.Create(request);

            using (var httpResponse = await SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ForAwait())
            {
                var response = await ContinuousChangesResponseFactory.CreateAsync(httpResponse).ForAwait();

                if (response.IsSuccess)
                {
                    using (var content = await httpResponse.Content.ReadAsStreamAsync().ForAwait())
                    {
                        using (var reader = new StreamReader(content, MyCouchRuntime.DefaultEncoding))
                        {
                            while (!cancellationToken.IsCancellationRequested && !reader.EndOfStream)
                            {
                                //cancellationToken.ThrowIfCancellationRequested();
                                if (!cancellationToken.IsCancellationRequested)
                                {
                                    await onRead(reader.ReadLine()).ForAwait();
                                }
                            }
                        }
                    }
                }
                return(response);
            }
        }
Beispiel #3
0
        public virtual HttpRequest Create(GetChangesRequest request)
        {
            Ensure.Any.IsNotNull(request, nameof(request));

            return(new HttpRequest(HttpMethod.Get, GenerateRelativeUrl(request))
                   .SetRequestTypeHeader(request.GetType()));
        }
Beispiel #4
0
        public virtual void When_getting_Continuous_changes_via_callback_and_performing_three_changes_It_will_extract_three_changes()
        {
            var lastSequence   = GetLastSequence();
            var changesRequest = new GetChangesRequest {
                Feed = ChangesFeed.Continuous, Since = lastSequence
            };
            var       numOfChanges         = 0;
            const int expectedNumOfChanges = 3;
            var       cancellation         = new CancellationTokenSource();

            var changes = SUT.GetAsync(changesRequest, data =>
            {
                Interlocked.Increment(ref numOfChanges);
                if (numOfChanges == expectedNumOfChanges)
                {
                    cancellation.Cancel();
                }
            }, cancellation.Token);

            var postOfDoc   = DbClient.Documents.PostAsync(ClientTestData.Artists.Artist1Json).Result;
            var putOfDoc    = DbClient.Documents.PutAsync(postOfDoc.Id, postOfDoc.Rev, ClientTestData.Artists.Artist1Json).Result;
            var deleteOfDoc = DbClient.Documents.DeleteAsync(putOfDoc.Id, putOfDoc.Rev).Result;

            var response = changes.Result;

            response.IsSuccess.Should().BeTrue();
        }
Beispiel #5
0
        public virtual IObservable <string> ObserveContinuous(GetChangesRequest request, CancellationToken cancellationToken)
        {
            var httpRequest = ContinuousHttpRequestFactory.Create(request);

            var ob = new MyObservable <string>();

            Task.Factory.StartNew(async() =>
            {
                using (var httpResponse = await SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ForAwait())
                {
                    var response = await ContinuousChangesResponseFactory.CreateAsync(httpResponse).ForAwait();
                    if (response.IsSuccess)
                    {
                        using (var content = await httpResponse.Content.ReadAsStreamAsync().ForAwait())
                        {
                            using (var reader = new StreamReader(content, MyCouchRuntime.DefaultEncoding))
                            {
                                while (!cancellationToken.IsCancellationRequested && !reader.EndOfStream)
                                {
                                    //cancellationToken.ThrowIfCancellationRequested();
                                    if (!cancellationToken.IsCancellationRequested)
                                    {
                                        ob.Notify(reader.ReadLine());
                                    }
                                }
                                ob.Complete();
                            }
                        }
                    }
                }
            }, cancellationToken).ForAwait();

            return(ob);
        }
 protected virtual void EnsureContinuousFeedIsRequested(GetChangesRequest request)
 {
     if (request.Feed.HasValue && request.Feed != ChangesFeed.Continuous)
     {
         throw new ArgumentException(ExceptionStrings.GetContinuousChangesInvalidFeed, "request");
     }
 }
Beispiel #7
0
        public virtual void When_getting_Continuous_changes_via_observable_and_performing_three_changes_It_will_extract_three_changes()
        {
            var lastSequence   = GetLastSequence();
            var changesRequest = new GetChangesRequest {
                Feed = ChangesFeed.Continuous, Since = lastSequence
            };
            var       numOfChanges         = 0;
            const int expectedNumOfChanges = 3;
            var       cancellation         = new CancellationTokenSource();

            var changes = SUT.ObserveContinuous(changesRequest, cancellation.Token).ForEachAsync((d, i) =>
            {
                Interlocked.Increment(ref numOfChanges);
                if (numOfChanges >= expectedNumOfChanges)
                {
                    cancellation.Cancel();
                }
            });

            var postOfDoc   = DbClient.Documents.PostAsync(ClientTestData.Artists.Artist1Json).Result;
            var putOfDoc    = DbClient.Documents.PutAsync(postOfDoc.Id, postOfDoc.Rev, ClientTestData.Artists.Artist1Json).Result;
            var deleteOfDoc = DbClient.Documents.DeleteAsync(putOfDoc.Id, putOfDoc.Rev).Result;

            changes.Wait();
        }
        /// <summary>
        /// Returns all configured options of <see cref="GetChangesRequest"/> as key values.
        /// The values are formatted to JSON-compatible strings.
        /// </summary>
        /// <returns></returns>
        protected virtual IDictionary<string, string> ConvertRequestToJsonCompatibleKeyValues(GetChangesRequest request)
        {
            var kvs = new Dictionary<string, string>();

            if(request.Feed.HasValue)
                kvs.Add(KeyNames.Feed, request.Feed.Value.AsString());

            if (HasValue(request.Since))
                kvs.Add(KeyNames.Since, request.Since);

            if (request.IncludeDocs.HasValue)
                kvs.Add(KeyNames.IncludeDocs, request.IncludeDocs.Value.ToString().ToLower());

            if (request.Descending.HasValue)
                kvs.Add(KeyNames.Descending, request.Descending.Value.ToString().ToLower());

            if (request.Limit.HasValue)
                kvs.Add(KeyNames.Limit, request.Limit.Value.ToString(MyCouchRuntime.NumberFormat));

            if (request.Heartbeat.HasValue)
                kvs.Add(KeyNames.HeartBeat, request.Heartbeat.Value.ToString(MyCouchRuntime.NumberFormat));

            if (request.Timeout.HasValue)
                kvs.Add(KeyNames.Timeout, request.Timeout.Value.ToString(MyCouchRuntime.NumberFormat));

            if (request.Filter != null)
                kvs.Add(KeyNames.Filter, request.Filter);

            if (request.Style.HasValue)
                kvs.Add(KeyNames.Style, request.Style.Value.AsString());

            return kvs;
        }
Beispiel #9
0
 protected virtual void EnsureNonContinuousFeedIsRequested(GetChangesRequest request)
 {
     if (request.Feed.HasValue && request.Feed == ChangesFeed.Continuous)
     {
         throw new ArgumentException(ExceptionStrings.GetChangesForNonContinuousFeedOnly, "request");
     }
 }
Beispiel #10
0
        public override HttpRequest Create(GetChangesRequest request)
        {
            Ensure.That(request, "request").IsNotNull();

            EnsureNonContinuousFeedIsRequested(request);

            return(base.Create(request));
        }
Beispiel #11
0
        public override HttpRequest Create(GetChangesRequest request)
        {
            Ensure.Any.IsNotNull(request, nameof(request));

            EnsureNonContinuousFeedIsRequested(request);

            return(base.Create(request));
        }
Beispiel #12
0
 public virtual Task <ContinuousChangesResponse> GetAsync(GetChangesRequest request, Action <string> onRead, CancellationToken cancellationToken = default)
 {
     return(GetAsync(request, data =>
     {
         onRead(data);
         return Task.FromResult(0);
     }, cancellationToken));
 }
Beispiel #13
0
        public virtual async Task <ChangesResponse> GetAsync(GetChangesRequest request, CancellationToken cancellationToken = default)
        {
            var httpRequest = HttpRequestFactory.Create(request);

            using (var httpResponse = await SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ForAwait())
            {
                return(await ChangesResponseFactory.CreateAsync(httpResponse).ForAwait());
            }
        }
Beispiel #14
0
        public virtual async Task <ChangesResponse> GetAsync(GetChangesRequest request)
        {
            var httpRequest = HttpRequestFactory.Create(request);

            using (var httpResponse = await SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).ForAwait())
            {
                return(ChangesResponseFactory.Create(httpResponse));
            }
        }
Beispiel #15
0
        public virtual async Task <ChangesResponse> GetAsync(GetChangesRequest request)
        {
            Ensure.That(request, "request").IsNotNull();
            EnsureNonContinuousFeed(request);

            using (var httpRequest = HttpRequestFactory.Create(request))
            {
                using (var httpResponse = await SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).ForAwait())
                {
                    return(ChangesResponseFactory.Create(httpResponse));
                }
            }
        }
Beispiel #16
0
        public void When_getting_Normal_changes_after_all_changes_has_been_done_It_contains_only_info_about_the_last_change()
        {
            var changesRequest = new GetChangesRequest {
                Feed = ChangesFeed.Normal
            };
            var changes0 = SUT.GetAsync(changesRequest).Result;

            changes0.Should().BeSuccessfulGet();

            var postOfDoc   = DbClient.Documents.PostAsync(ClientTestData.Artists.Artist1Json).Result;
            var putOfDoc    = DbClient.Documents.PutAsync(postOfDoc.Id, postOfDoc.Rev, ClientTestData.Artists.Artist1Json).Result;
            var deleteOfDoc = DbClient.Documents.DeleteAsync(putOfDoc.Id, putOfDoc.Rev).Result;

            var changesAfterLastOperation = SUT.GetAsync(changesRequest).Result;

            VerifyChanges(changes0, changesAfterLastOperation, deleteOfDoc.Id, deleteOfDoc.Rev, shouldBeDeleted: true);
        }
        public async Task <BatchSet> GetChanges(string bucketName, Filter query, int limit, string anchor, string uploadAnchor)
        {
            using (var client = new MyCouchClient(DbServerUrl, bucketName))
            {
                GetChangesRequest changesReq = new GetChangesRequest();
                changesReq.Since       = anchor;
                changesReq.Limit       = limit;
                changesReq.IncludeDocs = true;
                var response = await client.Changes.GetAsync(changesReq);

                if (response.IsSuccess)
                {
                    BatchSet changeSet = new BatchSet();
                    if (response.Results != null)
                    {
                        SyncLogItem logItem = await this.GetSyncLogItem(uploadAnchor);

                        foreach (var row in response.Results)
                        {
                            if (row.Deleted)
                            {
                                this.AddDeletedDoc(changeSet, row, logItem);
                            }
                            else
                            {
                                this.AddChangedDoc(changeSet, row, logItem, query, client.Serializer);
                            }
                        }
                        changeSet.Anchor = response.LastSeq;
                    }

                    return(changeSet);
                }
                else
                {
                    CheckBucketNotFound(bucketName, response);
                }
                return(null);
            }
        }
Beispiel #18
0
        public void When_getting_Normal_changes_with_included_doc_after_a_post_It_contains_the_included_doc()
        {
            var changesRequest = new GetChangesRequest {
                Feed = ChangesFeed.Normal
            };
            var changes0 = SUT.GetAsync(changesRequest).Result;

            changes0.Should().BeSuccessfulGet();

            var postOfDoc = DbClient.Documents.PostAsync(ClientTestData.Artists.Artist1Json).Result;

            var changesRequestWithInclude = new GetChangesRequest {
                Feed = ChangesFeed.Normal, IncludeDocs = true
            };
            var changesAfterPostOfDoc = SUT.GetAsync(changesRequestWithInclude).Result;

            VerifyChanges(changes0, changesAfterPostOfDoc, postOfDoc.Id, postOfDoc.Rev, shouldBeDeleted: false);

            var change    = changesAfterPostOfDoc.Results.OrderBy(c => GetSeqNumber(c.Seq)).Last();
            var postedDoc = DbClient.Documents.GetAsync(postOfDoc.Id, postOfDoc.Rev).Result.Content;

            change.IncludedDoc.Should().Be(postedDoc);
        }
Beispiel #19
0
        public void When_getting_Normal_changes_after_each_change_It_contains_info_about_each_change()
        {
            var changesRequest = new GetChangesRequest {
                Feed = ChangesFeed.Normal
            };
            var changes0 = SUT.GetAsync(changesRequest).Result;

            changes0.Should().BeSuccessfulGet();

            var postOfDoc             = Client.Documents.PostAsync(ClientTestData.Artists.Artist1Json).Result;
            var changesAfterPostOfDoc = SUT.GetAsync(changesRequest).Result;

            VerifyChanges(changes0, changesAfterPostOfDoc, postOfDoc.Id, postOfDoc.Rev, shouldBeDeleted: false);

            var putOfDoc             = Client.Documents.PutAsync(postOfDoc.Id, postOfDoc.Rev, ClientTestData.Artists.Artist1Json).Result;
            var changesAfterPutOfDoc = SUT.GetAsync(changesRequest).Result;

            VerifyChanges(changesAfterPostOfDoc, changesAfterPutOfDoc, putOfDoc.Id, putOfDoc.Rev, shouldBeDeleted: false);

            var deleteOfDoc             = Client.Documents.DeleteAsync(putOfDoc.Id, putOfDoc.Rev).Result;
            var changesAfterDeleteOfDoc = SUT.GetAsync(changesRequest).Result;

            VerifyChanges(changesAfterPutOfDoc, changesAfterDeleteOfDoc, deleteOfDoc.Id, deleteOfDoc.Rev, shouldBeDeleted: true);
        }
 public virtual HttpRequest Create(GetChangesRequest request)
 {
     return(CreateFor <GetChangesRequest>(HttpMethod.Get, GenerateRequestUrl(request)));
 }
Beispiel #21
0
 public static Task <ChangesResponse> PerformAsync(this IMyCouchClient client, GetChangesRequest request)
 {
     return(client.Changes.GetAsync(request));
 }
Beispiel #22
0
 public static Task <ContinuousChangesResponse> PerformAsync(this IMyCouchClient client, GetChangesRequest request, Action <string> onRead, CancellationToken cancellationToken)
 {
     return(client.Changes.GetAsync(request, onRead, cancellationToken));
 }
Beispiel #23
0
        /// <summary>
        /// Returns all configured options of <see cref="GetChangesRequest"/> as key values.
        /// The values are formatted to JSON-compatible strings.
        /// </summary>
        /// <returns></returns>
        protected virtual IDictionary <string, string> ConvertRequestToJsonCompatibleKeyValues(GetChangesRequest request)
        {
            var kvs = new Dictionary <string, string>();

            if (request.Feed.HasValue)
            {
                kvs.Add(KeyNames.Feed, request.Feed.Value.AsString());
            }

            if (!string.IsNullOrWhiteSpace(request.Since))
            {
                kvs.Add(KeyNames.Since, request.Since);
            }

            if (request.IncludeDocs.HasValue)
            {
                kvs.Add(KeyNames.IncludeDocs, request.IncludeDocs.Value.ToString().ToLower());
            }

            if (request.Descending.HasValue)
            {
                kvs.Add(KeyNames.Descending, request.Descending.Value.ToString().ToLower());
            }

            if (request.Limit.HasValue)
            {
                kvs.Add(KeyNames.Limit, request.Limit.Value.ToString(MyCouchRuntime.FormatingCulture.NumberFormat));
            }

            if (request.Heartbeat.HasValue)
            {
                kvs.Add(KeyNames.HeartBeat, request.Heartbeat.Value.ToString(MyCouchRuntime.FormatingCulture.NumberFormat));
            }

            if (request.Timeout.HasValue)
            {
                kvs.Add(KeyNames.Timeout, request.Timeout.Value.ToString(MyCouchRuntime.FormatingCulture.NumberFormat));
            }

            if (request.Filter != null)
            {
                kvs.Add(KeyNames.Filter, request.Filter);
            }

            if (request.Style.HasValue)
            {
                kvs.Add(KeyNames.Style, request.Style.Value.AsString());
            }

            return(kvs);
        }
Beispiel #24
0
 protected virtual string GenerateQueryStringParams(GetChangesRequest request)
 {
     return(string.Join("&", ConvertRequestToJsonCompatibleKeyValues(request)
                        .Select(kv => string.Format("{0}={1}", kv.Key, UrlParam.Encode(kv.Value)))));
 }
Beispiel #25
0
        protected virtual string GenerateQueryString(GetChangesRequest request)
        {
            var p = GenerateQueryStringParams(request);

            return(string.IsNullOrEmpty(p) ? string.Empty : string.Concat("?", p));
        }
Beispiel #26
0
 protected virtual string GenerateRelativeUrl(GetChangesRequest request)
 {
     return(string.Format("/_changes{0}",
                          GenerateQueryString(request)));
 }
 protected virtual string GenerateRequestUrl(GetChangesRequest request)
 {
     return(string.Format("{0}/_changes{1}",
                          Connection.Address,
                          GenerateQueryString(request)));
 }
 protected virtual string GenerateQueryStringParams(GetChangesRequest request)
 {
     return string.Join("&", ConvertRequestToJsonCompatibleKeyValues(request)
         .Select(kv => string.Format("{0}={1}", kv.Key, Uri.EscapeDataString(kv.Value))));
 }
        protected virtual string GenerateQueryString(GetChangesRequest request)
        {
            var p = GenerateQueryStringParams(request);

            return string.IsNullOrEmpty(p) ? string.Empty : string.Concat("?", p);
        }
 protected virtual string GenerateRequestUrl(GetChangesRequest request)
 {
     return string.Format("{0}/_changes{1}",
         Connection.Address,
         GenerateQueryString(request));
 }
 public virtual HttpRequest Create(GetChangesRequest request)
 {
     return CreateFor<GetChangesRequest>(HttpMethod.Get, GenerateRequestUrl(request));
 }
Beispiel #32
0
        protected virtual void WithHttpRequestFor(GetChangesRequest request, Action <HttpRequest> a)
        {
            var req = SUT.Create(request);

            a(req);
        }
 protected virtual void WithHttpRequestFor(GetChangesRequest request, Action <HttpRequestMessage> a)
 {
     using (var req = SUT.Create(request))
         a(req);
 }