Friday, 15 February 2019

Add document library to publishing page powershell

Why can't you see the export on out of box web part?  This is by design but there is a very easy workaround.

In SharePoint design change the web parts that you would like to export 

  1. Configure the web part on the publish page the way you would like it to look
  2. Open the site in SharePoint Designer 
  3. In the code view find the web part and find <ExportControlledProperties>false</ExportControlledProperties> and change from “false” to “true”
  4. Save the page
  5. Open the web page in the browser, Edit the Page and export the web part.
  6. Give the file a name and save it somewhere where you can find it in the next step.

Powershell code

$wpxml = '<webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type name="Microsoft.SharePoint.WebPartPages.XsltListViewWebPart, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="ShowWithSampleData" type="bool">False</property>
        <property name="Default" type="string" />
        <property name="NoDefaultStyle" type="string" null="true" />
        <property name="CacheXslStorage" type="bool">True</property>
        <property name="ViewContentTypeId" type="string" />
        <property name="XmlDefinitionLink" type="string" />
        <property name="ManualRefresh" type="bool">False</property>
        <property name="ListUrl" type="string" />
        <property name="ListId" type="System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">3ba65105-0767-4f57-9aa8-3d2e3c1e10cf</property>
        <property name="TitleUrl" type="string">/My School/2392/Shared Documents Area</property>
        <property name="EnableOriginalValue" type="bool">False</property>
        <property name="Direction" type="direction">NotSet</property>
        <property name="ServerRender" type="bool">False</property>
        <property name="ViewFlags" type="Microsoft.SharePoint.SPViewFlags, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">Html, TabularView, Hidden, Mobile</property>
        <property name="AllowConnect" type="bool">True</property>
        <property name="ListName" type="string">{3BA65105-0767-4F57-9AA8-3D2E3C1E10CF}</property>
        <property name="ListDisplayName" type="string" />
        <property name="AllowZoneChange" type="bool">True</property>
        <property name="ChromeState" type="chromestate">Normal</property>
        <property name="DisableSaveAsNewViewButton" type="bool">False</property>
        <property name="ViewFlag" type="string" />
        <property name="DataSourceID" type="string" />
        <property name="ExportMode" type="exportmode">All</property>
        <property name="AutoRefresh" type="bool">False</property>
        <property name="FireInitialRow" type="bool">True</property>
        <property name="AllowEdit" type="bool">True</property>
        <property name="Description" type="string" />
        <property name="HelpMode" type="helpmode">Modeless</property>
        <property name="BaseXsltHashKey" type="string" null="true" />
        <property name="AllowMinimize" type="bool">True</property>
        <property name="CacheXslTimeOut" type="int">86400</property>
        <property name="ChromeType" type="chrometype">Default</property>
        <property name="Xsl" type="string" null="true" />
        <property name="JSLink" type="string" null="true" />
        <property name="CatalogIconImageUrl" type="string">/_layouts/15/images/itdl.png?rev=23</property>
        <property name="SampleData" type="string" null="true" />
        <property name="UseSQLDataSourcePaging" type="bool">True</property>
        <property name="TitleIconImageUrl" type="string" />
        <property name="PageSize" type="int">-1</property>
        <property name="ShowTimelineIfAvailable" type="bool">True</property>
        <property name="Width" type="string" />
        <property name="DataFields" type="string" />
        <property name="Hidden" type="bool">False</property>
        <property name="Title" type="string" />
        <property name="PageType" type="Microsoft.SharePoint.PAGETYPE, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">PAGE_NORMALVIEW</property>
        <property name="DataSourcesString" type="string" />
        <property name="AllowClose" type="bool">True</property>
        <property name="InplaceSearchEnabled" type="bool">True</property>
        <property name="WebId" type="System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">00000000-0000-0000-0000-000000000000</property>
        <property name="Height" type="string" />
        <property name="GhostedXslLink" type="string">main.xsl</property>
        <property name="DisableViewSelectorMenu" type="bool">False</property>
        <property name="DisplayName" type="string" />
        <property name="IsClientRender" type="bool">False</property>
        <property name="XmlDefinition" type="string">&lt;View Name="{FA0742C6-54A6-476C-8DB6-247AE4DAE34C}" MobileView="TRUE" Type="HTML" Hidden="TRUE" DisplayName="" Url="/My School/2392/default.aspx" Level="1" BaseViewID="1" ContentTypeID="0x" ImageUrl="/_layouts/15/images/dlicon.png?rev=23" &gt;&lt;Query&gt;&lt;OrderBy&gt;&lt;FieldRef Name="FileLeafRef"/&gt;&lt;/OrderBy&gt;&lt;/Query&gt;&lt;ViewFields&gt;&lt;FieldRef Name="DocIcon"/&gt;&lt;FieldRef Name="LinkFilename"/&gt;&lt;FieldRef Name="Modified"/&gt;&lt;FieldRef Name="Editor"/&gt;&lt;/ViewFields&gt;&lt;RowLimit Paged="TRUE"&gt;30&lt;/RowLimit&gt;&lt;JSLink&gt;clienttemplates.js&lt;/JSLink&gt;&lt;XslLink Default="TRUE"&gt;main.xsl&lt;/XslLink&gt;&lt;Toolbar Type="Standard"/&gt;&lt;/View&gt;</property>
        <property name="InitialAsyncDataFetch" type="bool">False</property>
        <property name="AllowHide" type="bool">True</property>
        <property name="ParameterBindings" type="string">
  &lt;ParameterBinding Name="dvt_sortdir" Location="Postback;Connection"/&gt;
            &lt;ParameterBinding Name="dvt_sortfield" Location="Postback;Connection"/&gt;
            &lt;ParameterBinding Name="dvt_startposition" Location="Postback" DefaultValue=""/&gt;
            &lt;ParameterBinding Name="dvt_firstrow" Location="Postback;Connection"/&gt;
            &lt;ParameterBinding Name="OpenMenuKeyAccessible" Location="Resource(wss,OpenMenuKeyAccessible)" /&gt;
            &lt;ParameterBinding Name="open_menu" Location="Resource(wss,open_menu)" /&gt;
            &lt;ParameterBinding Name="select_deselect_all" Location="Resource(wss,select_deselect_all)" /&gt;
            &lt;ParameterBinding Name="idPresEnabled" Location="Resource(wss,idPresEnabled)" /&gt;&lt;ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noitemsinview_doclibrary)" /&gt;&lt;ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noitemsinview_doclibrary_howto2)" /&gt;</property>
        <property name="DataSourceMode" type="Microsoft.SharePoint.WebControls.SPDataSourceMode, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">List</property>
        <property name="AutoRefreshInterval" type="int">60</property>
        <property name="AsyncRefresh" type="bool">False</property>
        <property name="HelpUrl" type="string" />
        <property name="MissingAssembly" type="string">Cannot import this Web Part.</property>
        <property name="XslLink" type="string" null="true" />
        <property name="SelectParameters" type="string" />
      </properties>
    </data>
  </webPart>
</webParts>'

$serverRelativeUrl = '/My School/2392/default.aspx'

$pageRelativeUrl='/My School/2392/default.aspx'


$clientContext= [Microsoft.SharePoint.Client.ClientContext,Microsoft.SharePoint.Client, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c]

Foreach ($i in $pageRelativeUrl)
    
{
$siteurl='https://portal.peelschools.org/My School/2392'
 write-host "test 1 " $siteUrl
    $name = $i.Substring($i.IndexOf("/My School/2392")+9,$i.IndexOf("/Lists")-13)

    $siteurl = "$siteurl$name"
    write-host "test " $siteUrl
    $context=New-Object Microsoft.SharePoint.Client.ClientContext($siteurl)
    

    write-host "Reading file " $i

    $oFile = $context.Web.GetFileByServerRelativeUrl($i);

    $limitedWebPartManager = $oFile.GetLimitedWebPartManager([Microsoft.Sharepoint.Client.WebParts.PersonalizationScope]::Shared);

    write-host "getting xml reader from file"

    $xtr = New-Object System.Xml.XmlTextReader($localWebpartPath)

    [void] [Reflection.Assembly]::LoadWithPartialName("System.Text")

    $sb = new-object System.Text.StringBuilder

    try

    {

    if ($xtr -ne $null)

    {

    $xtr.Close()

    }

    #Add Web Part to catalogs folder

    write-host "Adding Webpart....."

    $oWebPartDefinition = $limitedWebPartManager.ImportWebPart($wpxml);

    $limitedWebPartManager.AddWebPart($oWebPartDefinition.WebPart, "Main", 0);

    $context.ExecuteQuery();

    write-host "Adding Web Part Done"

    }

    catch

    {

    write-host "Error while 'AddWebPartToPage'" $_.exception

    }
}

Wednesday, 26 September 2018

Powershell - copy files from on document library to another keep the original modified by and created by

Copy files from one document library to another document library within the same site collection.

script

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Copy Files from Source Folder to Target Folder
Function Copy-Files($SourceFolder, $TargetFolder)
{
    write-host "Copying Files from:$($SourceFolder.URL) to $($TargetFolder.URL)"
    #Get Each Source File
    $SourceFilesColl = $SourceFolder.Files

    #Iterate through each items
    Foreach($SourceFile in $SourceFilesColl)
    {
        #Copy File from the Source
        $NewFile = $TargetFolder.Files.Add($SourceFile.Name, $SourceFile.OpenBinary(),$True)
     
       #Copy updated required fields
        $ditem =  $NewFile.Item
        $ditem["Modified"] =$SourceFile.TimeLastModified.ToLocalTime()
        $ditem["Created"] = $SourceFile.TimeCreated.ToLocalTime()
        $ditem["Author"] = $SourceFile.Author
        $ditem["Editor"] = $SourceFile.ModifiedBy

        #Copy Meta-Data
        Foreach($Field in $SourceFile.Item.Fields)
        {

            If(!$Field.ReadOnlyField)
            {
                if($NewFile.Item.Fields.ContainsField($Field.InternalName))
                {
                    $NewFile.Item[$Field.InternalName] = $SourceFile.Item[$Field.InternalName]
                }
            }
        }
        #Update
        $NewFile.Item.UpdateOverwriteVersion()
   
        Write-host "Copied File:"$SourceFile.Name
    }
   
    #Process SubFolders
    Foreach($SubFolder in $SourceFolder.SubFolders)
    {
        if($SubFolder.Name -ne "Forms")
        {
            #Check if Sub-Folder exists in the Target
            $NewTargetFolder = $TargetFolder.ParentWeb.GetFolder($SubFolder.Name)

            if ($NewTargetFolder.Exists -eq $false)
            {
                #Create a Folder
                $NewTargetFolder = $TargetFolder.SubFolders.Add($SubFolder.Name)
            }
            #Call the function recursively
            Copy-Files $SubFolder $NewTargetFolder
        }
    }
}

#Variables
$WebURL="https://portal.peelschools.org/My School/1553"
$SourceLibrary ="Shared Documents Area"
$TargetLibrary = "New"

#Get Objects
$Web = Get-SPWeb $WebURL
$SourceFolder = $Web.GetFolder($SourceLibrary)
$TargetFolder = $Web.GetFolder($TargetLibrary)

#Call the Function
Copy-Files $SourceFolder $TargetFolder


powershell-in-sharepoint.html#ixzz5S8r4cB00

Wednesday, 5 September 2018

Nintex Form - hiding panel and white spaces is being displayed

I have large amount of white space on my form because I am hiding multiple panels.

Steps to resolve issue
1. are the panel touching
2. create a separate rule for each panel

Thursday, 19 July 2018

Change the layout page of a publishing page

Issue

Update an exiting page to a new layout page and need to update all my sites page to the new layout page.


Code
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Site that I would like to implement the change on
$StartWeb="https://intranet.peelschools.org/ltss/pmo/PMLC"

#filter to only the sites that I want
$subsites = ((Get-SPWeb $StartWeb).Site).allwebs | ?{$_.url -like "$StartWeb*"}
$pWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($subsites)
$pSite = New-Object Microsoft.SharePoint.Publishing.PublishingSite($subsites.Site)

#need the root of the site collection to get the layout page from
$rootSite = Get-SPSite https://intranet.peelschools.org
$site =$subsites
$lookForList = "Pages"

   foreach($subsite in $subsites){

            $spPubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($subsite)
            $pages = $spPubWeb.PagesList
            $myLayout = $siteLayouts["/_catalogs/masterpage/PDSB/Content.aspx"]

            #Add site content types to the list
            $ctToAdd = $rootSite.RootWeb.ContentTypes["Intranet SP2013"]
            $ct =  $pages.ContentTypes.Add($ctToAdd)
            write-host "Content type" $ct.Name "added to list"  $pages.Title
         

            foreach($item in $pages.Items)
            {
                $pubPage = [Microsoft.SharePoint.Publishing.PublishingPage]::GetPublishingPage($item)
               
                if ($pubPage.Title -ne "Forms" -and $pubPage.Title -ne "All Documents" -and $pubPage.Title -ne "Documents")
                {           
                    $pubPage.CheckOut()
                    $pubPage.Layout = $myLayout
                   # $pubPage.item["Show Resources in page"]=$true
                   $pubPage.
                    $pubPage.Update()
                    $pubPage.CheckIn("")
                    $pageFile = $pubPage.ListItem.File
                    $pageFile.Publish("")
                 }                     
            }
            Write-Host $subsite.url  "is done"
 }

$subsites.Dispose()
$rootsite.Dispose()

$site.Dispose()

Display attachments as an image

Request

Display the attachments as image using jquery script.  The attachments are images that have been uploaded.  The attachments are still links but the image is displayed on the form in read mode.

Example


Code 
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js">​
</script>
<script type="text/javascript">
    $(document).ready(function(){
$('#idAttachmentsTable tr td span a').each(function() {
$(this).text('');
var a_href = $(this).attr('href');
$(this).append("<img alt='' src='" + a_href + "' width=80% />");


});

    });
    </script>

Results




Wednesday, 14 December 2016

error export Nintex workflow

Issue 

When trying to export the Nintex workflow we got the following errors.

 Error #1

Server Error in '/' Application.

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

http://go.microsoft.com/fwlink/?LinkID=314055

 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

http://go.microsoft.com/fwlink/?LinkID=314055


Error #2

Server Error in '/' Application.

Cannot find workflow in repository.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Nintex.Workflow.NWException: Cannot find workflow in repository.

Source Error:


An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[NWException: Cannot find workflow in repository.]
   Nintex.Workflow.WorkflowRepository.get_Item(Guid wfId) +673
   Nintex.Workflow.ApplicationPages.ExportWorkflow.Page_Load(Object sender, EventArgs e) +990

[NWException: Error exporting workflow.]
   Nintex.Workflow.ApplicationPages.ExportWorkflow.Page_Load(Object sender, EventArgs e) +1523
   Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase.OnLoad(EventArgs e) +300
   Microsoft.SharePoint.WebControls.LayoutsPageBase.OnLoad(EventArgs e) +49
   System.Web.UI.Control.LoadRecursive() +71
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178



This is happening because you are accessing the workflow from site setting-> Workflows gallery (Nintex Workflow section) in top the level site (root of the site collection).


You need to access the workflow from site Nintex menu.



.

Wednesday, 12 October 2016

Powershell: starting a workflow on items in list within a view

I had so much trouble getting this to work I thought I would share this.

Limitation of this you can only process the items within the page of the view so you need to change your max page number to 1000.


#web site url
$siteurl="https://portal.peelschools.org/MLP"
#list name
$ListName="AODAACCE"
#workflow Name
$workflowName="DBUpdateReusable2010WF"
#view name Note: Change the view limit to 1000. This script is limited the page in a view.
$viewName="wf"

#content type name
$ctname="MLPRequiredAction"
$cTypes = $list.ContentTypes
$cType = $cTypes[$ctname]

$web = Get-SPWeb -Identity $siteurl
$manager = $web.Site.WorkFlowManager

$List = $Web.lists[$ListName]
$view = $list.Views[$viewName]

# Name of the Workflow
$assoc = $cType.WorkflowAssociations.GetAssociationByName($workflowName,"en-US")

$web.AllowUnsafeUpdates = $true
$wf = $cType.WorkflowAssociations
$data = $wf.AssociationData


write-host $view.Url
foreach($item in $list.GetItems($view))
{

 $mywf = $manager.StartWorkFlow($item,$assoc,$data,$true)

}
$manager.Dispose()
$Web.Dispose()


Error message 
Exception calling "StartWorkflow" with "4" argument(s): "This workflow association is not valid for use with this item."
At line:33 char:2
+  $mywf = $manager.StartWorkFlow($item,$assoc,$data,$true)
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentException

I had to add  the following line to resolve the error.
$web.AllowUnsafeUpdates = $true