private async Task <List <ContentItemIdentifier> > GetAllUserItemIdentifiers() { List <ContentItemIdentifier> listIds = new List <ContentItemIdentifier>(); ListingResponseModel <ContentItemModel> response = await managementClient.ListContentItemsAsync(); // this is guid of Content Type "User" in the KC project ObjectIdentifier userContentType = new ObjectIdentifier() { Id = Guid.Parse("eaf7e4c9-0a4d-46dc-b787-ef02c9860592") }; while (true) { foreach (var item in response) { if (item.Type == userContentType) { listIds.Add(ContentItemIdentifier.ById(item.Id)); } } if (!response.HasNextPage()) { break; } response = await response.GetNextPage(); } return(listIds); }
private async Task DeleteAllItems(List <ContentItemModel> contentItems) { var allTasks = new List <Task>(); var throttler = new SemaphoreSlim(initialCount: 2); foreach (var item in contentItems) { await throttler.WaitAsync(); allTasks.Add( Task.Run(async() => { try { logger.Info("Deleting item:" + item.Id); await managementClient.DeleteContentItemAsync(ContentItemIdentifier.ById(item.Id)); } catch (KenticoCloud.ContentManagement.Exceptions.ContentManagementException e) { logger.Error(e, "Something went wrong deleting item."); } finally { throttler.Release(); } })); } await Task.WhenAll(allTasks); }
internal async Task <ContentItemVariantModel <UserModel> > CreateUser(IntercomUser user) { string itemName; if (user.Type == "admin") { itemName = user.Name; } else { itemName = user.Id; } var userItem = await CreateUserItem(itemName, user.Id); UserModel userModel = new UserModel { Name = user.Name, Type = user.Type, Email = user.Email, Id = user.Id, IntercomLink = "<p><a href=\"" + IntercomFunctions.GetIntercomUserLink(user.Id, user.Type) + "\">Link to intercom</a></p>" }; var userVariant = await CreateUserVariant(userModel, ContentItemIdentifier.ById(userItem.Id)); var publishUser = await PublishItemVariant(userItem.Id.ToString()); return(userVariant); }
internal async Task <ContentItemVariantModel <UserModel> > TryGetExistingUserVariant(string userId) { if (!userItemVariants.ContainsKey(userId)) { ContentItemVariantModel <UserModel> userVariant = null; try { ContentItemIdentifier userItemIdentifier = ContentItemIdentifier.ByExternalId(userId); ContentItemVariantIdentifier variantIdentifier = new ContentItemVariantIdentifier(userItemIdentifier, LanguageIdentifier.DEFAULT_LANGUAGE); userVariant = await GetUserVariant(variantIdentifier); logger.Debug("Downloaded existing user variant: " + userVariant.Elements.Name); userItemVariants.Add(userVariant.Elements.Id, userVariant); } catch (ContentManagementException e) { if (e.StatusCode != HttpStatusCode.NotFound) { throw e; } return(null); } } return(userItemVariants[userId]); }
public void BuildItemUrl_ItemExternalId_ReturnsCorrectUrl() { var identifier = ContentItemIdentifier.ByExternalId(ITEM_EXTERNAL_ID); var actualUrl = _builder.BuildItemUrl(identifier); var expectedUrl = $"{ENDPOINT}/projects/{PROJECT_ID}/items/external-id/{EXPECTED_ITEM_EXTERNAL_ID}"; Assert.Equal(expectedUrl, actualUrl); }
public void BuildListVariantsUrl_ItemId_ReturnsCorrectUrl() { var identifier = ContentItemIdentifier.ById(ITEM_ID); var actualUrl = _builder.BuildListVariantsUrl(identifier); var expectedUrl = $"{ENDPOINT}/projects/{PROJECT_ID}/items/{ITEM_ID}/variants"; Assert.Equal(expectedUrl, actualUrl); }
public void BuildItemUrl_ItemCodename_ReturnsCorrectUrl() { var identifier = ContentItemIdentifier.ByCodename(ITEM_CODENAME); var actualUrl = _builder.BuildItemUrl(identifier); var expectedUrl = $"{ENDPOINT}/projects/{PROJECT_ID}/items/codename/{ITEM_CODENAME}"; Assert.Equal(expectedUrl, actualUrl); }
public void BuildContentItemVariantsUrl_ItemCodenameVariantCodename_ReturnsCorrectUrl() { var itemIdentifier = ContentItemIdentifier.ByCodename(ITEM_CODENAME); var variantIdentifier = LanguageIdentifier.ByCodename(VARIANT_CODENAME); var identifier = new ContentItemVariantIdentifier(itemIdentifier, variantIdentifier); var actualUrl = _builder.BuildVariantsUrl(identifier); var expectedUrl = $"{ENDPOINT}/projects/{PROJECT_ID}/items/codename/{ITEM_CODENAME}/variants/codename/{VARIANT_CODENAME}"; Assert.Equal(expectedUrl, actualUrl); }
public void BuildContentItemVariantsUrl_ItemExternalIdVariantId_ReturnsCorrectUrl() { var itemIdentifier = ContentItemIdentifier.ByExternalId(ITEM_EXTERNAL_ID); var variantIdentifier = LanguageIdentifier.ById(VARIANT_ID); var identifier = new ContentItemVariantIdentifier(itemIdentifier, variantIdentifier); var actualUrl = _builder.BuildVariantsUrl(identifier); var expectedUrl = $"{ENDPOINT}/projects/{PROJECT_ID}/items/external-id/{EXPECTED_ITEM_EXTERNAL_ID}/variants/{VARIANT_ID}"; Assert.Equal(expectedUrl, actualUrl); }
/// <summary> /// Deletes given content item. /// </summary> /// <param name="identifier">The identifier of the content item.</param> public async Task DeleteContentItemAsync(ContentItemIdentifier identifier) { if (identifier == null) { throw new ArgumentNullException(nameof(identifier)); } var endpointUrl = _urlBuilder.BuildItemUrl(identifier); await _actionInvoker.InvokeMethodAsync(endpointUrl, HttpMethod.Delete); }
/// <summary> /// Returns strongly typed content item. /// </summary> /// <param name="identifier">The identifier of the content item.</param> /// <returns>The <see cref="ContentItemModel"/> instance that represents requested content item.</returns> public async Task <ContentItemModel> GetContentItemAsync(ContentItemIdentifier identifier) { if (identifier == null) { throw new ArgumentNullException(nameof(identifier)); } var endpointUrl = _urlBuilder.BuildItemUrl(identifier); var response = await _actionInvoker.InvokeReadOnlyMethodAsync <ContentItemModel>(endpointUrl, HttpMethod.Get); return(response); }
internal static async Task <ContentItemVariantModel> PrepareTestVariant(ContentManagementClient client, string languageCodename, object elements, ContentItemModel item) { var addedItemIdentifier = ContentItemIdentifier.ByCodename(item.CodeName); var addedLanguageIdentifier = LanguageIdentifier.ByCodename(languageCodename); var addedContentItemLanguageIdentifier = new ContentItemVariantIdentifier(addedItemIdentifier, addedLanguageIdentifier); var variantUpdateModel = new ContentItemVariantUpsertModel() { Elements = elements }; return(await client.UpsertContentItemVariantAsync(addedContentItemLanguageIdentifier, variantUpdateModel)); }
private ConversationModel CreateConversationModel(Conversation conversation) { var messages = CreateRichTextCompatibleConversationString(conversation); var tags = CreateTagsString(conversation); string intercomConversationLinkRichText = "<p><a href=\"" + IntercomFunctions.GetIntercomConversationLink(conversation) + "\">Link to intercom</a></p>"; List <ContentItemIdentifier> assignees = new List <ContentItemIdentifier>() { }; List <ContentItemIdentifier> author = new List <ContentItemIdentifier>() { }; if (conversation.assignee.id != null) //unassigned conversation { assignees.Add(ContentItemIdentifier.ByExternalId(currentConversationUsers .Where(x => x.Id.Equals(conversation.assignee.id, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault() .Id)); } author.Add(ContentItemIdentifier.ByExternalId(currentConversationUsers .Where(x => x.Id.Equals(conversation.conversation_message.author.id, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault() .Id)); ConversationModel conversationModel = new ConversationModel { IntercomLink = intercomConversationLinkRichText, Author = author, CreatedAt = Tools.FromUnixTimestamp(conversation.created_at), LastUpdated = Tools.FromUnixTimestamp(conversation.updated_at), Assignee = assignees, Messages = messages, RatingValue = conversation.conversation_rating.rating, RatingNote = conversation.conversation_rating.remark, Tags = tags, SearchBody = CreateSearchBody(conversation), /*Participants = userItemVariants * .Where(userReferences => participants.Any(participant => participant.Id.Equals(userReferences.Key, StringComparison.OrdinalIgnoreCase))) * .Select(userReference => userReference.Value) * .ToList(),*/ Participants = currentConversationUsers .Select(x => ContentItemIdentifier.ByExternalId(x.Id)) .ToList(), MessageCount = IntercomFunctions.GetConversationMessageCount(conversation), ConversationId = conversation.id }; return(conversationModel); }
public static (ContentItemIdentifier, LanguageIdentifier, ContentItemVariantIdentifier) GetIdentifiers(string ContentItemCodeName) { //Retrieive an ItemIdentifier by codename of the content item we want to create a new version of ContentItemIdentifier itemIdentifier = ContentItemIdentifier.ByCodename(ContentItemCodeName); //Retreive the language identifier of the content item in Konent for the content item (even if we only have one) LanguageIdentifier langIdentifier = LanguageIdentifier.ByCodename(RowlingAppConstants.DefaultLanguageCode); //Retreive the content item language variant of the content item we want to update (the real unique identifier) ContentItemVariantIdentifier identifier = new ContentItemVariantIdentifier(itemIdentifier, langIdentifier); return(itemIdentifier, langIdentifier, identifier); }
/// <summary> /// Updates given content item. /// </summary> /// <param name="identifier">The identifier of the content item.</param> /// <param name="contentItem">Represents updated content item.</param> /// <returns>The <see cref="ContentItemModel"/> instance that represents updated content item.</returns> public async Task <ContentItemModel> UpdateContentItemAsync(ContentItemIdentifier identifier, ContentItemUpdateModel contentItem) { if (identifier == null) { throw new ArgumentNullException(nameof(identifier)); } if (contentItem == null) { throw new ArgumentNullException(nameof(contentItem)); } var endpointUrl = _urlBuilder.BuildItemUrl(identifier); var response = await _actionInvoker.InvokeMethodAsync <ContentItemUpdateModel, ContentItemModel>(endpointUrl, HttpMethod.Put, contentItem); return(response); }
public async Task <string> UpsertTaxonomy(Movie movie, string listing_prediction) { MovieImport stronglyTypedElements = new MovieImport { ListedIn = new[] { TaxonomyTermIdentifier.ByCodename(listing_prediction) } }; // Specifies the content item and the language variant ContentItemIdentifier itemIdentifier = ContentItemIdentifier.ByCodename(movie.System.Codename); LanguageIdentifier languageIdentifier = LanguageIdentifier.ByCodename(movie.System.Language); ContentItemVariantIdentifier identifier = new ContentItemVariantIdentifier(itemIdentifier, languageIdentifier); // Upserts a language variant of your content item ContentItemVariantModel <MovieImport> response = await client.UpsertContentItemVariantAsync(identifier, stronglyTypedElements); return(response.Elements.Title + " updated."); }
/// <summary> /// Inserts or updates content item according to external identifier. /// </summary> /// <param name="externalId">The external identifier of the content item.</param> /// <param name="contentItem">Represents inserted or updated content item.</param> /// <returns>The <see cref="ContentItemModel"/> instance that represents inserted or updated content item.</returns> public async Task <ContentItemModel> UpsertContentItemByExternalIdAsync(string externalId, ContentItemUpsertModel contentItem) { if (string.IsNullOrEmpty(externalId)) { throw new ArgumentException("The external id is not specified.", nameof(externalId)); } if (contentItem == null) { throw new ArgumentNullException(nameof(contentItem)); } var endpointUrl = _urlBuilder.BuildItemUrl(ContentItemIdentifier.ByExternalId(externalId)); var response = await _actionInvoker.InvokeMethodAsync <ContentItemUpsertModel, ContentItemModel>(endpointUrl, HttpMethod.Put, contentItem); return(response); }
private string GetItemUrlSegment(ContentItemIdentifier identifier) { if (identifier.Id != null) { return(string.Format(URL_TEMPLATE_ITEM_ID, identifier.Id)); } if (!string.IsNullOrEmpty(identifier.Codename)) { return(string.Format(URL_TEMPLATE_ITEM_CODENAME, identifier.Codename)); } if (!string.IsNullOrEmpty(identifier.ExternalId)) { return(BuildItemUrlSegmentFromExternalId(identifier.ExternalId)); } throw new ArgumentException("You must provide item's id, codename or externalId"); }
private static void ImportMovies(string folderPath, ContentManagementClient client) { foreach (var movie in DatabaseEntry.CreateFromFolder(Path.Combine(folderPath, "Movies"))) { Console.WriteLine($"Importing {movie.GetText("Name")}"); var imageExternalIds = ImportMoviePhotos(movie, folderPath, client); var externalId = $"Movie - {movie.ExternalId}"; var item = new ContentItemUpsertModel { Name = movie.GetText("Name"), Type = ContentTypeIdentifier.ByCodename("movie"), SitemapLocations = movie.GetListItems("Sitemap location").Select(x => SitemapNodeIdentifier.ByCodename(GetCodename(x))) }; client.UpsertContentItemByExternalIdAsync(externalId, item); var itemIdentifier = ContentItemIdentifier.ByExternalId(externalId); var languageIdentifier = LanguageIdentifier.DEFAULT_LANGUAGE; var variant = new ContentItemVariantUpsertModel { Elements = new { name = movie.GetText("Name"), description = movie.GetText("Description"), synopsis = movie.GetText("Synopsis"), release_date = movie.GetDateTime("Release date"), genre = movie.GetListItems("Genres").Select(x => TaxonomyTermIdentifier.ByCodename(GetCodename(x))), cast = movie.GetListItems("Cast").Select(x => ContentItemIdentifier.ByExternalId($"Actor - {x}")), imdb_rating = movie.GetNumber("IMDB rating"), rating = new [] { MultipleChoiceOptionIdentifier.ByCodename(GetCodename(movie.GetText("Rating"))) }, slug = movie.GetText("Slug"), photos = imageExternalIds.Select(imageExternalId => AssetIdentifier.ByExternalId(imageExternalId)) }, }; client.UpsertContentItemVariantAsync(new ContentItemVariantIdentifier(itemIdentifier, languageIdentifier), variant); } }
internal async Task <(ContentItemVariantModel <ConversationModel> variant, bool success)> SyncSingle(Conversation intercomConversation, ContentItemVariantModel <ConversationModel> conversationVariant, List <ContentItemVariantModel <UserModel> > conversationUserVariants) { currentConversationId = intercomConversation.id; currentConversationUsers = new List <UserModel>() { }; currentConversationUsers.AddRange(conversationUserVariants.Select(x => x.Elements)); ContentItemModel conversationItem = null; Guid itemIdentifier = Guid.Empty; // If conversation doesn't exist, create item for it if (conversationVariant == null) { try { logger.Debug("Creating item for conversation: " + currentConversationId); conversationItem = await CreateConversationItem(currentConversationId); itemIdentifier = conversationItem.Id; } catch (ContentManagementException e) { logger.Error(e, "Unable to create item for conversation: " + currentConversationId); return(null, false); } } else { itemIdentifier = conversationVariant.Item.Id; } // Fill model with data var model = CreateConversationModel(intercomConversation); logger.Debug("Creating item variant for conversation: " + currentConversationId); var variant = await UpsertConversationVariant(model, ContentItemIdentifier.ById(itemIdentifier)); var publishConversation = await PublishItemVariant(itemIdentifier.ToString()); return(variant, true); }
public async static Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log, ExecutionContext context) { try { var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); string strLanguageCode = config["KenticoCloudLanguageCode"]; ContentManagementOptions options = new ContentManagementOptions { ProjectId = config["KenticoCloudProjectID"], ApiKey = config["KenticoCloudContentManagementAPIKey"] }; // Initializes an instance of the ContentManagementClient client ContentManagementClient client = new ContentManagementClient(options); // Defines the content elements to update Task <string> body = new StreamReader(req.Body).ReadToEndAsync(); ArticleModel NewArticleModel = JsonConvert.DeserializeObject <ArticleModel>(body.Result.ToString()); // Specifies the content item and the language variant ContentItemIdentifier itemIdentifier = ContentItemIdentifier.ByCodename(NewArticleModel.OriginalCodename); LanguageIdentifier languageIdentifier = LanguageIdentifier.ByCodename(strLanguageCode); ContentItemVariantIdentifier identifier = new ContentItemVariantIdentifier(itemIdentifier, languageIdentifier); // Upserts a language variant of your content item ContentItemVariantModel <Article> responseUpdate = await client.UpsertContentItemVariantAsync <Article>(identifier, NewArticleModel.NewArticle); return((ActionResult) new OkObjectResult($"SUCCESS: Language variant added!")); } catch (Exception ex) { return(new OkObjectResult("FAILURE: " + ex.Message)); } }
internal async Task DeleteItems(List <string> externalIds) { foreach (var itemId in externalIds) { try { await managementClient.DeleteContentItemAsync(ContentItemIdentifier.ByExternalId(itemId)); //processedItems.Add(itemId, true); } catch (Exception e) { logger.Error(e, "Deleting of item " + itemId + "failed."); } finally { //processedItems.Add(itemId, false); } } }
private async Task <List <ContentItemIdentifier> > GetAllItemIdentifiers() { List <ContentItemIdentifier> listIds = new List <ContentItemIdentifier>(); ListingResponseModel <ContentItemModel> response = await managementClient.ListContentItemsAsync(); while (true) { foreach (var item in response) { listIds.Add(ContentItemIdentifier.ById(item.Id)); } if (!response.HasNextPage()) { break; } response = await response.GetNextPage(); } return(listIds); }
/// <summary> /// Adds language variant content to the content item with the supplied codename /// </summary> /// <param name="codename">Codename of the content item needed</param> /// <returns></returns> public async Task <Guid> CreateItemVariantAsync(string codename) { const string htmlMarkup = @"<h1>Some content</h1> <p>This is the content</p>"; if (!IsValidHtml(htmlMarkup)) { return(Guid.Empty); } var content = new SimplePage { PageTitle = "Test import", PageContent = htmlMarkup, DishColour = new[] { TaxonomyTermIdentifier.ByCodename("green") }, PageTeaser = new AssetIdentifier[0] }; // Specifies the content item and the language variant ContentItemIdentifier itemIdentifier = ContentItemIdentifier.ByCodename(codename); LanguageIdentifier languageIdentifier = LanguageIdentifier.DEFAULT_LANGUAGE; ContentItemVariantIdentifier identifier = new ContentItemVariantIdentifier(itemIdentifier: itemIdentifier, languageIdentifier: languageIdentifier); // Upserts a language variant of your content item try { ContentItemVariantModel <SimplePage> response = await _managementClient.UpsertContentItemVariantAsync <SimplePage>(identifier, content); return(response.Item.Id); } catch (Exception ex) { Console.WriteLine($"ERROR: {ex.Message}"); return(Guid.Empty); } }
private static void ImportActors(string folderPath, ContentManagementClient client) { foreach (var actor in DatabaseEntry.CreateFromFolder(Path.Combine(folderPath, "Actors"))) { Console.WriteLine($"Importing {actor.GetText("Name")}"); var imageExternalId = ImportActorPhoto(actor, folderPath, client); var externalId = $"Actor - {actor.ExternalId}"; var item = new ContentItemUpsertModel { Name = actor.GetText("Name"), Type = ContentTypeIdentifier.ByCodename("actor"), }; client.UpsertContentItemByExternalIdAsync(externalId, item); var itemIdentifier = ContentItemIdentifier.ByExternalId(actor.ExternalId); var languageIdentifier = LanguageIdentifier.DEFAULT_LANGUAGE; var variant = new ContentItemVariantUpsertModel { Elements = new { name = actor.GetText("Name"), born = actor.GetDateTime("Born"), bio = actor.GetText("Bio"), photo = new [] { AssetIdentifier.ByExternalId(imageExternalId) } }, }; client.UpsertContentItemVariantAsync( new ContentItemVariantIdentifier(itemIdentifier, languageIdentifier), variant ); } }
/// <summary> /// Updates the given content item. /// </summary> /// <param name="client">Content management client instance.</param> /// <param name="identifier">Identifies which content item will be updated. </param> /// <param name="contentItem">Specifies data for updated content item.</param> /// <returns>The <see cref="ContentItemModel"/> instance that represents updated content item.</returns> public static async Task <ContentItemModel> UpdateContentItemAsync(this ContentManagementClient client, ContentItemIdentifier identifier, ContentItemModel contentItem) { if (identifier == null) { throw new ArgumentNullException(nameof(identifier)); } if (contentItem == null) { throw new ArgumentNullException(nameof(contentItem)); } var contentItemUpdateModel = new ContentItemUpdateModel(contentItem); return(await client.UpdateContentItemAsync(identifier, contentItemUpdateModel)); }
/// <summary> /// Returns strongly typed listing of content item variants with strongly typed elements for specified content item. /// </summary> /// <typeparam name="T">Type of the content item elements</typeparam> /// <param name="identifier">The identifier of the content item.</param> /// <returns>A strongly-typed collection with content item variants.</returns> public async Task <List <ContentItemVariantModel <T> > > ListContentItemVariantsAsync <T>(ContentItemIdentifier identifier) where T : new() { if (identifier == null) { throw new ArgumentNullException(nameof(identifier)); } var endpointUrl = _urlBuilder.BuildListVariantsUrl(identifier); var response = await _actionInvoker.InvokeReadOnlyMethodAsync <List <ContentItemVariantModel> >(endpointUrl, HttpMethod.Get); return(response.Select(x => _modelProvider.GetContentItemVariantModel <T>(x)).ToList()); }
internal string BuildItemUrl(ContentItemIdentifier identifier) { var itemSegment = GetItemUrlSegment(identifier); return(GetUrl(itemSegment)); }
/// <summary> /// Returns strongly typed listing of content item variants for specified content item. /// </summary> /// <param name="identifier">The identifier of the content item.</param> /// <returns>The <see cref="IEnumerable{ContentItemVariantModel}"/> instance that represents the listing of content item variants.</returns> public async Task <IEnumerable <ContentItemVariantModel> > ListContentItemVariantsAsync(ContentItemIdentifier identifier) { if (identifier == null) { throw new ArgumentNullException(nameof(identifier)); } var endpointUrl = _urlBuilder.BuildListVariantsUrl(identifier); var response = await _actionInvoker.InvokeReadOnlyMethodAsync <IEnumerable <ContentItemVariantModel> >(endpointUrl, HttpMethod.Get); return(response); }
internal string BuildListVariantsUrl(ContentItemIdentifier identifier) { var itemSegment = GetItemUrlSegment(identifier); return(GetUrl(string.Concat(itemSegment, URL_VARIANT))); }