Example #1
0
 protected HttpResponseMessage Respond(IEnumerable <T> results)
 {
     if (wrapRequestAndResponse)
     {
         if (usesMapping)
         {
             var mappedResults = mapper.ProjectTo <M>(results.ToList().AsQueryable());
             var response      = new MultiResponse <M>();
             response.Results = mappedResults.ToList();
             return(ResponseHelper.CreateJsonResponse(response, jsonSettings));
         }
         else
         {
             var response = new MultiResponse <T>();
             response.Results = results.ToList();
             return(ResponseHelper.CreateJsonResponse(response, jsonSettings));
         }
     }
     else
     {
         if (usesMapping)
         {
             var mappedResults = mapper.ProjectTo <M>(results.ToList().AsQueryable());
             return(ResponseHelper.CreateJsonResponse(mappedResults, jsonSettings));
         }
         else
         {
             return(ResponseHelper.CreateJsonResponse(results, jsonSettings));
         }
     }
 }
        public async Task<MultiResponse<PictureResponseModel>> Handle(CreatePictureCommand request,
            CancellationToken cancellationToken)
        {
            var item = await this.context
                .Items
                .Select(i => new
                {
                    i.Id,
                    i.UserId
                })
                .SingleOrDefaultAsync(i => i.Id == request.ItemId, cancellationToken);
            if (item.UserId != this.currentUserService.UserId)
            {
                throw new NotFoundException(nameof(Item));
            }

            if (!request.Pictures.Any())
            {
                return new MultiResponse<PictureResponseModel>(new List<PictureResponseModel>());
            }

            var uploadResults = new ConcurrentBag<ImageUploadResult>();
            foreach (var picture in request.Pictures)
            {
                var guid = Guid.NewGuid().ToString();
                var uploadParams = new ImageUploadParams
                {
                    PublicId = Guid.NewGuid().ToString(),
                    File = new FileDescription(guid, picture.OpenReadStream()),
                    Folder = $"{request.ItemId}"
                };
                var uploadResult = await this.cloudinary.UploadAsync(uploadParams);
                uploadResults.Add(uploadResult);
            }

            var picturesToAdd = uploadResults.Select(picture => new Picture
            {
                Id = Guid.Parse(picture.PublicId.Substring(picture.PublicId.LastIndexOf('/') + 1)),
                ItemId = request.ItemId,
                Url = picture.SecureUri.AbsoluteUri
            }).ToList();

            await this.context.Pictures.AddRangeAsync(picturesToAdd, cancellationToken);
            await this.context.SaveChangesAsync(cancellationToken);

            var result =
                new MultiResponse<PictureResponseModel>(picturesToAdd
                    .Select(p => this.mapper.Map<PictureResponseModel>(p)).ToList());
            return result;
        }
        public void Can_Search_Owners()
        {
            using (var mock = AutoMock.GetLoose())
            {
                // Arrange
                var config           = mock.Provide <IAppConfig, TestConfig>();
                var searchCriteria   = new { field = "emailAddress", value = "test" };
                var testOwner        = GetTestOwner();
                var expectedMetadata = new Metadata(new[]
                {
                    Link.Self($"{Constants.TOKENIZED_CURRENT_URL}", HttpMethod.Get.Method),
                    Link.Custom("summary", $"{Constants.TOKENIZED_BASE_URL}/{Constants.API_ROUTE_BASE_PATH}{Constants.TOKENIZED_CONTROLLER_PATH}/{testOwner.Id}/summary", HttpMethod.Get.Method),
                    Link.Custom("detail", $"{Constants.TOKENIZED_BASE_URL}/{Constants.API_ROUTE_BASE_PATH}{Constants.TOKENIZED_CONTROLLER_PATH}/{testOwner.Id}/detail", HttpMethod.Get.Method),
                });
                var expectedOwners = new List <OwnerEntity> {
                    testOwner
                };
                var expected = new MultiResponse(Result.Success, expectedMetadata, expectedOwners.Select(Mapper.Map <OwnerEntity, OwnerSummaryModel>).OfType <IModel>().ToList());
                mock.Mock <IRepository <OwnerEntity> >().Setup(x => x.Search(searchCriteria.field, searchCriteria.value)).ReturnsAsync(expectedOwners);
                var systemUnderTest = mock.Create <OwnerService>();

                // Act
                var actual = systemUnderTest.Search(searchCriteria.field, searchCriteria.value).Result;

                // Assert
                mock.Mock <IRepository <OwnerEntity> >().VerifyAll();
                Assert.IsNotNull(actual);
                Assert.IsNull(actual.Errors);
                Assert.IsNotNull(actual.Data);
                Assert.IsNotNull(actual.Metadata);
                Assert.IsNotNull(actual.Metadata.Links);
                Assert.AreEqual(actual.Result, Result.Success);
                Assert.AreEqual(expected.Data.Count, actual.Data.Count);
                // todo - compare and assert the actual data
                Assert.AreEqual(expected.Metadata.ServerVersion, actual.Metadata.ServerVersion);
                Assert.IsTrue(MetadataLinksAreEqual(expected.Metadata.Links, actual.Metadata.Links));
            }
        }
Example #4
0
        /// <inheritdoc />
        public async Task <MultiResponse> CopyIndexAsync <T>(ISearchIndex sourceIndex, ISearchIndex destinationIndex,
                                                             RequestOptions requestOptions = null, CancellationToken ct = default) where T : class
        {
            if (sourceIndex.Config.AppId.Equals(destinationIndex.Config.AppId))
            {
                throw new AlgoliaException("Source and Destination indices should not be on the same application.");
            }

            // TODO: improve this section
            try
            {
                IndexSettings destinationSettings =
                    await destinationIndex.GetSettingsAsync(ct : ct).ConfigureAwait(false);

                if (destinationSettings != null)
                {
                    throw new AlgoliaException(
                              "Destination index already exists. Please delete it before copying index across applications.");
                }
            }
            catch (AlgoliaApiException ex)
            {
                // We want to catch an non existing index exception (404) and continue
                // Otherwise, we want to throw if it's another Http exception
                if (ex.HttpErrorCode != 404)
                {
                    throw;
                }
            }

            MultiResponse ret = new MultiResponse {
                Responses = new List <IAlgoliaWaitableResponse>()
            };

            // Save settings
            IndexSettings sourceSettings = await sourceIndex.GetSettingsAsync(ct : ct).ConfigureAwait(false);

            SetSettingsResponse destinationSettingsResp = await destinationIndex
                                                          .SetSettingsAsync(sourceSettings, requestOptions, ct)
                                                          .ConfigureAwait(false);

            ret.Responses.Add(destinationSettingsResp);

            // Save synonyms
            SynonymsIterator    sourceSynonyms             = new SynonymsIterator(sourceIndex);
            SaveSynonymResponse destinationSynonymResponse = await destinationIndex
                                                             .SaveSynonymsAsync(sourceSynonyms, requestOptions : requestOptions, ct : ct)
                                                             .ConfigureAwait(false);

            ret.Responses.Add(destinationSynonymResponse);

            // Save rules
            RulesIterator sourceRules             = new RulesIterator(sourceIndex);
            BatchResponse destinationRuleResponse = await destinationIndex
                                                    .SaveRulesAsync(sourceRules, requestOptions : requestOptions, ct : ct)
                                                    .ConfigureAwait(false);

            ret.Responses.Add(destinationRuleResponse);

            // Save objects (batched)
            IndexIterator <T>     indexIterator = sourceIndex.Browse <T>(new BrowseIndexQuery());
            BatchIndexingResponse saveObject    = await destinationIndex
                                                  .SaveObjectsAsync(indexIterator, requestOptions, ct)
                                                  .ConfigureAwait(false);

            ret.Responses.Add(saveObject);

            return(ret);
        }
 public ClientApi (List<DeserializedResult> theList) {
     if (theList == null) throw ArgumentNullException("error message here");
     // add overloaded constructors to MultiResponse class.
     MoreThanOne = new MultiResponse (theList);
    // OnlyOne = null;
 }