a scenario wherein the “WebPart Page” could be added dynamically using the
custom code and then the “WebPart” be added on top of the same page until someone
asked me if that could be done or not.
My first answer was, “Yes! That
can be done!” and asked him to take a look at the several MSDN links. I tried to
implement the code myself then and found that the link that I actually asked
person to look at would not be good enough considering the performance of the
code.
I thought for some time and found a way to achieve the task. Take a look at the code below, which
creates a very simple web part. The web part takes input from the user for the
page name and then creates a “WebPart page” based on the input supplied by the
user. I am then adding the same web part to the newly created page.
1. Defining the webpart structure

2. Some try catch and the method calls for creating the page and adding webpart
3. Code to create a new "WebPart Page"
4. Code to add a webpart on the newly created "WebPart page"
5. Code to check if the page exists or not
PS.: One thing to note here is that, I've used the Farm Solution to deploy this code. The Sandbox solution would not allow you to access the class "SPLimitedWebPartManager" due to the CAS restrictions.