Monday, 22 April 2013

How to get list item by absolute URL of the item

Pass the URL as query string named DocumentPath.


  protected void Page_Load(object sender, EventArgs e)
        {
            string documentPath = Convert.ToString(Request.QueryString["DocumentPath"]);
            if (string.IsNullOrEmpty(documentPath))
            {
            }
            else
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = site.RootWeb)
                        {

                            SPListItem item = web.GetListItem(documentPath);
                        }
                    }
                });


            }


        }

            }

        }

Wednesday, 17 April 2013

How to create webpart page programatically in SharePoint 2010 (Source Code)

/// <summary>
/// Create new webpart page
/// </summary>
/// <param name="list">List to keep page</param>
/// <param name="pageTitle">Page title</param>
/// <param name="layoutTemplate">Layout template id</param>
/// <returns>Operation result</returns>
private static string CreateWebPartPage(SPList list, string pageTitle, int layoutTemplate)
{
    const string newItemTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                    "<Method ID=\"0,NewWebPage\">" +
                                    "<SetList Scope=\"Request\">{0}</SetList>" +
                                    "<SetVar Name=\"Cmd\">NewWebPage</SetVar>" +
                                    "<SetVar Name=\"ID\">New</SetVar>" +
                                    "<SetVar Name=\"Type\">WebPartPage</SetVar>" +
                                    "<SetVar Name=\"WebPartPageTemplate\">{2}</SetVar>" +
                                    "<SetVar Name=\"Overwrite\">true</SetVar>" +
                                    "<SetVar Name=\"Title\">{1}</SetVar>" +
                                    "</Method>";
    var newItemXml = string.Format(newItemTemplate, list.ID, pageTitle, layoutTemplate);
    return list.ParentWeb.ProcessBatchData(newItemXml);
}

Using:
var web = SPContext.Current.Web;
var pagesLibrary = web.GetList("Pages");
CreateWebPartPage(pagesLibrary, "MyPage", 2);
Values for LayoutTemplate parameter:
  1. Full Page, Vertical
  2. Header, Footer, 3 Columns
  3. Header, Left Column, Body
  4. Header, Right Column, Body
  5. Header, Footer, 2 Columns, 4 Rows
  6. Header, Footer, 4 Columns, Top Row
  7. Left Column, Header, Footer, Top Row, 3 Columns
  8. Right Column, Header, Footer, Top Row, 3 Columns