Pages

Search This Blog

Showing posts with label Publishing. Show all posts
Showing posts with label Publishing. Show all posts

Sunday, April 22, 2012

Publish Content Type in Content Type hub SharePoint 2010

Sometimes we have a requirement where we need to create the content type in hub and publish the same via code. Following are the methods to Publish or Un-Publish the Content Type in Content Type HUB


 public static String PublishorUnPublishedContentType(SPSite hubSiteCollection, SPContentType cType, bool doPublish)
        {
            String sMessage = String.Empty;
            if (ContentTypePublisher.IsContentTypeSharingEnabled(hubSiteCollection))
            {
                ContentTypePublisher publisher = new ContentTypePublisher(hubSiteCollection);
                try
                {
                    if (doPublish)
                    {
                        publisher.Publish(cType);
                        sMessage = "Content Type Published Successfully.";
                    }
                    else
                    {
                        if (publisher.IsPublished(cType))
                        {
                            publisher.Unpublish(cType);
                            sMessage = "Content Type UnPublished Successfully.";
                        }
                        else
                        {
                            sMessage = "Content Type is not published. You need to Publish the Content Type before UnPublished.";
                        }
                    }
                }
                catch (Exception ex)
                {
                    sMessage = ex.Message;
                }
            }
            else
            {
                // The provided site is not a valid hub site.
                sMessage = hubSiteCollection.Url + ": is not a valid Content Hub Site.";
            }
            return sMessage;
        }

Hope this will help you out !!!!!

Monday, January 16, 2012

How to change the default home page or Set Welcome Page of a SharePoint site using PowerShell Script - SharePoint 2010

By default a SharePoint 2010 publishing site uses default.aspx as its welcome page.
There are so many conditions where we use our custom web part page as the default page for our publishing site in place of general default.aspx. The best example for this is an application dashboard as the default page.

Below are four ways to set another page as your home page: (all four work for both 2007 and 2010)

1. From Site Settings (If the publishing features are enabled)
2. From SharePoint Designer
3. From code / API
4. From PowerShell

1. If the publishing features are enabled for a site then:
Go to Site Actions -> Site Settings -> Welcome Page
In SharePoint 2007

In SharePoint 2010

2. From SharePoint Designer:
Right-click the new page and click "Set as Home Page".
(For SharePoint 2007 this only appears to work from SharePoint Designer if the file is in the root of the site. I.e. the same place as default.aspx.)

3. From code / API:

using (SPSite oSiteCollection = new SPSite("http://sharepoint2010:2400"))
            {
                SPWeb oWebsite = oSiteCollection.OpenWeb();
                SPFolder oFolder = oWebsite.RootFolder;
                oFolder.WelcomePage = "SiteAssets/BecomeFan.aspx";
                oFolder.Update();
                oWebsite.Dispose();
            }

4. From PowerShell:
In SharePoint 2010, Create a powershell script file e.g. SetWelcomePage.ps1, with the following script:

Add-PsSnapin Microsoft.SharePoint.PowerShell
$assignment=Start-SPAssignment
$web=Get-SPWeb -Identity "http://sharepoint2010:2400" -AssignmentCollection $assignment
$rootFolder=$web.RootFolder
$rootFolder.WelcomePage="SiteAssets/BecomeFan.aspx"
$rootFolder.Update()
Stop-SPAssignment $assignment
$web.Update()
$web.Dispose()
Write-Host 'Welcome Page Set Successfully…'
Write-Host 'Press any key to exit…'
$x=$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$Host.SetShouldExit(1)

After creating the script file, just run that file by right click and Run with PowerShell:


Now, navigate back to a site and see that the homepage is now set to the given page.


Friday, December 9, 2011

Enable Item Scheduling through code in SharePoint 2010


Many a times we need to create lists or sites from object model and hence it is often required to enable scheduling on list. Following code will do 3 things that are required to item scheduling:

  1. Enable Content approval
  2. Enable Versioning
  3. Enable Scheduling

Scheduling is dependent on both versions and content approval and should be enabled first.

Scheduling feature is only available in publishing site.


 using (SPSite site = new SPSite("http://sharepoint2010/"))
            {
                using (SPWeb web = site.RootWeb)
                {
                    SPList list=web.Lists["Documents"];
                    list.EnableModeration = true;
                    list.EnableMinorVersions = true;
                    list.Update();
                    Microsoft.SharePoint.Publishing.PublishingWeb.EnableScheduling(list);
                }
            }


list.EnableModeration = true; code will be actually doing the setting shown below:


list.EnableMinorVersions = true; this code will enable the minor versioning on the list as shown below:



Microsoft.SharePoint.Publishing.PublishingWeb.EnableScheduling(list); This code will actually enable scheduling on this list




To disable Scheduling in the list we can use following command:

Microsoft.SharePoint.Publishing.PublishingWeb.DisableScheduling(list);

###############################################################

We can also make use of powershell script for the same

$list= $SPList = Get-SPList -url "http://sharepoint2010/" -List Documents
$list.EnableModeration=$true
$list.EnableMinorVersions=$true
# To enable Scheduling in the list
[Microsoft.SharePoint.Publishing.PublishingWeb]::EnableScheduling($list)
# To disable Scheduling in the list
[Microsoft.SharePoint.Publishing.PublishingWeb]::DisableScheduling($list)


Saturday, December 3, 2011

Uncustomized the PageLayout or Page via SharePoint API


Sometimes we have a requirement where we need to remove all customization from the PageLayout or from the Page. OOB SharePoint provide link to reset to site definition. But is someone needs to do that via code then below code will help them.

SPSecurity.RunWithElevatedPrivileges(delegate()
                      {
                          using (SPSite site = new SPSite("http://sharepoint2010"))
                          {
                              PublishingSite publishingSite = new PublishingSite(site);
                              PageLayoutCollection pageCollection = publishingSite.PageLayouts;
                              foreach (PageLayout layout in pageCollection)
                              {
                                  SPFile currentFile = site.RootWeb.GetFile(layout.ServerRelativeUrl);
                                  if (currentFile.CustomizedPageStatus == SPCustomizedPageStatus.Customized || currentFile.CustomizedPageStatus == SPCustomizedPageStatus.None)
                                  {
                                      try
                                      {
                                          currentFile.RevertContentStream();
                                          currentFile.Versions.DeleteAll();
                                          currentFile.Update();
                                          site.RootWeb.Update();
                                      }
                                      catch (Exception ex)
                                      {
                                          Console.WriteLine("Error occuured : " + ex.Message);
                                      }

                                  }
                              }

                          }
                      });

Hope it will helps!!! 

Monday, May 9, 2011

Save publishing site a template

By default share point doesn't allow to save the site as template.

To save site as template open the "_layouts/savetmpl.aspx" from site setting and save the site as template.

Sunday, April 24, 2011

Programmatically change the Welcome / Default page of a Sharepoint Publishing Web

Sometimes we have a requirement like on feature activation or deactivation we have to change the Welcome Page(Default Page) of the publishing site.
Below is the code snippet with the help of which we can change the Welcome Page:
public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using (SPSite objSiteProperty = (SPSite)properties.Feature.Parent)
            {
                using (SPWeb objSPWeb = objSiteProperty.OpenWeb())
                {
                    PublishingWeb objPublishingWeb = PublishingWeb.GetPublishingWeb(objSPWeb);
                    SPFile objHomePageFile = objSPWeb.GetFile("Pages/Test.aspx");
                    objPublishingWeb.DefaultPage = objHomePageFile;
                    objPublishingWeb.Update();
                }
            }
        }

And in the same way on Feature Deactivation we can change the Welcome Page again.

Monday, April 4, 2011

Creating & Publishing SPFolder

In a scenario I have to create and publish a folder in the Pages Library Programaticaly. This post shows how we can Create and Publish a SPFolder in the Default Pages Library in a Publishing Web.

Code Snippet:
private void CreateFolder(SPWeb objWeb,string FolderName )
{
Guid PagesLibraryId = PublishingWeb.GetPagesListId(objWeb);
if (PagesLibraryId != null)
{
objList = objWeb.Lists[PagesLibraryId];
// Create New Folder
SPListItem newFolder = objList.Items.Add(objList.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, FolderName);
newFolder.Update();
// Publishing a specific Folder
SPFolder objfolders = objList.RootFolder.SubFolders[FolderName];
bool isFolderExists = objWeb.GetFolder(objList.RootFolder.ServerRelativeUrl +
"/" +).Exists;
if (isFolderExists)
{
if (objFolder.Item.ModerationInformation.Status !=
SPModerationStatusType.Approved)
{
objFolder.Item.ModerationInformation.Status =
SPModerationStatusType.Approved;
objFolder.Item.Update();
}
}
//Publishing All Folders in the List
SPFolderCollection objfolders = objList.RootFolder.SubFolders;
foreach (SPFolder objFolder in objfolders)
{
if (objFolder.Item != null)
{
if (objFolder.Item.ModerationInformation.Status !=
SPModerationStatusType.Approved)
{
objFolder.Item.ModerationInformation.Status =
SPModerationStatusType.Approved;
objFolder.Item.Update();
}
}
}
}

Monday, March 28, 2011

Error:- "Column 'Page Content' does not exist. It may have been deleted by another user."

In a scenario I have to write the content in the “page content area” with some formatting. Using UI we can do this very easily by just clicking on “Edit as HTML” link and writing the HTML code in the editor.
Programmatically we can do this using the following code snippet:
PublishingPage objPublishingPage;
PublishingWeb objPublishingWeb;
String PageUrl =http://...;
String PageName =”XYZ.aspx”;
objPublishingWeb = PublishingWeb.GetPublishingWeb(SPWebObject);
objPublishingPage = objPublishingWeb.GetPublishingPage(PageUrl + "/" + PageName);
if (objPublishingPage != null)
{
objPublishingPage.CheckOut();
objPublishingPage.ListItem["Page Content"]=PageContent;
objPublishingPage.ListItem.Update();
}
This works fine till you are not using the multilingual feature. But I have to also publish the content in its locale language in the multilingual page, in which the above code fails and give the error “Column 'Page Content' does not exist. It may have been deleted by another user. ”. In Multilingual page the column “Page Content” changes its language to its local so it’s hard to find the column instead of this we can use the following code snippet:
PublishingPage objPublishingPage;
PublishingWeb objPublishingWeb;
String PageUrl =http://...;
String PageName =”XYZ.aspx”;
objPublishingWeb = PublishingWeb.GetPublishingWeb(SPWebObject);
objPublishingPage = objPublishingWeb.GetPublishingPage(PageUrl + "/" + PageName);
if (objPublishingPage != null)
{
objPublishingPage.CheckOut();
objPublishingPage.ListItem["PublishingPageContent"]=PageContent;
objPublishingPage.ListItem.Update();
}

Friday, February 11, 2011

Publishing Sharepoint 2007 Publishing Pages,Master pages using Object Model

Requirement : We are having 150+ pages. So every time we have to demo when we have to go to pages library and master page library to check the publishing status. It was tedious task to make sure that all the pages, master pages and css file in style library are check in and published.
Solution : We have create a console application so every time when we needs all the pages to be check in and approve all we have to do is to run the console applicaton .
Code:


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
namespace Publishing_Sharepoint_Pages
{
class Program
{
static void Main(string[] args)
{
//Get the reference of site object
using (SPSite site = new SPSite("http://test"))
{
//Get the spweb object
using (SPWeb webs = site.OpenWeb())
{
// To publish all the page in pages library
//Get the publishing instance of the web
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(webs);
//Get the pages library
PublishingPageCollection pages = pubWeb.GetPublishingPages();
foreach (PublishingPage page in pages)
{
SPModerationInformation moderationStatus = page.ListItem.ModerationInformation;
//Check if the page is not approved
if (moderationStatus.Status != SPModerationStatusType.Approved)
{
// the page page status approved and update the page status
page.ListItem.ModerationInformation.Status = SPModerationStatusType.Approved;
page.Update();
}
}
// Code to publish the master page
//Get the master page libaray reference
SPList masterPageGallery = site.GetCatalog(SPListTemplateType.MasterPageCatalog);
//Navigate the all item in master page
// This will also include all the page layouts
foreach (SPListItem galleryPage in masterPageGallery.Items)
{
//if the page is status in not published
if (!galleryPage.HasPublishedVersion)
{
//Check in the page with automated comments and set the status to checkin
galleryPage.File.CheckIn("Automatically approved", SPCheckinType.MajorCheckIn);
galleryPage.File.Update();
// approve the page with comments
galleryPage.File.Approve("Automatically approved");
galleryPage.File.Update();
}
}
// Update the style library items
SPList styleLibrary = webs.Lists["Style Library"];
//Get all the css from the style library
SPFolder editingMenuFolder = styleLibrary.RootFolder;
foreach (SPFile cssFile in editingMenuFolder.Files)
{
// if the file is not checkin then check in the file with comments.
if (cssFile.CheckOutStatus != SPFile.SPCheckOutStatus.None)
{
cssFile.CheckIn("Automatically approved");
cssFile.Update();
}
}
}
}
}
}
}

Friday, February 4, 2011

Adding the WebPart in a Publishing Site Dynamically

When adding WebPart dynamically on a Publishing Site Page we need to define three things
1. WebPart to be Added
2. Zone
3. ZoneIndex
The Code Snippet is shown below:
SPLimitedWebPartManager manager = objFile.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
manager.AddWebPart(objWebPart, Zone, ZoneIndex);
objweb.Update();
  • Here objWebPart is the object of the WebPart to be added.
  • Zone is the zone where the WebPart is to added.
o Zones for default.aspx can be:
1. TopColumnZone
2. LeftColumnZone
3. RightColumnZone
o Zones for BlankWebPart.aspx Layout can be:
1. Header
2. TopLeftRow
3. TopRightRow
4. CenterLeftColumn
5. CenterColumn
6. CenterRightColumn
7. Footer
8. RightColumn
  • ZoneIndex is the index of the WebPart in that Particular Zone, by default its zero.