Creating content by code

Topics: Writing modules
Mar 8, 2013 at 10:25 AM
Edited Mar 8, 2013 at 10:26 AM

I am trying to write a content item programmatically.

The content type has been created in the dashbord. it is called "SampleContentType" and has one text field called "Name".

I've performed the following in my module :
public class SampleContentTypePart : ContentPart<SampleContentTypePartRecord>
        public string Name
            get { return Record.Name; }
            set { Record.Name = value; }


    public class SampleContentTypePartRecord : ContentPartRecord
        public virtual string Name { get; set; }


    public class SampleContentTypetPartDriver : ContentPartDriver<SampleContentTypePart>


    public class SampleContentTypePartHandler : ContentHandler
to create the item : I created this method :
 var customPart = _contentManager.New<SampleContentTypePart>("SampleContentType");

            customPart.As<TitlePart>().Title = "zzz";
            customPart.Record.Name = "hhh";

But i'm getting "InvalidCastException.

What's wrong please ?
Mar 8, 2013 at 11:28 AM
Did you attach the TitlePart to the SampleContentType?
Mar 8, 2013 at 11:34 AM

When I try to create the content type and assign only the TitlePart it works !

But when I try to assign values to my own values, it is generating invalidcastexception or NullReferenceException.

I am running 1.6 version
Mar 8, 2013 at 11:57 AM
Did you add a StorageFilter from your handler? From looking at the code you pasted above, it appears you haven't.
Mar 8, 2013 at 1:14 PM
In the constructor, I am doing this :
public SampleContentTypePartHandler(IRepository<SampleContentTypePartRecord> repository)
But I still get an InvalidCastException
Mar 15, 2013 at 8:51 PM
Then I don't know, sorry.
Mar 15, 2013 at 10:54 PM
Attach a debugger and take a closer look at this exception. The error message is actually giving you the two types it can't cast (the actual one and the expected one). It would help to give that information.