Thursday, August 29, 2013

How to remove columns from web part view on a page


The code locates a landing page and search for web part called "Shared Documents". If page is not checked out, it checks out the page and delete "Version" column web part view (_UIVersionString)


private void UpdateViewOfWebpart(SPSite createdSite)
        {
            //// Sets the page url where the webpart is located
            string pageUrl = createdSite.RootWeb.RootFolder.WelcomePage;
            string targetwebpartTitle = "Shared Documents";

            //// Elevating permission
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                //// Creates a new SPSite instance for the sharepoint website
                using (SPSite spsite = new SPSite(createdSite.Url))
                {
                    //// Opens the SPWeb instance based on which the SPSite was initiated
                    using (SPWeb spweb = spsite.OpenWeb())
                    {
                        /// Gets the page SPFile object
                        SPFile pageSPFile = spweb.GetFile(pageUrl);

                        try
                        {
                            //// If file is not checked out then do a check out
                            if (pageSPFile.Level != SPFileLevel.Checkout)
                            {
                                pageSPFile.CheckOut();
                            }

                            //// Gets the SPLimitedWebpartManager instance from the page
                            SPLimitedWebPartManager limitedWebpartManager = pageSPFile.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

                            //// A temp value to use inside the following for loop
                            string currentWebpartTitle = string.Empty;

                            foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in limitedWebpartManager.WebParts)
                            {
                                //// Ignore the closed webpart
                                if (!webPart.IsClosed)
                                {
                                    //// Reads the webpart title in the iterated loop
                                    currentWebpartTitle = webPart == null ? string.Empty : (webPart.Title == null ? string.Empty : webPart.Title);

                                    //// Checks whether current webpart title in iterated loop is the targeted webpart or not
                                    if (currentWebpartTitle == targetwebpartTitle)
                                    {
                                        //// With the help of reflection gets the View field’s info
                                        System.Reflection.FieldInfo viewFieldInfo = webPart.GetType().GetField("view", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

                                        //// Ignore and continue loop if view field is null
                                        if (viewFieldInfo == null)
                                        {
                                            continue;
                                        }

                                        //// Cast the view field’s value which was retrieved using reflection to the SPView
                                        SPView view = viewFieldInfo.GetValue(webPart) as SPView;

                                        if (view.ViewFields.Exists("_UIVersionString"))
                                            view.ViewFields.Delete("_UIVersionString");

                                        /// Updates the view
                                        view.Update();

                                        //// This is optional, need not have to save changes to webpart, but just to confirm
                                        limitedWebpartManager.SaveChanges(webPart);

                                        break;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                        finally
                        {
                            if (pageSPFile.Level == SPFileLevel.Checkout)
                            {
                                pageSPFile.CheckIn("Removed Version column", SPCheckinType.MajorCheckIn);
                            }
                        }

                    }
                }
            });

        }

PowerShell script does the same

$deleteField = "_UIVersionString"
$whereToLook = "Shared Documents"

function HasPageWebPartField()
{
      param
      (
      [Microsoft.SharePoint.SPFile]$Page,
      [Microsoft.SharePoint.SPWeb]$Web
      )          
     
      $localWebVariable = Get-SPWeb -Identity $web.Url     
    $checkWpm = $localWebVariable.GetLimitedWebPartManager($page.Url, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
      $checkWp = $checkWpm.WebParts | Where-Object { $_.Title -eq $whereToLook }
      $checkList = $localWebVariable.Lists | Where-Object { $_.Title -eq $whereToLook }
      if ($wp.ViewGUID -ne $null -and $wp.ViewGUID -ne "")
      {
            $checkView = $checkList.Views[[Guid]$checkWp.ViewGUID]
            $returnVal = $checkView.ViewFields.Exists($deleteField)
      }
      else
      {
            $returnVal = $false
      }
      $checkWpm.Dispose()
      $localWebVariable.Dispose()
      return $returnVal
}

$web = Get-SPWeb $_.URL
      
       if ([Microsoft.SharePoint.Publishing.PublishingWeb]::IsPublishingWeb($web))
       {
              [Microsoft.SharePoint.Publishing.PublishingWeb]$publishingWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
              $page = $publishingWeb.DefaultPage
              if ($page.CheckedOutDate -eq $null)
              {
                     $hasField = HasPageWebPartField -Page $page -Web $web
                     if ($hasField)
                     {
                     $page.CheckOut()
                     $wpm = $web.GetLimitedWebPartManager($page.Url, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
                            $wp = $wpm.WebParts | Where-Object { $_.Title -eq $whereToLook }
                           $list = $web.Lists | Where-Object { $_.Title -eq $whereToLook }
                           $view = $list.Views[[Guid]$wp.ViewGUID]
                           $view.ViewFields.Delete($deleteField)
                           $view.Update()
                           $wpm.SaveChanges($wp)
                           $page.CheckIn("Removed Version column. Update via PowerShell",[Microsoft.SharePoint.SPCheckinType]::MajorCheckIn)
                     }
              }
              else
              {
                     $message = "Web " + $web.Url + " page " + $page.Name + " was checked out - to be processed manually."
                     Write-Host $message -ForegroundColor Red
                     $script:fileContents += ($message)
                     $script:fileContents += ("`r`n")
              }
       }

      $web.Close()


No comments:

Post a Comment