2011-08-04 99 views
0

我試圖從一個子網站的自定義佈局頁面獲取發佈網站(Microsoft.SharePoint.Publishing.PublishingWeb)中的所有頁面佈局時最近遇到此錯誤。該代碼使用從Enterprise Wiki站點模板創建的站點在VM服務器上工作。但是,在開發服務器上運行時,代碼會遇到各種異常。NullReferenceException引發「GetAvailablePageLayouts」

爲了解決這個錯誤,我編寫了三種不同的方法。所有這三個人都在VM中工作,但是在開發服務器中使用這三者時都會引發異常。例如:

private PageLayout FindPageLayout(PublishingWeb pubWeb, string examplePage) 
     { 
      /* The error occurs in this method */ 
      if (pubWeb == null) 
       throw new ArgumentException("The pubWeb argument cannot be null."); 
      PublishingSite pubSiteCollection = new PublishingSite(pubWeb.Web.Site); 
      string pageLayoutName = "EnterpriseWiki.aspx"; // for testing purposes 
      PageLayout layout = null; 

      /* Option 1: Get page layout from collection with name of layout used as index 
      * Result: System.NullReferenceException from GetPageLayouts() 
      */ 

      layout = pubSiteCollection.PageLayouts["/_catalogs/masterpage/"+pageLayoutName]; 

      /* Option 2: Bring up an existing publishing page, then find the layout of that page using the Layout property 
      * Result: Incorrect function COM exception 
      */ 

      SPListItem listItem = pubWeb.Web.GetListItem(examplePage); 
      PublishingPage item = PublishingPage.GetPublishingPage(listItem); 
      layout = item.Layout; 

      /* Option 3: Call "GetPageLayouts" and iterate through the results looking for a layout of a particular name 
      * Result: System.NullReferenceException thrown from Microsoft.SharePoint.Publishing.PublishingSite.GetPageLayouts() 
      */ 

      PageLayoutCollection layouts = pubSiteCollection.GetPageLayouts(true); 
      for(int i = 0; i < layouts.Count; i++) 
      { 
       // String Comparison based on the Page Layout Name 
       if (layouts[i].Name.Equals(pageLayoutName, StringComparison.InvariantCultureIgnoreCase)) 
        layout = layouts[i]; 
      } 

      return layout; 
     } 

回答

1

這裏是解決辦法,我一個星期左右後發現:

確保當你通過調用讓您的「PublishingWeb」對象PublishingWeb.GetPublishingWeb(的SPWeb)方法,你是傳入一個已完全檢索的SPWeb對象。更具體地講,我會確保調用SPSite.OpenWeb在任何網站上,具體如下:

using (SPSite site = new SPSite(folder.ParentWeb.Url)) 
      { 
       SPWeb web = site.OpenWeb(); 
       PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web); 
       /* work with PublishingWeb here ... */ 
       web.Close(); 
      } 

一旦我做了這個簡單的變化,在問題中提到的所有錯誤被清除了,在什麼情況下,無論我稱爲「GetPageLayouts」或「GetAvailablePageLayouts」。該method documentation說,這和它的真正含義是:

使用此方法,以訪問爲已經被檢索的的SPWeb類的一個實例 行爲PublishingWeb。

相關問題