How to use TaxonomyService.UpdateTerms against a BlogPostPart from code

Mar 8, 2012 at 8:34 PM
Edited Mar 9, 2012 at 6:36 PM

I have a site where I am using the taxonomy module to categorize blog posts. I am in the process of working through the import of existing wordpress posts and I am attempting to automate the assignment of TermParts to the BlogPostPart.

The actual line that fires in my import code is:

 

_taxonomyService.UpdateTerms(blogPost.ContentItem, postCategories, "Categories");

 

Inside the UpdateTerms method - which comes from the taxonomy module - is where I get the failure. The following conversion always returns null:

 

var termsPart = contentItem.As<TermsPart>();

 

Even though the TermsPart is shown as associated with the BlogPost part I can never access it using this conversion method. So my question is how do I use code to associate a taxonomy term with a content item?

Thanks

Mar 9, 2012 at 6:38 PM
Edited Mar 9, 2012 at 6:39 PM

So yeah like most things in life I was part of the problem. The issue was not with the taxonomy infrastructure it was with my understanding of what was going on as well as simple coding mistakes.

I had originally not understood the difference between the TermPart and TermsPart as well as understanding the importance of having the third parameter of the UpdateTerms method accurate to what the taxonomy name was.

You can use the TaxonomyService to update using the UpdateTerms method. If anyone ever wants the full code for the blog import I am happy to share.

Mar 12, 2012 at 5:10 PM

Hi Jhresh
Absolutely it would be helpful if you share us what you understood and done with taxonomies.

Mar 26, 2012 at 4:46 PM
Edited Mar 26, 2012 at 4:49 PM

Here it goes:

The problem that I wanted to solve was migrating my blog from wordpress to orchard. There are multiple solutions out there but what I was looking for was the simplest thing that would work. What I found was a github project that seemed like it fit the bill: https://github.com/moberg/WordpressImport.

What follows is the modifications that I made to that particular code base. The two changes that I made were the mapping of the original URL to the new autoroute bits and the addition of code to properly map the wordpress category to the taxonomy bits. If you refer to the original source the only file I modified is the admincontroller.cs

constructor was modified to inject the ITaxonomyService:

 

	    public AdminController(
            ITaxonomyService taxonomyService,
			IOrchardServices services,
			ISignals signals,
			IBlogService blogService, 
			IBlogPostService blogPostService, 
			ITagService tagsService,
			ICommentService commentService) {
		    _taxonomyService = taxonomyService;
		    _signals = signals;
		    _blogService = blogService;
			_blogPostService = blogPostService;
			_tagsService = tagsService;
			_commentService = commentService;
			Services = services;
		}

 

Index post action was modified to pull the existing taxonomy for my blog categories, and reconcile the wordpress blog posts category against this source, and finally update the taxonomy for the newly created post in orchard:

Map individual blog post URL to new autoroute part:

				if (isPublished) {
					blogPost.Get<AutoroutePart>().DisplayAlias = slug;
				}

Pull existing taxonomy for mapping:

 

            var taxonomy = _taxonomyService.GetTaxonomyByName("Categories");
		    IEnumerable<TermPart> categories = null;

            if(taxonomy != null) {
                categories = _taxonomyService.GetTerms(taxonomy.Id);
            }

Map individual blog post to existing taxonomy:

                if (categories != null)
                {
                    var postCategories = post.CategorieNames.
                                            Select(category =>
                                                    categories.SingleOrDefault(term => term.Name == category)).
                                                    Where(termPart => termPart != null).ToList();
                    _taxonomyService.UpdateTerms(blogPost.ContentItem, postCategories, "Category");
                }

Full method:

 

[HttpPost, ActionName("Index")]
		public ActionResult IndexPost(IndexViewModel viewModel)
		{
			if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not allowed to manage cache")))
				return new HttpUnauthorizedResult();

            var wordpress = new WordpressXmlParser(Request.Files[0].InputStream);
			var blog = _blogService.Get(int.Parse(Request.Params["BlogId"]), VersionOptions.Latest).As<BlogPart>();

            if (blog == null)
                return HttpNotFound();

            var taxonomy = _taxonomyService.GetTaxonomyByName("Categories");
		    IEnumerable<TermPart> categories = null;

            if(taxonomy != null) {
                categories = _taxonomyService.GetTerms(taxonomy.Id);
            }

			var posts = wordpress.GetPosts().ToList();
			foreach (var post in posts) {

				var uri = new Uri(post.Link);
				var slug = uri.PathAndQuery.TrimStart('/');
				var blogPost = Services.ContentManager.New<BlogPostPart>("BlogPost");

				blogPost.BlogPart = blog;
				blogPost.Title = post.Title;
				blogPost.Text = post.Content;
				blogPost.Get<CommonPart>().CreatedUtc = post.Date;

				var isPublished = !slug.StartsWith("?");

				if (isPublished) {
					blogPost.Get<AutoroutePart>().DisplayAlias = slug;
				}

				if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, blogPost, T("Couldn't create blog post"))) {
					return new HttpUnauthorizedResult();
				}

                if (categories != null)
                {
                    var postCategories = post.CategorieNames.
                                            Select(category =>
                                                    categories.SingleOrDefault(term => term.Name == category)).
                                                    Where(termPart => termPart != null).ToList();
                    _taxonomyService.UpdateTerms(blogPost.ContentItem, postCategories, "Category");
                }

				Services.ContentManager.Create(blogPost, isPublished ? VersionOptions.Published : VersionOptions.Draft);
                blogPost.Get<CommonPart>().PublishedUtc = post.Date;

				_tagsService.UpdateTagsForContentItem(blogPost.ContentItem, post.Tags);

                foreach (var wpComment in post.Comments) {
					WpComment wpComment1 = wpComment;
					var fun = Services.ContentManager.Create<CommentPart>("Comment", comment => {
					    comment.Record.Author = wpComment1.AuthorName;
					    comment.Record.CommentDateUtc = wpComment1.Date;
					    comment.Record.CommentText = wpComment1.Content;
					    comment.Record.Email = wpComment1.AuthorEmail;
					    comment.Record.SiteName = wpComment1.AuthorUrl;
						comment.Record.UserName = null;
					    comment.Record.CommentedOn = blogPost.Id;
						comment.Record.Status = CommentStatus.Approved;
					    
						var commentedOn = Services.ContentManager.Get<ICommonPart>(comment.Record.CommentedOn);
					    if (commentedOn != null && commentedOn.Container != null) {
					        comment.Record.CommentedOnContainer = commentedOn.Container.ContentItem.Id;
					    }
					});
				}
			}

			Services.Notifier.Information(T("Imported {0} blog posts", posts.Count));

            return RedirectToAction("Index");
		}
Mar 27, 2012 at 7:21 AM

May I ask how much users (as in accounts) your site has?

Mar 27, 2012 at 3:28 PM

Approximately a thousand.