Monday, October 24, 2011

Creating Custom SharePoint Site Pages by Object Model (Code only)

This is in continuation to my earlier post on Site Pages. In this post I have only used the object model to create and put a Site page again in pages library. A very simple piece of code which creates a stream and writes it to the file location in SharePoint. I know this approach will never be used in any project, though.  I have created this in a windows program and thus it is in a shape of method stub. One way to implement would be to put this in a feature receiver to work on feature activation.

private void DoFileStreamWriteFile()

        {

            ////Site url

            string strUrl = "http://myserver0111:7000/";

            using (SPSite oSite = new SPSite(strUrl))

            {

                using (SPWeb oWeb = oSite.OpenWeb())

                {

                    MemoryStream fileStream = new MemoryStream();

                    StreamWriter fileWriter = new StreamWriter(fileStream);

                    ////write the source of the page (include meta:progid so SharePoint Designer understands this file)

                    fileWriter.WriteLine("<%@ Page MasterPageFile=\"~masterurl/default.master\" meta:progid=\"SharePoint.WebPartPage.Document\" %> ");

                    fileWriter.WriteLine("<asp:Content runat=\"server\" ContentPlaceHolderID=\"PlaceHolderMain\" > ");

                    fileWriter.WriteLine("<h1> Hello World </h1>");

                    fileWriter.WriteLine("</asp:Content>");

                    fileWriter.Flush();

                    //// save the file to SharePoint

                    oWeb.Files.Add(oWeb.Url+"/Pages/"+"MyApiGeneratedPage.aspx", fileStream);

                    //// cleanup

                    fileWriter.Close();

                    fileWriter.Dispose();

                    fileStream.Close();

                    fileStream.Dispose();

                }

            } 

        }

 

Now  build and deploy to see the magic happening yourself again.... J

Thanks for reading. If you have some other explanation – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

No comments:

Post a Comment