Showing posts with label SharePoint 2013. Show all posts
Showing posts with label SharePoint 2013. Show all posts

Tuesday, December 18, 2018

SharePoint upgrade missing feature reference issue

While I tried to migrated the SharePoint 2010 Data base to SharePoint 2016 through the database upgrade approach , I received the below missing feature error

Database [database] has reference(s) to a missing feature: Name = [PowerPivot Feature 
                  Integration for Site Collections], Id = [1a33a234-b4a4-4fc6-96c2-8bdb56388bd5

usually if you follow this blog Link, you should be able to clean up the missing feature , if not by using the feature admin tool you should be able to clean up the faulty feature at the source . But in this case neither worked . SharePoint 2010 was not showing that this feature was activated , but the upgrade was failing in SharePoint 2013/2016 .

Hence i decide to do some digging myself  in SQL and try to resolve the issue , below are the steps followed to resolve the issue




1.      Open SSMS in source (SharePoint 2010 /2013), run the below script to find the tables in DB where the missing feature is referenced

USE [Name of the DB]
GO
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%FeatureId%'
ORDER BY schema_name, table_name;

2.      Query result would provide the list of tables in SQL

table_name        schema_name   column_name
AllLists                  dbo                       tp_FeatureId
CustomActions   dbo                       FeatureId
Features              dbo                       FeatureId
FeatureTracking dbo                      FeatureId

3.      Open up each table in SQL and identify the row as per sample query

Select * from [data base name].[dbo].[tablename] where tp_featureID = ‘guid of missing feature’

Results would provide the webID of the website

4.      Open up any of the SharePoint server in the farm and execute the below query , this would list all the site and webs with the ID
5       
Get-SPWebApplication http://sharepoint.dev.symetra.com/ | Get-SPSite -Limit All | Get-SPWeb -Limit All | Select Title, URL, ID, ParentWebID | Export-CSV C:\InfoArch.csv –NoTypeInformation

6.      Navigate to the website and clean up the component which is referred by the feature .

I In my case there was a faulty power pivot library at SharePoint 2010 , I went ahead and cleaned up the library at 2010

Tuesday, August 22, 2017

SSRS issue in SharePoint 2013 integrated mode .

I did recently come across an issue with SSRS in SharePoint 2013 integrated mode , the error was while opening up a SSRS report . Error stated as below


·        An error occurred during client rendering.
o   The requested service, 'http://serverName:32843/39c0f43bbd794f929239eb6ede09edb6/ReportStreaming.svc' could not be activated. See the server's diagnostic trace logs for more information.

The requested service, 'http://serverName:32843/39c0f43bbd794f929239eb6ede09edb6/ReportStreaming.svc' could not be activated. See the server's diagnostic trace logs for more information.


There was no much information on the above issue , only way to figured out the issue was by testing the SSRS webservice URL


open the management studio and enter below command
Get-SPRSServiceApplication

You will get the result with Name,ID and UEAccountName

You can frame the report service webapplication ID with this GUID as below

1)    http://serverName:32843/39c0f43bbd794f929239eb6ede09edb6/ReportingWebService.svc --> this URL is working fine 
12)http://serverName:32843/39c0f43bbd794f929239eb6ede09edb6/ReportStreaming. à this one throws a error as below 


Memory gates checking failed because the free memory (208904192 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.



Increasing the RAM of the server resolved the issue

Thursday, August 10, 2017

Secure store service issue in SharePoint 2013

Recently were trying some tests on migration of SharePoint 2010 contents to SharePoint 2016 , having SharePoint 2013 as intermediary server without which the migration will not be successful .

Had this weird issue of Secure store service application not being created in SharePoint 2013, the farm was built by someone a yr ago , so did not have the full data on the issue , but below were the errors in ULS

Microsoft.SharePoint.SPException: Your session has expired. Restart this wizard to continue.  
 at Microsoft.SharePoint.Administration.SPScenarioContext.GetContext(Page page, CultureInfo culture)   
 at Microsoft.Office.SharePoint.ClientExtensions.SecureStoreAdministration.CreateSSSApplicationStateInfo.OnLoad(EventArgs e) 

Application error when access /_admin/sssvc/createsssvcapplicationstateinfo.aspx, Error=Your session has expired. Restart this wizard to continue. 


The current state '_admin/sssvc/createsssvcapplication.aspx' doesn't match the Page '_admin/sssvc/createsssvcapplicationstateinfo.aspx'


I was unable to fix this issue not the root cause of it yet , but figured it out that this was an issue only through the UI , so I could still go ahead the create a new Secure store service application through power shell 

New-SPSecureStoreServiceApplication -ApplicationPool "app pool name which already exists" -AuditingEnabled:$false -DatabaseServer "devomasp02" -DatabaseName "Secure store SANew"-Name "Secure store SANew"

$secureStoreApplicationName  ="Secure Store Service Application"
Get-SPServiceApplication | ? {$_.GetType().Equals([Microsoft.Office.SecureStoreService.Server.SecureStoreServiceApplication])} | New-SPSecureStoreServiceApplicationProxy -Name $secureStoreApplicationProxyName -DefaultProxyGroup | Out-Null

I shall look into issue and keep posted if I fix it 

Friday, September 16, 2016

Using Custom fonts in SharePoint

You can use the custom fonts in SharePoint applications ,below are the few things you may have to perform in order to get the new stylish fonts which you want to display to your users in your application .

My experience was to try use the "Avenier" fonts ,this is a paid font and it is been widely used these days .

1)I received the few packages like "Avenir Next Condensed.ttc" "Avenir Next.ttc" "Avenir.ttc"
2) If you try to use these package directly on to your site it will not work ,as the the extension of the file says it is a collection  "TrueType collection font file" .
3)Hence use some tools (many tools are readily available online)  to convert the truetype collection font file to "TrueType font file.
4)What it basically does it breaks the collection of files into individual files (ttf from ttc)
5)Now there are many different formats of font file you can use in your application
6)I have again used the online converter and converted my ttf  files to ".woff"  format
7)Upload these files in any of the document library (eg: site assets"
8)Now you are ready to use your new font in your css file as below

@font-face {
      font-family: "ThiloshNewFont";
      src: url("http://SiteCollection/SiteAssets/HLS-LEAD-FontFamily/AvenirNext-DemiBold.woff");


using in the custom class as below 


.testNewclass
{

     font-family: "ThiloshNewFont";

}


So now in which ever HTML element you use this ".testNewClass" the font style applied will be  "AvenirNextDemiBold"


Thursday, May 19, 2016

Add items to Sharepoint having multiselect Lookup through SharePoint REST


If you are trying to add the list items in the normal way using the REST you would probably get this error

"an unexpected 'primitivevalue' node was found when reading from the json reader"

This is because you would have used the wrong format of people picker or lookup field to update or add item .Below eg "spLookup" is my lookup field and is multiselect .Sharepoint creates the field named spLookupId .


function CreateListItems(){
var data = {
    __metadata: { 'type': 'SP.Data.ThiloshListItem' },
    Title: 'Create from the REST code',  
    spLookupId : { 'results': [1,2] }
};

var url = "/_api/web/lists/getbytitle('thilosh')/items";
var siteurl = "https://thilosh1224456.sharepoint.com/sites/TeamSite"
//var test = __spPageContextInfo.webAbsoluteUrl;
$.ajax({
       // url: __spPageContextInfo.webAbsoluteUrl + url,
   url : siteurl + url,
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },
        data: JSON.stringify(data),
        success: function (data) {
            $("#resultArea").append("Item added from REST code");
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}

Friday, November 27, 2015

SharePoint Migration Lookup error

There was site in SharePoint 2010 and I was planning to move it to SharePoint 2013 version by performing a Content db migration .

The site had a list which consists of lookup columns ,these were lookup to other list.But the point here was that these columns were hidden while it was created through element.xml in the solution .The list was working fine in SharePoint 2010 ,But when I migrated the 2010 site to SharePoint 2013 the link of the lookup is lost and the data is been displayed as a text field Eg: "#2;lookupValue" etc .
This was creating few problems in my solution due to mismatch in the values of the list itms .I had to fix the lookup column .Below is the resolution to this migration error



I placed the below code in Content Editor WebPart and made the field readable,This changed the column back as lookup .Later you can change the column to readonly =true


<content id="Main" contentplaceholderid="PlaceHolderMain" runat="server"></content><script language="ecmascript" type="text/ecmascript">
        var fieldCollection;
        var field;
        var list;
        function UpdateField() {
            var clientContext = SP.ClientContext.get_current();
            if (clientContext != undefined && clientContext != null) {
                var webSite = clientContext.get_web();
                this.list = webSite.get_lists().getByTitle("ListA");
                this.fieldCollection = list.get_fields();
                this.field = fieldCollection.getByTitle("Column1");
                this.field.set_readOnlyField(false);
                this.field.update();

            clientContext.load(this.fieldCollection);
            clientContext.load(this.field);
                clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
            }
        }
        function OnLoadSuccess(sender, args) {
            alert("Field deleted successfully.");
        }
        function OnLoadFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }
</script><input type="button" id="btnUpdateField" onclick="UpdateField()" value="Change ReadOnly"/> 

Tuesday, September 8, 2015

Move Sharepoint folders and files in list/Libraries through powershell



I had this folder movement structure of
1)Adjacency
    2)Group
          3)Subgroup

Below is the Powershell code through which I achieved it.It can be used to move files and folders in the same library or to different library.You could also pick only the subfolders to be moved or the whole main folder to be moved



$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}


$logFile = "LogFile_MoveFiles.txt"

function create-fileitems()
    {
     [CmdletBinding()]
     param(
[Parameter(position=1, mandatory=$true, parametersetname="Default")] [Microsoft.SharePoint.SPDocumentLibrary]$SourceList,
[Parameter(position=2, mandatory=$true, parametersetname="Default")] [Microsoft.SharePoint.SPDocumentLibrary]$DestinationList,
     [Parameter(position=3, mandatory=$true, parametersetname="Default")] [string] $SourceAdjacencyToMove,
     [Parameter(position=4, mandatory=$true, parametersetname="Default")] [string] $ConfirmAdjToMove,
     [Parameter(position=5, mandatory=$true, parametersetname="Default")] [string] $SourceGroupToMove,
     [Parameter(position=6, mandatory=$true, parametersetname="Default")] [string] $DestinationAdjToMove,
     [Parameter(position=7, mandatory=$true, parametersetname="Default")] [Microsoft.SharePoint.SPWeb]$sourceweb
     )
        $src = $SourceList
        $tgt = $DestinationList
        $SourceAdjacency = $SourceAdjacency
        $AllFolders = $src.Folders
        $srcRootFolder = $src.RootFolder
        $allfiles = $src.items
        $RootItems = $srcRootFolder.files
        $destRootFolder = $tgt.RootFolder
        $arrListFolderURLToDelete = New-Object System.Collections.ArrayList
        Try
         {
          foreach($Folder in $src.RootFolder.SubFolders)
           {
         if($Folder.Name -eq $SourceAdjacencyToMove)
           {
            $srcFolderURL = $folder.url
            $destFolderURL = $srcFolderURL          
            $destFolderURL = $destFolderURL -replace $SourceAdjacencyToMove, $DestinationAdjToMove
            $srcItems = $Folder.folder.files
            if(!($tgt.Folders | ? {$_.URL -eq $destFolderURL}))
            {
             
                $parentFolderURL = $Folder.ParentFolder.ServerRelativeUrl
                $newFolder = $src.Additem($parentFolderURL,[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$DestinationAdjToMove)
                $newFolder.Update()
                write-host -ForegroundColor Green "Folder Creation:"$destFolderURL" - Complete"
                Add-Content $logFile "Folder Creation: $destFolderURL - Complete"
            }          
               foreach($subFolder in $Folder.SubFolders)
               {
                   if($ConfirmAdjToMove -eq "N" -or $ConfirmAdjToMove -eq "n")
                     {
                        if($subFolder.Name -eq $SourceGroupToMove)
                        {
                            MoveGroup $Folder $subFolder $srcRootFolder $destRootFolder $tgt $AllFiles
                            $arrListFolderURLToDelete.Add($subFolder.URL) | Out-Null
                        }
                     }
                   else
                     {
                       MoveGroup $Folder $subFolder $srcRootFolder $destRootFolder $tgt $AllFiles
                       $arrListFolderURLToDelete.Add($subFolder.URL) | Out-Null
                     }
                   
               }
             if($ConfirmAdjToMove -eq "Y" -or $ConfirmAdjToMove -eq "y")
               {
                 $arrListFolderURLToDelete.Add($Folder.URL) | Out-Null
               }  
                     
           }

        }
          Foreach($folderURLToDelete in $arrListFolderURLToDelete)
           {

                $folderToDelete = $sourceweb.GetFolder($folderURLToDelete)
                $folderToDelete.Delete()

             }
         }
        catch
         {
            Write-Host  $_.Exception.Message
            Add-Content $logFile    "***Error description Starts****`n"
            Add-Content $logFile    $_.Exception.Message      
            Add-Content $logFile    "***Error description ends****`n"
         }

      }

 function MoveGroup($Folder,$subFolder , $srcRootFolder ,$destRootFolder,$tgt,$AllFiles)
    {
        $srcSubFolderURL = $subFolder.url
        $destSubFolderURL = $srcSubFolderURL                  
        $destSubFolderURL = $destSubFolderURL -replace $SourceAdjacencyToMove, $DestinationAdjToMove
        $srcSubItems = $subFolder.folder.files
          if(!($tgt.Folders | ? {$_.URL -eq $destSubFolderURL}))
              {
                        $parentFolderURL = $Folder.serverrelativeurl
                        $parentFolderURL = $parentFolderURL -replace $SourceAdjacencyToMove, $DestinationAdjToMove                                              
                        $newFolder = $src.Additem($parentFolderURL,[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$subFolder.name)
                        $newFolder.Update()
                        write-host -ForegroundColor Green "Folder Creation:"$destSubFolderURL" - Complete"
                        Add-Content $logFile "Folder Creation: $destSubFolderURL - Complete"
                      }
                   
                foreach($sub2Folder in $subFolder.SubFolders)
                      {
                            $srcSub2FolderURL = $sub2Folder.url
                            $destSub2FolderURL = $srcSub2FolderURL                          
                            $destSub2FolderURL = $destSub2FolderURL -replace $SourceAdjacencyToMove, $DestinationAdjToMove
                            $srcSub2Items = $sub2Folder.folder.files
                            if(!($tgt.Folders | ? {$_.URL -eq $destSub2FolderURL}))
                              {
                                $parentFolderURL = $subFolder.serverrelativeurl              
                                $parentFolderDestination = $destRootFolder                              
                                $parentFolderURL = $parentFolderURL -replace $SourceAdjacencyToMove, $DestinationAdjToMove                                                      
                                $newFolder = $src.Additem($parentFolderURL,[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$sub2Folder.name)
                                $newFolder.Update()
                                write-host -ForegroundColor Green "Folder Creation:"$destSub2FolderURL" - Complete"
                                Add-Content $logFile "Folder Creation: $destSub2FolderURL - Complete"
                              }
                     
                       $destFolder = $src.Folders | ? {$_.url -eq $destSub2FolderURL}
                             if($sub2Folder.Files.count -gt 0)
                              {
                                $srcItems = $sub2Folder.Files
                                    foreach ($item in $srcItems)
                                    {
                                        $sourceListItem = $item.Item
                                        [Microsoft.Office.RecordsManagement.RecordsRepository.Records]::UndeclareItemAsRecord($sourceListItem)
                                        $Relative = $Item.URL
                                        $TargetItem = $AllFiles | ? {$_.URL -eq $Relative}
                                        $sBytes = $TargetItem.File.OpenBinary()
                                        $dFile = $destFolder.Folder.Files.Add($TargetItem.Name, $sBytes, $true)
                                        $ditem = $dfile.Item
                                        $ditem["Modified"] = $Item.TimeLastModified.ToLocalTime()
                                        $ditem["Created"] = $Item.TimeCreated.ToLocalTime()
                                        $ditem["Author"] = $Item.Author
                                        $ditem["Editor"] = $Item.ModifiedBy                                                                              
                                        $ditem.SystemUpdate($true)
                                        $dFile.CheckIn("Check in by Administrator")
                                        $dFile.Update()
                                        write-host -ForegroundColor Green "File Creation:" $dfile.name" - Complete"
                                        Add-Content $logFile "File Creation: $dfile.name - Complete"
                                    }
                               }
                       }
   }
 


$siteURL = Read-Host "Enter the Site collection URL - Eg:http://Yourwebapplication:1234/ "
$site = Get-SPSite -Identity  $siteURL
$sourceweb = $site.Openweb()
$sourcelist = $sourceweb.lists["LibraryA"]
$destinationlist = $sourceweb.lists["LibraryB"]

$SourceAdjacencyToMove = Read-Host "Enter the name of source Adjacency to be moved"
$DestinationAdjToMove = Read-Host "Enter the name of Destination Adjacency where the files has to be moved to :"
$ConfirmAdjToMove = Read-Host "Press (Y) to move all files ,Press (N) to select Group"


if($ConfirmAdjToMove -eq "N" -or $ConfirmAdjToMove -eq "n")
    {
        $SourceGroupToMove =Read-Host "Enter the Name of Group to be moved"
        create-fileitems -sourcelist $sourcelist -destinationlist $destinationlist -SourceAdjacencyToMove $SourceAdjacencyToMove  -ConfirmAdjToMove  $ConfirmAdjToMove -SourceGroupToMove $SourceGroupToMove -DestinationAdjToMove $DestinationAdjToMove -sourceweb $sourceweb
    }
elseif($ConfirmAdjToMove -eq "Y" -or $ConfirmAdjToMove -eq "y")
    {
        $SourceGroupToMove = " "
        create-fileitems -sourcelist $sourcelist -destinationlist $destinationlist -SourceAdjacencyToMove $SourceAdjacencyToMove  -ConfirmAdjToMove  $ConfirmAdjToMove -SourceGroupToMove $SourceGroupToMove -DestinationAdjToMove $DestinationAdjToMove  -sourceweb $sourceweb
    }




Note: I am using the "[Microsoft.Office.RecordsManagement.RecordsRepository.Records]" because I am working on the Record center and my files are marked as records .Without un-declaring as record ,you cannot perform any action on the document even through powershell or through C# codes.



Monday, March 2, 2015

Add Expiration/Rentention policy in Sharepoint Through powershell


Below is the power-shell script which can be used to add expiration/Retention policy in any version of share-point  through powershell.This helps in moving the policy from one environment to other in a very easy and hassle free way.
               Below power shell script adds the expiration policy to the Content Type at the site collection level ,This is designed to add at Site collection level because this can be run in the Content Hub hosting site and the policy can be migrated to other site collections which are leveraging the Hub.You can make the necessary changes to the script to add the policy at the "Library level" or" to the "content type " at the library level by instantiating the suitable object .
      The script below add the expiration policy like "DocumentDate+0 days" move to "Recycle bin"
"DocumentDate" is my custom column of DateTime type field.



$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}
$logFile = "LogFile_RDM_Expiration_Policy"

function AddExpirationPolicy($web , $contentTypes)
 {
     try
     {
        $arrayCT = $contentTypes.Split(",")
        foreach($CT in $arrayCT)
         {
              Write-host -for yellow "Checking if the Content type" $CT "exists ?"
              Add-Content $logFile "Checking if the Content type $CT exists ?"
              $CT = $web.ContentTypes[$CT]
              if($CT -ne $null)
              {
                Write-host -ForegroundColor green "Content Types -" $CT.Name  "exists !!"
                Add-Content $logFile "Content Types - $CT.Name exists !!"
                $policy=[Microsoft.Office.RecordsManagement.InformationPolicy.Policy]::GetPolicy($CT);
                 if ($policy -eq $null)
                   {
                    $policy=[Microsoft.Office.RecordsManagement.InformationPolicy.Policy]:: CreatePolicy($CT,$null);
                    $policy=[Microsoft.Office.RecordsManagement.InformationPolicy.Policy]::GetPolicy($CT);
                   }
                $policy.Description="Thilosh expiration Policy";
                $policy.Statement="Thilosh expiration Policy";
                $policy.Update();
                $expirypolicyexists=$false;
                if ($policy.Items.Count -ne 0)
                {
                foreach ($policyitem in $policy.Items)
                {
                    if ($policyitem.Name -eq "Retention")
                    {
                        $expirypolicyexists=$true;
                    }
                }
                }
                if ($expirypolicyexists -eq $false)
                 {
                $policyFeatureID = [Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration];
                #Expires data when the current date is equal to the document date set for the record      
                $customData = '<Schedules nextStageId="2">
                                <Schedule type="Default">
                                <stages>
                                  <data stageId="1">
                                    <formula id="Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration.Formula.BuiltIn">
                                      <number>0</number>
                                      <property>DocumentDate</property>                        
                                      <period>days</period>
                                    </formula>
                                    <action type="action" id="Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration.Action.MoveToRecycleBin" />
                                  </data>
                                </stages>
                              </Schedule>
                            </Schedules>'
                $policy.Items.Add($policyFeatureID,$customData);
                #$policy.Items.Add("Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration",$customData);
                $policy.Update();
                Write-Host -ForegroundColor Green  "Expiration  policy added for thr Content Type -" $CT.Name
                Add-Content $logFile "Expiration  policy added for thr Content Type - $CT.Name"
                 }
                else
                 {
                   Write-Host -ForegroundColor Red  "An expiry policy already exists and is not overwritten for the Content type -" $CT.Name
                   Add-Content $logFile   "An expiry policy already exists and is not overwritten for the Content type - $CT.Name"
                 }
              }
              else
              {
                Write-host -ForegroundColor red "Content Types -" $CT  "doesnot exists !!"
                Add-Content $logFile "Content Types - $CT doesnot exists !!"
              }
         
       }
     }
     catch
     {
         Write-Host  $_.Exception.Message      
         Add-Content $logFile    "***Error description Starts****`n"
         Add-Content $logFile    $_.Exception.Message        
         Add-Content $logFile    "***Error description ends****`n"

     }
 }

 $siteURL = Read-Host "Enter the Site collection URL - Eg:http://Thilosh:1234/ "
 $site = Get-SPSite -Identity  $siteURL
 $web = $site.RootWeb
 $contentTypes =  "ContentType1,ContentType2,ContentType3"

 AddExpirationPolicy $web $contentTypes

 $web.Dispose();
 $site.Dispose();




Read-Host "Press enter Key to exit !!"



Now you must be thinking how do I change the formula in "$customData ".This is very simple,You must have heard about a tool named "Sharepoint Manager" by using this you should be able to create formula for literally anything what ever possible in the sharepoint :)


Wednesday, October 22, 2014

Bulk creation of Sharepoint Site column ,Content types ,list and permission groups



Here is the GitHub Link  where I have upload the CSV and power shell scripts which can be used for bulk creation of Sharepoint Site column,Content types,List and permissions,

All you need to do is enter the values in the respective CSV which already consists of some sample values.


https://gallery.technet.microsoft.com/Create-Sharepoint-81bba042#content

Thursday, October 9, 2014

Sharepoint break role inherentence and add custom permission in sharepoint library/List through Powershell

$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}



function AddGroupsToList($groupName,$permissionLevel)
{
    $Group = $web.SiteGroups[$groupName]
    $GroupAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($Group)
    #Get the permission levels to apply to the new groups
    $RoleDefinition = $web.Site.RootWeb.RoleDefinitions[$permissionLevel]
    #Assign the groups the appropriate permission level
    $GroupAssignment.RoleDefinitionBindings.Add($RoleDefinition)
    #Add the group to the site with the permission level
    $list.RoleAssignments.Add($GroupAssignment)    
    $list.Update()
}


$site = Get-SPSite "http://webapplication/sites/RECMRepository/"
$web = $site.RootWeb



#Break Roleinherentence for "Public Documents" list
Write-Host  -foreground "green" "Breaking Role inherentence for the list - Public Documents"
$list = $web.Lists["Public Documents"]
$list.BreakRoleInheritance($false)
#Add Groups to the list with permission levels assigned
AddGroupsToList "Group1" "Full Control"
AddGroupsToList "Group2" "Contribute"
AddGroupsToList "Group3" "Read"


Note:Breaking role inherentence of either site or library or list with Parameter "False" will give you with clean slate no groups from top level will be copied hence I am adding the groups which I need later,

But if the parameter is "True" it will copy the groups from top level,in the case you may need to delete the unwanted groups from the list
 

Create Sharepoint Site Group and role definition through powershell

Below code to be used in powershell file


function createSiteGroups($groupName,$groupOwner,$groupDescription,$permissionLevel,$users)
{
    Write-Host  -foreground "green"  "Creating Sharepoint group -" $groupName
    $web.SiteGroups.Add($groupName, $groupOwner, $groupOwner, $groupDescription)
    $Group = $web.SiteGroups[$groupName]
    $Group.AllowMembersEditMembership = $true
    $Group.Update()
    Write-Host  -foreground "green"  "Creating role assignment for the group -" $groupName
    $GroupAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($Group)

    #Get the permission levels to apply to the new groups
    $RoleDefinition = $web.Site.RootWeb.RoleDefinitions[$permissionLevel]
    #Assign the groups the appropriate permission level
    $GroupAssignment.RoleDefinitionBindings.Add($RoleDefinition)
    #Add the group to the site with the permission level
    $web.RoleAssignments.Add($GroupAssignment)
    Write-Host  -foreground "green"  "Creation of group and role assignment completed successfully for the group -" $groupName
    #Adding users to the group
    Write-Host  -foreground "green"  "Adding users to the group -" $groupName
    $arrayUsers = $users.split(",")
    foreach($user in $arrayUsers)
        {
           if($user -ne "")
             {
               $adUser = $web.Site.RootWeb.EnsureUser($user)
               $Group.AddUser($adUser)
              }
        }
}


You can call the function as below

#Creating Sharepoint security Groups
#create group "Group1 "
$groupName = "Group1"
$groupOwner = $web.Site.Owner
$groupDescription =  "test Group"
$permissionLevel = "Full Control"
$users = "domain\user1,Domain\user2"
createSiteGroups $groupName  $groupOwner $groupDescription $permissionLevel $users



 

Sharepoint create List and attach Content Type to Library or List through powershell

Below code to be used in Powershell file


$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}

function AddContentTypes($web,$libraryName,$libraryDescription,$libraryTemplate,$customContentTypes)
{
   
    #Adding CT
    Write-Host -foreground "green" "Adding Content Types to the Library - " $libraryName
    $docLib = $web.Lists[$libraryName]
    $docLib.ContentTypesEnabled = "True"
    $docLib.update()
    $customContentTypeArray = $customContentTypes.Split(",")
    foreach($customContentType in $customContentTypeArray)
       {
         $customCT = $web.ContentTypes[$customContentType]
         $docLib.ContentTypes.Add($customCT)
         Write-Host -foreground "green" "Content Type -"$customContentType "Added to the List"
       }
    $docLib.update()

}



$site = Get-SPSite "http://Webapplication:777"
$web = $site.RootWeb

$libraryName = "Config"
$libraryDescription = ""
$libraryTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary;
Write-Host -foreground "green" "Creating Library - " $libraryName "...."
# Adding Library
$web.Lists.Add($libraryName,$libraryDescription,$libraryTemplate);
$web.Update();

$customContentTypes = "CT1,CT2,CT3"
AddContentTypes $web $libraryName $libraryDescription $libraryTemplate $customContentTypes



$web.Dispose()
$site.Dispose()

Read-host "Press Enter key to exit ...."



To create site column and Content type use the Link
 

Create sharepoint Site column and Content Types through powershell

Use the below code in Powershell file




$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}
$site = Get-SPSite http://WebApplication:777
$web = $site.RootWeb 

$fieldXML = '<Field Type="Text" ID="{20152dbc-7793-46cb-bc0d-5dd98b0aa1a4}" StaticName="Col1" Name=" Col1" DisplayName=" Col1"
            Description="A document classification ." Required="TRUE" MaxLength="255"
            Group="RDM Site Columns"  ></Field>'
write-host -foreground "green" "Adding Site Column"
$web.Fields.AddFieldAsXml($fieldXML) 

$fieldXML =  '<Field Type="Note" ID="{2808ba7f-78a9-4930-8840-385a18e85b53}" StaticName="Col2" Name=" Col2" DisplayName=" Col2"
        Description="The type of business conducted at a site." Required="FALSE"  NumLines="6" RichText="TRUE"
        Group="RDM Site Columns"  ></Field>'
write-host -foreground "green" "Adding Site Column"
$web.Fields.AddFieldAsXml($fieldXML) 

$fieldXML = '<Field Type="Choice" ID="{ce7f74d7-fc8c-4844-85a9-903e208e68d2}" StaticName="Col3" Name=" Col3" DisplayName=" Col3"
        Description="The status of a complete location." Required="TRUE" Group="EICM Site Columns" >   
<CHOICES>
      <CHOICE>Active</CHOICE>
      <CHOICE>InActive</CHOICE>
      <CHOICE>Pending</CHOICE>
    </CHOICES>
    <Default>Pending</Default>
  </Field>'
write-host -foreground "green" "Adding Site Column"
$web.Fields.AddFieldAsXml($fieldXML) 
 

Write-Host -foreground "green" "Creating Content Type-CT1 ...."
$ctypeName = “CT1”
$ctypeParent = $web.availablecontenttypes["Document"]
$ctype = new-object Microsoft.SharePoint.SPContentType($ctypeParent, $web.contenttypes, $ctypeName)
$ctype.Group = "CT"
$ctype.Description = ""
$web.contenttypes.add($ctype)
 

$field = $web.fields.getfield(“Col1”)
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.add($fieldLink)
$field = $web.fields.getfield(“Col2”)
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.add($fieldLink)
$field = $web.fields.getfield(“Col3”)
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.add($fieldLink)
$ctype.update()
 

If u need to delete any field in child CT which got inherted from Parent CT then you can use the below code 

 

Write-Host -foreground "green" "Creating Content Type-CT2 ...."
$ctypeName = “CT2”
$ctypeParent = $web.availablecontenttypes["CT1"]
$ctype = new-object Microsoft.SharePoint.SPContentType($ctypeParent, $web.contenttypes, $ctypeName)
$ctype.Group = "EICM Content Types"
$ctype.Description = ""
$web.contenttypes.add($ctype)
 

$field = $web.fields.getfield(“col1”)
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.Delete($fieldLink.Id)
$ctype.update()

Monday, July 7, 2014

update aspx or any file through Powershell

I had this problem of SharePoint people picker issue, where in the People picker restricted to particular SharePoint group was having UI problem .Problem was that when you try to search users a popup open with the users in that SharePoint group for you to be selected .

Problem is that the Height of the people picker popup in IE10 was very small as below.
It was working fine in IE9,IE11 and IE10 quirks mode


The files in use are picker.aspx and pickerdialog.aspx .

There were two solutions

Solution-1 : Edit the picker.aspx



·         Locate the div with ID = ‘resultcontent ‘and add style property to it. Set the min-height value from inside the style property like below.

<div id='resultcontent' style="min-height:300px" class="ms-pickerresultdiv">
 
 
Solution-2 : Edit the Pickerdialog.master 
·         In the Meta tags section, set the “X-UA-Compatible” to “IE=EmulateIE9” to make it look like below.
 
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />
Here in this option the page is rendered in IE9 mode  

Client chose the solution-2 and they wanted to automate this using the PowerShell ,hence I wrote the below PowerShell command to take backup of the current pickerdialog.aspx and update the tag in the file which is present in 15 hive, this ps1 has to run in all web front-end server
Below is the PowerShell command
 
 
 
 
Write-host -ForegroundColor Green "Updating Pickerdialog.master file started .........!!"
Write-host -ForegroundColor Green "Creating backup of current file ........."
$a =(Get-Date).ToString('MM-dd-yyyy hh-mm-ss')
$filename = "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\pickerdialog-{0}.master" -f $a
copy "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\pickerdialog.master" $filename
Write-host -ForegroundColor Green "Backup of current file completed ........."
(Get-Content "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\pickerdialog.master") |
Foreach-Object {$_ -replace "<meta http-equiv=`"X-UA-Compatible`" content=`"IE=10`"/>", "<meta http-equiv=`"X-UA-Compatible`" content=`"IE=EmulateIE9`"/>"} |
Set-Content "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\pickerdialog.master"
Write-host -ForegroundColor Green "Updating Pickerdialog.master file completed ........."
pause
 
 
 
 

Friday, May 9, 2014

Add Sharepoint Navigation links with audience targeting through powershell

Below is the powershell command to add Navigation links in SharePoint.This was tested in SharePoint 2013 environment.This script will check if the link is present in the site if not it will add the links along with audience targeting



$snapin = Get-PSSnapin | Where-Object { $_.Name -eq "Microsoft.SharePoint.Powershell" }

if ($snapin -eq $null) {

Write-Host "[INIT] Loading SharePoint Powershell Snapin"

Add-PSSnapin "Microsoft.SharePoint.Powershell"


}

 
 
$Web = Get-SPWeb http://testWebapplication:7777

$TopNav = $Web.Navigation.TopNavigationBar

Write-Host -ForegroundColor Green "Creating Navigation links ......................."



$Heading = $TopNav | where { $_.Title -eq "Link1" }

if($Heading -eq $null)



{
 
$newLink = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode -ArgumentList @("Link1", "/Lists/CreateNewPublication/DocProjects.aspx");

$Heading = $Web.Navigation.TopNavigationBar.AddAsLast($newLink)

$Web.Update()





}

 
 
$Heading = $TopNav | where { $_.Title -eq "Search" }

if($Heading -eq $null)


{
 
$newLink = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode -ArgumentList @("Search", "/SitePages/Search.aspx");

$Heading = $Web.Navigation.TopNavigationBar.AddAsLast($newLink)

$Web.Update()


}
 
$Heading = $TopNav | where { $_.Title -eq "Google" }

if($Heading -eq $null)


{
 
$newLink = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode -ArgumentList @("Google", http://www.google.com);

$Heading = $Web.Navigation.TopNavigationBar.AddAsLast($newLink)

$Web.Update()


}
 
$Heading = $TopNav | where { $_.Title -eq "Yahoo" }

if($Heading -eq $null)



{
 
$newLink = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode -ArgumentList @("Yahoo", http://yahoo.co.in);

$Heading = $Web.Navigation.TopNavigationBar.AddAsLast($newLink)

$Heading.Properties["Audience"] = ";;;;" + "IK,IL,R,C"

$Heading.update()

$Web.Update()





}
 
$Heading = $TopNav | where { $_.Title -eq "Reports" }

if($Heading -eq $null)



{
 
$newLink = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode -ArgumentList @("Reports", "/SitePages/Reports.aspx");

$Heading = $Web.Navigation.TopNavigationBar.AddAsLast($newLink)

$Heading.Properties["Audience"] = ";;;;" + "PM,TL,IL,C"

$Heading.update()

$Web.Update() 



}
 
  $Heading = $TopNav | where { $_.Title -eq " Help" }

if($Heading -eq $null)

{
 
$newLink = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode -ArgumentList @(" Help", "/Lists/HelpLibrary ");

$Heading = $Web.Navigation.TopNavigationBar.AddAsLast($newLink)

$Web.Update()


}
 
Write-Host -ForegroundColor Green "Navigation link creation completed"

Pause