This project is read-only.

Creating ContentItem programmatically

Topics: Troubleshooting, Writing modules
Feb 28, 2011 at 12:51 PM


I have defined a ContentType consisting of two parts -- CommonPart and ConfigPart (my own part).
Now I need to create items of this ContentType from my own Controller (not via drivers).
So I figured out, I need something like this:


// Create new content item
ContentItem item = Services.ContentManager.New("Config");
// Cast it to my Part type
var configPart = item.As<ConfigPart>();
// Fill part's properties
configPart.Name = model.Name;


 However, the item.As<> call returns null.

Stepping through this method in debugger shows that collection _parts in ContentItem has my part under the base class -- Orchard.ContentManager.ContentPart, instead of the actual derived class. So, method ContentItem.Get cannot find it in the following query:

return _parts.FirstOrDefault(part => partType.IsAssignableFrom(part.GetType()));

Any help is appreciated.



Feb 28, 2011 at 8:17 PM

That should work. Can you show the code that created the type (that is, if you used code to do that)?

Mar 5, 2012 at 9:18 AM

I previously raised a question on "How to access content Item field programmatically and storing field values manually?"

I'm trying to access the content item field which I created from admin UI,I assigned my BlogPost a field named TaxonomyField.

Now using XML-RPC web services, on each content item create request, I want to store field values in database?

my field of taxonomy in BlogPost is treated as BlogPostPart...can I find any similar example in Orchard? 

this is the original code from XMLRpc Handler.cs 

  private int MetaWeblogNewPost(
            string blogId,
            string userName,
            string password,
            XRpcStruct content,
            bool publish,
            IEnumerable drivers)

            IUser user = ValidateUser(userName, password);

            // User needs permission to edit or publish its own blog posts
            _authorizationService.CheckAccess(publish ? Permissions.PublishBlogPost : Permissions.EditBlogPost, user, null);

            BlogPart blog = _contentManager.Get(Convert.ToInt32(blogId));
            if (blog == null)
                throw new ArgumentException();

            var title = content.Optional("title");
            var description = content.Optional("description");
            var slug = content.Optional("wp_slug");
            var category = content.Optional("categories");
            var blogPost = _contentManager.New("BlogPost");

            // BodyPart   

            if (blogPost.Is())
                blogPost.As().Text = description;


            if (blogPost.Is())
                blogPost.As().Owner = user;
                blogPost.As().Container = blog;

            if (blogPost.Is())
                blogPost.As().Title = title;
                blogPost.As().Slug = slug;
                blogPost.As().Path = blogPost.As().GetPathWithSlug(blogPost.As().Slug);


            if (blogPost.Has())

			// this is where I want to access the BlogPart Taxonomy and update the record as the record is already have been create
			// as _contentManager.Create...

            _contentManager.Create(blogPost, VersionOptions.Draft);

            var publishedUtc = content.Optional("dateCreated");
            if (publish && (publishedUtc == null || publishedUtc <= DateTime.UtcNow))

            foreach (var driver in drivers)

            return blogPost.Id;


Bertand Answer was:

@Aamir: it would be best to post that on the discussions forum, so that others can find it and benefit from any answers. In a nutshell, yes you can access fields. The easiest is to cast the ContentItem to dynamic and access the field through something like item.ThePartThatHasTheField.TheField.TheFieldProperty. S

Still need more information...

Mar 5, 2012 at 9:39 AM

What more information do you need?

Mar 5, 2012 at 10:11 AM

Which services should I call for update driver for BlogPostPart?

Mar 5, 2012 at 9:37 PM
If you have access to an instance of the BlogPostPart already, you can simply set its property and it will be saved to the database after the request has finished.

So you should be able to do it like this:

dynamic dynamicBlogPost = blogPost;
dynamicBlogPost.SomeField.SomeProperty = "Any string you like";

No need to update drivers, unless you want to invoke all of the drivers of the content parts that are attached to the content item to which the BlogPostPart is attached. In that case, you can use the IContentManager service and invoke its UpdateEditor method. However, I'm not sure that makes sense in your example.



Mar 6, 2012 at 12:10 AM

Thanks Bertrand and SkyWalker, I'm new to C# Dynamics but did figured out after reading on msn developer blog...about it. 

Here is what I'm trying to do...

I used TaxonomyField as BlogPostPart  and casting dynamic I can get it's TaxonomyId from where using _taxonomiesService.getTermsbyId() I call all the related terms...

Getting XRpcArray I can get all the selected categories back from WindowsLive Writer...

Now I've learned that those values from the TaxonomyField is storing as Record? 

By creating a new BlogPost those record do get create in the database and from the designer view tool I can see that they are under Content.ContetItem.Record 

My question is how can I assign values to Record? by creating new ContentItemRecord? or there is another way, I thought first there might be some services where we can update BlogPostPart? as we are not using Repository ?


Mar 6, 2012 at 12:29 AM

You're overthinking it. You don't need to reach into records, the part is going to do exactly that for you.

Mar 6, 2012 at 12:45 AM
Edited Mar 6, 2012 at 12:46 AM

Exactly. As en example, just have a look on how the properties of BlogPostPart are implemented: they wrap arround properties of its Record instance.
So, setting a property of a content part actually sets a property on its Record, whose changes are tracked via an NHibernate Session. At the end of each request, Orchard will instruct NHibernate to submit any changes. Voila.

Mar 6, 2012 at 8:55 AM

But the BlogPostPart has no properties for TaxonomyTermPart...however It uses TaxonomyPart?

Mar 6, 2012 at 9:00 AM


              if (blogPost.Is<BlogPostPart>())

                dynamic bg = blogPost.As<BlogPostPart>().ContentItem;
                var settings = bg.BlogPost.MyTaxonomy.PartFieldDefinition.Settings.GetModel<TaxonomyFieldSettings>();
               // var appliedTerms = _taxonomyService.GetTermsForContentItem(blogPost.Id, bg.BlogPost.MyTaxonomy.Name);
                var taxonomy = _taxonomyService.GetTerms(settings.TaxonomyId);
                IList<TermPart> selectedTerms = new List<TermPart>();

                var singleTerm = new TermPart();
                for (int i = 0; i < category.Data.Count; i++)
                    singleTerm = _taxonomyService.GetTermByName(settings.TaxonomyId, category[i].ToString());


                foreach (var selectedTerm in selectedTerms)
                    blogPost.As<BlogPostPart>(). Property?


Here is the code...
Mar 6, 2012 at 1:51 PM

Yep, welcome to the magical world of dynamic ;)

You can simply cast a BlogPost or BlogPostPart to dynamic, and then the clay behaviors will figure it out for you.
So this will work:

dynamic post = blogPost;
var taxonomyField = post.BlogPostPart.MyTaxonomyField;

In order to understand how this works, check out this excellent post on Clay and dynamic: