public async Task ShouldSearch()
        {
            // Arrange
            var name = "Embed share to search" + new Random().Next(0, 999999);

            await CreateShare(new ShareEmbedCreateRequest
            {
                Contents       = await GetRandomShareContent().ConfigureAwait(false),
                Description    = "Description of Embed share bbb",
                ExpirationDate = new DateTime(2020, 12, 31),
                Name           = name
            }).ConfigureAwait(false);

            // Act
            var request = new ShareSearchRequest
            {
                Limit  = 100,
                Filter = new AndFilter
                {
                    Filters = new List <FilterBase>
                    {
                        FilterBase.FromExpression <Share>(i => i.ShareType, ShareType.Embed.ToString()),
                        FilterBase.FromExpression <Share>(i => i.Name, name)
                    }
                }
            };

            // Act
            var result = await _client.Share.SearchAsync(request).ConfigureAwait(false);

            // Assert
            result.TotalResults.Should().Be(1);
            result.Results.First().Name.Should().Be(name);
        }
        public async Task ShouldCreateSearchAndDelete()
        {
            // Arrange
            var roles = await CreateRoles().ConfigureAwait(false);

            try
            {
                // Act
                var res = await _client.UserRole.SearchAsync(new UserRoleSearchRequest
                {
                    Filter = FilterBase.FromExpression <UserRole>(r => r.Names, "en", new[] { JamesBond, PeterGriffin })
                }).ConfigureAwait(false);

                // Assert
                res.Results.Should().HaveCount(2)
                .And.ContainSingle(r => r.Names.ContainsValue(JamesBond))
                .Which.UserRights.Should().ContainSingle(u => u == UserRight.ManageTransfer);

                res.Results.Should().ContainSingle(r => r.Names.ContainsValue(PeterGriffin))
                .Which.UserRights.Should().ContainSingle(u => u == UserRight.ManageChannels);
            }
            finally
            {
                await Delete(roles).ConfigureAwait(false);
            }
        }
        public void ShouldCreateTermFilterWithExpressionAndSchemaNamePrefixWithOverridenName()
        {
            // Act
            var termFilter = FilterBase.FromExpression <PersonSchema>(p => p.Name, "John");

            // Assert
            Assert.Equal("person.name", termFilter.Field);
        }
        public void ShouldCreateTermFilterWithExpressionAndSchemaNamePrefixAndSimpleAnalyzer()
        {
            // Act
            var termFilter = FilterBase.FromExpression <CarSchema>(p => p.Model, "Supercar", Analyzer.Simple);

            // Assert
            Assert.Equal("carSchema.model.simple", termFilter.Field);
        }
        public void ShouldCreateTermFilterWithExpressionPath()
        {
            // Act
            var termFilter = FilterBase.FromExpression <Person>(p => p.Car.Name, "Foo");

            // Assert
            Assert.Equal("car.name", termFilter.Field);
        }
        public void ShouldCreateTermFilterWithExpressionAndNGramAnalyzer()
        {
            // Act
            var termFilter = FilterBase.FromExpression <Person>(p => p.FirstName, "Foo", Analyzer.NGram);

            // Assert
            Assert.Equal("firstName.ngram", termFilter.Field);
            Assert.Equal("Foo", termFilter.Term);
        }
        public void ShouldCreateTermFilterWithExpression()
        {
            // Act
            var termFilter = FilterBase.FromExpression <Person>(p => p.FirstName, "Foo");

            // Assert
            Assert.Equal("firstName", termFilter.Field);
            Assert.Equal("Foo", termFilter.Term);
        }
        public void ShouldCreateTermsFilterWithExpressionAndLanguageAnalyzer()
        {
            // Act
            var termFilter = FilterBase.FromExpression <Person>(p => p.FirstName, Analyzer.Language, "Foo", "Bar");

            // Assert
            Assert.Equal("firstName.language", termFilter.Field);
            Assert.Equal(2, termFilter.Terms.Count);
            Assert.Equal("Foo", termFilter.Terms.ToList()[0]);
            Assert.Equal("Bar", termFilter.Terms.ToList()[1]);
        }
Example #9
0
        public async Task <string> GetExistingPictureparkAssetBinaryUuidAsync(string licensePurchaseTransactionUuid, string binaryUuid)
        {
            var filters = new List <FilterBase>
            {
                FilterBase.FromExpression <Content>(i => i.LayerSchemaIds, new string[] { nameof(SmintIoContentLayer) }),
                FilterBase.FromExpression <SmintIoContentLayer>(i => i.LicensePurchaseTransactionUuid, new string[] { licensePurchaseTransactionUuid })
            };

            filters.Add(FilterBase.FromExpression <SmintIoContentLayer>(i => i.BinaryUuid, new string[] { binaryUuid }));

            return(await GetFilterResultAsync(filters));
        }
Example #10
0
        public async Task <List <ContentItem <PressRelease> > > List(int start, int limit, string searchString)
        {
            var searchResult = await _client.Content.SearchAsync(new ContentSearchRequest
            {
                Start        = start,
                Limit        = limit,
                SearchString = searchString,
                Filter       = new AndFilter
                {
                    Filters = new List <FilterBase>
                    {
                        // Limit to PressRelease content
                        FilterBase.FromExpression <Content>(i => i.ContentSchemaId, nameof(PressRelease)),

                        // Filter out future publications
                        new DateRangeFilter
                        {
                            Field = "pressRelease.publishDate",
                            Range = new DateRange
                            {
                                To = "now"
                            }
                        }
                    }
                },
                Sort = new List <SortInfo>
                {
                    new SortInfo {
                        Field = "pressRelease.publishDate", Direction = SortDirection.Desc
                    }
                }
            });

            // Fetch details
            var contents = searchResult.Results.Any()
                ? await _client.Content.GetManyAsync(searchResult.Results.Select(i => i.Id),
                                                     new[]
            {
                ContentResolveBehavior.Content,
                ContentResolveBehavior.Owner
            })
                : new List <ContentDetail>();

            // Convert to C# poco
            var pressPortals = contents.AsContentItems <PressRelease>().ToList();

            return(pressPortals);
        }
Example #11
0
        public async Task <IReadOnlyList <UserDetail> > CreateAndActivateUsers(int userCount)
        {
            var usersToCreate = Enumerable.Range(0, userCount).Select(_ =>
                                                                      new UserCreateRequest
            {
                FirstName    = "Test",
                LastName     = "User",
                EmailAddress = $"test.user_{Guid.NewGuid()}@test.picturepark.com",
                LanguageCode = "en"
            }).ToArray();

            var userCreationTasks = usersToCreate.Select(userRequest => Client.User.CreateAsync(userRequest));

            var createdUsers = await Task.WhenAll(userCreationTasks);

            var searchRes = await Client.User.SearchAsync(new UserSearchRequest
            {
                Filter = FilterBase.FromExpression <User>(u => u.EmailAddress, usersToCreate.Select(u => u.EmailAddress).ToArray())
            });

            searchRes.Results.Select(e => e.EmailAddress).Should()
            .BeEquivalentTo(usersToCreate.Select(e => e.EmailAddress), "all users should have been created");

            foreach (var createdUser in createdUsers)
            {
                await Client.User.ReviewAsync(createdUser.Id, new UserReviewRequest
                {
                    Reviewed = true
                });
            }

            var createdUserIds = createdUsers.Select(u => u.Id);
            var reviewedUsers  = (await Client.User.GetManyAsync(createdUserIds)).ToArray();

            reviewedUsers.Should()
            .HaveCount(createdUsers.Length, "all previously created users should have been retrieved");

            reviewedUsers.Should().OnlyContain(
                u => u.AuthorizationState == AuthorizationState.Reviewed, "all invited users should be reviewed after review");

            foreach (var reviewedUser in reviewedUsers)
            {
                _createdUserIds.Enqueue(reviewedUser.Id);
            }

            return(reviewedUsers);
        }
        private async Task <UserDetail> GetUserDetails(TokenValidatedContext context)
        {
            var email = context.Principal.Identity.Name;

            var results = await _cpClient.User.SearchAsync(new UserSearchRequest
            {
                Filter = FilterBase.FromExpression <User>(u => u.EmailAddress, email)
            });

            if (results.Results.Count != 1)
            {
                throw new Exception("Unable to find the logged-in user in CP");
            }

            var userId = results.Results.Single().Id;

            return(await _cpClient.User.GetAsync(userId));
        }
Example #13
0
        public async Task ShouldGetObjectResolved()
        {
            // Arrange
            var countrySchemaId = SchemaFixture.CountrySchemaId;

            var chSearch = await _client.ListItem.SearchAsync(new ListItemSearchRequest
            {
                Filter    = FilterBase.FromExpression <Country>(c => c.Name, "Switzerland"),
                SchemaIds = new[] { countrySchemaId }
            }).ConfigureAwait(false);

            chSearch.Results.Should().NotBeEmpty("Switzerland should exist");

            // Act
            var listItem = await _client.ListItem.GetAsync(chSearch.Results.First().Id, new[] { ListItemResolveBehavior.Content, ListItemResolveBehavior.LinkedListItems }).ConfigureAwait(false);

            // Assert
            listItem.ContentSchemaId.Should().Be(countrySchemaId);

            var region = ((Newtonsoft.Json.Linq.JObject)listItem.Content)["regions"].First();

            region["name"].Should().NotBeNull("the regions should be resolved");
        }
Example #14
0
        private async Task <UserDetail> GetUserDetails(TokenValidatedContext context)
        {
            var email = context.Principal.Identity.Name;

            if (string.IsNullOrEmpty(email) || !email.Contains('@'))
            {
                throw new Exception($"Invalid or empty user email: '{email}'");
            }

            var results = await _cpClient.User.SearchAsync(new UserSearchRequest
            {
                Filter = FilterBase.FromExpression <User>(u => u.EmailAddress, email)
            });

            if (results.Results.Count != 1)
            {
                return(null);
            }

            var userId = results.Results.Single().Id;

            return(await _cpClient.User.GetAsync(userId));
        }
Example #15
0
        private async Task <(CreateTransferResult, string fileId)> CreateFileTransferAsync()
        {
            var transferName = new Random().Next(1000, 9999).ToString();
            var files        = new FileLocations[]
            {
                Path.Combine(_fixture.ExampleFilesBasePath, "0030_JabLtzJl8bc.jpg")
            };

            var createTransferResult = await _client.Transfer.CreateAndWaitForCompletionAsync(transferName, files).ConfigureAwait(false);

            await _client.Transfer.UploadFilesAsync(createTransferResult.Transfer, files, new UploadOptions()).ConfigureAwait(false);

            var searchRequest = new FileTransferSearchRequest
            {
                Limit        = 1,
                SearchString = "*",
                Filter       = FilterBase.FromExpression <FileTransfer>(i => i.TransferId, createTransferResult.Transfer.Id)
            };
            var searchResult = await _client.Transfer.SearchFilesAsync(searchRequest).ConfigureAwait(false);

            var fileId = searchResult.Results.ToList()[0].Id;

            return(createTransferResult, fileId);
        }
Example #16
0
        public async Task ShouldSearchListItemsAndScrollThroughResults()
        {
            // Arrange
            // ---------------------------------------------------------------------------
            // Get a list of MetadataSchemaIds
            // ---------------------------------------------------------------------------
            var searchRequestSchema = new SchemaSearchRequest
            {
                Limit  = 2,
                Filter = FilterBase.FromExpression <Schema>(i => i.Types, SchemaType.List.ToString())
            };

            var searchResultSchema = await _client.Schema.SearchAsync(searchRequestSchema).ConfigureAwait(false);

            Assert.True(searchResultSchema.Results.Any());

            List <string> metadataSchemaIds = searchResultSchema.Results
                                              .Select(i => i.Id)
                                              .OrderBy(i => i)
                                              .ToList();

            var searchRequestObject = new ListItemSearchRequest()
            {
                Limit = 100
            };
            var           items = new List <ListItem>();
            List <string> failedMetadataSchemaIds = new List <string>();

            // Act
            // ---------------------------------------------------------------------------
            // Loop over all metadataSchemaIds and make a search for each metadataSchemaId
            // ---------------------------------------------------------------------------
            foreach (var metadataSchemaId in metadataSchemaIds)
            {
                searchRequestObject.SchemaIds = new List <string> {
                    metadataSchemaId
                };
                searchRequestObject.PageToken = null;

                try
                {
                    int i = 0;
                    ListItemSearchResult searchResultObject;

                    do
                    {
                        searchResultObject = await _client.ListItem.SearchAsync(searchRequestObject).ConfigureAwait(false);

                        if (searchResultObject.Results.Any())
                        {
                            items.AddRange(searchResultObject.Results);
                        }
                    }while (++i < 3 && ((searchRequestObject.PageToken = searchResultObject.PageToken) != null));
                }
                catch (Exception)
                {
                    failedMetadataSchemaIds.Add(metadataSchemaId);
                }
            }

            // Assert
            Assert.True(!failedMetadataSchemaIds.Any());
            Assert.True(items.Any());
        }
        public async Task ShouldSearchAnalyzedFields()
        {
            // Arrange
            if (!await _client.Schema.ExistsAsync(nameof(AnalyzerTestObject)).ConfigureAwait(false))
            {
                var schemas = await _client.Schema.GenerateSchemasAsync(typeof(AnalyzerTestObject)).ConfigureAwait(false);

                var schemasToCreate = new List <SchemaDetail>();
                var schemasToUpdate = new List <SchemaDetail>();

                foreach (var schema in schemas)
                {
                    if (await _client.Schema.ExistsAsync(schema.Id).ConfigureAwait(false))
                    {
                        schemasToUpdate.Add(schema);
                    }
                    else
                    {
                        schemasToCreate.Add(schema);
                    }
                }

                await _client.Schema.CreateManyAsync(schemasToCreate, false, TimeSpan.FromMinutes(1)).ConfigureAwait(false);

                foreach (var schema in schemasToUpdate)
                {
                    await _client.Schema.UpdateAsync(schema, true, TimeSpan.FromMinutes(1)).ConfigureAwait(false);
                }

                var analyzerValue = new AnalyzerTestObject
                {
                    EdgeNGramField = "EdgeNGramFieldValue",
                    LanguageField  = new TranslatedStringDictionary
                    {
                        { "en", "Cities" }
                    },
                    NGramField         = "NGramFieldValue",
                    PathHierarchyField = "Path/Hierarchy/Field",
                    SimpleField        = "Simple12Field"
                };

                var res = await _client.ListItem.CreateFromObjectAsync(analyzerValue).ConfigureAwait(false);

                var resDetail = await res.FetchDetail().ConfigureAwait(false);

                resDetail.SucceededItems.Should().NotBeEmpty();
            }

            var requestSchemaIds = new[] { nameof(AnalyzerTestObject) };

            var simpleResults = await _client.ListItem.SearchAsync(new ListItemSearchRequest
            {
                SchemaIds = requestSchemaIds,
                Filter    = FilterBase.FromExpression <AnalyzerTestObject>(o => o.SimpleField, "simple", Analyzer.Simple)
            }).ConfigureAwait(false);

            Assert.True(simpleResults.TotalResults > 0);

            var pathResults = await _client.ListItem.SearchAsync(new ListItemSearchRequest
            {
                SchemaIds = requestSchemaIds,
                Filter    = FilterBase.FromExpression <AnalyzerTestObject>(o => o.PathHierarchyField, "Path/Hierarchy", Analyzer.PathHierarchy)
            }).ConfigureAwait(false);

            Assert.True(pathResults.TotalResults > 0);

            var languageResults = await _client.ListItem.SearchAsync(new ListItemSearchRequest
            {
                SchemaIds = requestSchemaIds,
                Filter    = FilterBase.FromExpression <AnalyzerTestObject>(o => o.LanguageField, "citi", language: "en", useAnalyzer: true)
            }).ConfigureAwait(false);

            Assert.True(languageResults.TotalResults > 0);

            var edgeNgramResults = await _client.ListItem.SearchAsync(new ListItemSearchRequest
            {
                SchemaIds = requestSchemaIds,
                Filter    = FilterBase.FromExpression <AnalyzerTestObject>(o => o.EdgeNGramField, "edg", Analyzer.EdgeNGram)
            }).ConfigureAwait(false);

            Assert.True(edgeNgramResults.TotalResults > 0);

            var ngramResults = await _client.ListItem.SearchAsync(new ListItemSearchRequest
            {
                SchemaIds = requestSchemaIds,
                Filter    = FilterBase.FromExpression <AnalyzerTestObject>(o => o.NGramField, "mfield", Analyzer.NGram)
            }).ConfigureAwait(false);

            Assert.True(ngramResults.TotalResults > 0);
        }