EPiServer  /  CMS August 31, 2009

Finding Page Type ID When Using Page Type Builder

In many situations we need to find out what ID a page type has. One such example is when programmatically creating a new PageData object. The code usually looks something like this:

int pageTypeID = ???
PageData newPage = DataFactory.Instance.GetDefaultPageData(CurrentPage.PageLink, pageTypeID);
DataFactory.Instance.Save(newPage, SaveAction.Publish);

So, how do we set the pageTypeID variable? Traditionally we’d retrieve the page type ID from a property on the start page, from appSettings or just hard code it. While that works it’s not exactly pretty and we move something that I think belongs in the code out of the code, making the code harder to understand.

Luckily, Page Type Builder has a class named PageTypeResolver that can help us. PageTypeResolver keeps track of the page types that we have declared in code and their corresponding IDs in the database. Using the GetPageTypeID method in PageTypeResolver we can rewrite the above code into

int pageTypeID = PageTypeResolver.Instance.GetPageTypeID(typeof(MyPageType)).Value;
PageData newPage = DataFactory.Instance.GetDefaultPageData(CurrentPage.PageLink, pageTypeID);
DataFactory.Instance.Save(newPage, SaveAction.Publish)

Erik Nordin has an example of how to build a custom GetDefaultPageData method using the GetPageTypeID method on his blog.

GetPageTypeType

Worth mentioning is also that PageTypeResolver has another method, GetPageTypeType, which does the exact opposite of GetPageTypeID. That is, given a page type ID it returns the declaring type.

Type pageTypeType = PageTypeResolver.Instance.GetPageTypeType(42);

PS. For updates about new posts, sites I find useful and the occasional rant you can follow me on Twitter. You are also most welcome to subscribe to the RSS-feed.

Joel Abrahamsson

Joel Abrahamsson

I'm a passionate web developer and systems architect living in Stockholm, Sweden. I work as CTO for a large media site and enjoy developing with all technologies, especially .NET, Node.js, and ElasticSearch. Read more

Comments

comments powered by Disqus

My book

Want a structured way to learn EPiServer 7 development? Check out my book on Leanpub!

More about EPiServer CMS