Créer un site internet

Posts by fredericdietrich

Caml Query Issue

By On 16/11/2018

Sharepoint caml query errors

The following exception occurred while trying to enumerate the collection: "Un ou plusieurs types de champs ne sont pas installés correctement. Accédez à la page des paramètres de liste pour supprimer ces champs.

i think my list was corrupted, but it was only my query who's got mistakes

if you see error above, try your query only with <Where></Where>, if she's working, your query contains errors

Powershell Paged Caml Query

By On 16/11/2018

param(
[string]$siteCollUrl = "http://test/sites/site1/",[string]$listTitle="Stockage",
[boolean]$checkin=$false,[boolean]$publish=$false, [boolean]$deleteAllVersion=$true
)
$web = Get-SPWeb $siteCollUrl
$splList = $web.Lists[$listTitle]
$spqQuery = New-Object Microsoft.SharePoint.SPQuery
$spqQuery.Query = "<Where><Neq><FieldRef Name='_Level' /><Value Type='Number'>1</Value></Neq></Where><OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>";
 
$spqQuery.ViewAttributes = "Scope=""RecursiveAll""";
$spqQuery.ViewFields = "<FieldRef Name='FileLeafRef' /><FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='owshiddenversion' /><FieldRef Name='_Level' /><FieldRef Name='_IsCurrentVersion' /><FieldRef Name='_UIVersion' />" #_UIVersionString
$spqQuery.ViewFieldsOnly = $true
 
$spqQuery.RowLimit = 1000;
 
# IsCheckedoutToLocal
$iNumber=1
do{
if($iNumber -eq 1)
{
$spqQuery.ListItemCollectionPosition = $splListItems.ListItemCollectionPosition;
}
$splListItems = $splList.GetItems($spqQuery)
writeInfo "page number : $($iNumber)"
foreach ($splListItem in $splListItems)
{
 
writeInfo "web $($web.ServerRelativeUrl) splList $($splList.RootFolder.ServerRelativeUrl) File id : $($splListItem.Id) # $($splListItem.Name) Title: $($splListItem["Title"]) Version: $($splListItem["owshiddenversion"]) _Level: $($splListItem["_Level"]) _IsCurrentVersion: $($splListItem["_IsCurrentVersion"]) _UIVersion: $($splListItem["_UIVersion"]) ver count : $($splListItem.File.Versions.Count)"
#check in file
try
{
if($checkin)
{
$splListItem.File.CheckIn("CheckIn as admin");
}
}
catch
{
WriteError "error CheckIn web $($web.ServerRelativeUrl) splList $($splList.RootFolder.ServerRelativeUrl) File id : $($splListItem.Id) "
}
#publish file
try
{
if($publish)
{
$splListItem.File.Publish("Publish as admin");
}
}
catch
{
WriteError "error Publish web $($web.ServerRelativeUrl) splList $($splList.RootFolder.ServerRelativeUrl) File id : $($splListItem.Id) "
}
#this is a folder
if($splListItem.ContentTypeId.ToString() -eq "0x00C2208B8CE6E1422CADC1C521EAB2A68B")
{
writeInfo "folder file $($splListItem.File.ServerRelativeUrl)"
continue
}
#delete old versions
if($deleteAllVersion -and $splListItem.File -ne $null -and $splListItem.File.Versions -ne $null -and $splListItem.File.Versions.Count -gt 1)
{
$splListItem.File.Versions.DeleteAll();
writeInfo "versions deleted for $($web.ServerRelativeUrl) splList $($splList.RootFolder.ServerRelativeUrl) File id : $($splListItem.Id)"
}
}
$iNumber+=1
$spqQuery.ListItemCollectionPosition = $splListItems.ListItemCollectionPosition;
}while($spqQuery.ListItemCollectionPosition -ne $null)
 
 
$web.Dispose()
 

get script

utils

Sharepoint ajax Without Jquery

By On 16/11/2018

var xhr = new XMLHttpRequest();
var url = _spPageContextInfo.webAbsoluteUrl;
if (url === "undefined") {
console.log("_spPageContextInfo.webAbsoluteUrl undefined");
url = "http://siteUrl";
}
//xhr.open('GET', url +"/_api/web/Lists?$select=Id,Title,Hidden,ItemCount");
// /_api/web/lists/getbytitle('Projets')/items?$select=Title,ID,
xhr.open('GET', url + "/_api/web");
//prefer using odata=nometadata to get minimum values and upgrade performances
xhr.setRequestHeader("Accept", "application/json; odata=verbose");
 
xhr.onload = function () {
if (xhr.status === 200) {
var kk = JSON.parse(xhr.responseText);
console.dir(kk);
}
else {
console.dir(xhr);
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
 

get script

In HTML

HTML templates

By On 03/11/2018

my html clipboard tool

Sharepoint Rest Base

By On 03/11/2018

//Copy file (copyTo) /_api/web/getFileByServerRelativeUrl('/sites/test/Template.xlsx')/copyTo(strNewUrl='/sites/test/Exports/Template_copy_5.xlsx',bOverWrite=true)
 
function getRequestData(req) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + req,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
console.dir(data);
},
error: function((data) {
console.dir(data);
}
});
}
getRequestData("/_api/web/Lists?$select=Id,Title,Hidden");
 
get script

Set Content Type Field Property

By On 22/10/2018

param([string]$webUrl="http://spdev", [string]$contentTypeName="myContenttype", [string]$fieldName="myTitle", [boolean]$required=$true)
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
clear
$web = Get-SPWeb $webUrl
$ct = $web.ContentTypes[$contentTypeName];
$oldSealedValue = $ct.Sealed;
Write-Host "content type Sealed Property $($ct.Sealed)"
if($ct.Sealed)
{
$ct.Sealed = $false;
}
$field = $ct.FieldLinks[$fieldName];
$field.Required = $required;
Write-Host "set field $($fieldName) Required $($ct.Required)"
 
if($oldSealedValue)
{
$ct.Sealed = $true;
}
$ct.Update($true);
$web.Update();
$web.Dispose();
get script

Powershell Upgrade SPFeature

By On 12/10/2018

param(
[string]$WebApplicationUrl = "http://fdi-sp2013-1",
$featureId = "6cfcd848-1f9f-4bf0-ac99-c6f2df0fc3fc"
)
##########################################################################
# DECLARATIONS
##########################################################################
#Retourne le chemin
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Get-ScriptDirectory | Push-Location
. .\Utils.ps1
$logFileName = "{0}updateFeature.log" -f (Get-Date -Format "yyyyMMdd_HHmm");
$logFilePath = "$($currentFolder)\Logs\UpgradeFeaturePublishing$($logFileName)"
EnsureLogDirectory $logFilePath
##########################################################################
# MAIN
##########################################################################
$currentUrl = "";
try{
if ($WebApplicationUrl -eq ""){
$WebApplicationUrl = AskForWebApplicationUrl
}
$webApp=Get-SPWebApplication $WebApplicationUrl
$webApp.Sites|Foreach-Object{
$spSite=$_
WriteInfo "Site: $($spSite.Url)"
$site=Get-SPSite $spSite.Url
if($site -ne $null)
{
$feature=Get-SPFeature $featureId
if($feature -ne $null){
$featuresForUpgrade = Get-SPSite $spSite.Url | %{$_.QueryFeatures($feature.Id)}
if($featuresForUpgrade -ne $null){
WriteInfo "Old Version..."
$featuresForUpgrade.Version
$featuresForUpgrade.Upgrade($false)
WriteInfo "New Version..."
$featuresForUpgrade.Version
}
}
}
}
Write-Host -NoNewLine 'Press any key to close...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
}catch{
Write-Error -Message $_.Exception.Message
Write-Host -NoNewLine 'Press any key to close...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
}finally{
Pop-Location
}

get script

In SQL

Shrink Sql ContentDataBase Log

By On 12/10/2018

USE WSS_Content_FDI80;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE WSS_Content_FDI80
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (WSS_Content_FDI80_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE WSS_Content_FDI80
SET RECOVERY FULL;
GO

Powershell Get SPList Last Modified

By On 11/10/2018

param($webUrl="http://fdi-sp2013-1:2921", [string]$listTitle="Pages")
 
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
clear;
$web = Get-SPWeb $webUrl
$list = $web.Lists[$listTitle]
$list.PropertiesXml
 
$props = New-Object System.Xml.XmlDocument
$props.LoadXml($list.PropertiesXml)
 
$props.ChildNodes
 
$web.Dispose()
 
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

get script

Listlastmodified

Sharepoint Hide List With REST

By On 10/10/2018

function UpdateList(){
var listName="Acquisition";//set here liste title
var list = {
"__metadata": { "type": 'SP.List' },
"Hidden": true//Set here visibility : true == hidden
};
 
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(list),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function (data) {
alert('Success');
window.location.href=window.location.href;//reload the page
},
error: function (data) {
console.dir(data);
}
});
}
UpdateList();
 
 

REST get Lists From Current Web

By On 08/10/2018

function getlists() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function (data) {
var lists = data.d.results;
console.clear();
console.dir(lists);
for (var i = 0 ; i < lists.length ; i++) {
var lst = lists[i];
//console.dir(lst);
$.ajax({
async: false,
headers: { "accept": "application/json; odata=verbose" },
method: "GET",
url: lst.RootFolder.__deferred.uri,
success: function (data) {
// get the rootFolder
var folder = data.d;
console.log("Title : " + lst.Title + "; RootFolder :" + folder.ServerRelativeUrl
+ "; Hidden :" + lst.Hidden + "; ItemCount :" + lst.ItemCount + "; LastItemModifiedDate :" + lst.LastItemModifiedDate
+ "; BaseTemplate :" + lst.BaseTemplate);
}
});
 
}
},
error: function (data) {
console.log(data);
}
});
}
get the code only

Visual Studio Push Dll to Gac on Build Succeded

By On 05/10/2018

push your dll in gac on build succeded

In your projet setiings click on Build Events, in post buil events add command below

"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\gacutil.exe" /if "$(TargetPath)"

Add task to reset sharepoint search index with powershell

By On 05/10/2018

Create a powershell script (task1.ps1) with code below


if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell -Verbose -ErrorAction:Stop
}
#the $True parameter denotes: Disable Alerts and Ignore Timeout error.
(Get-SPEnterpriseSearchServiceApplication).reset($true, $true)

Add a new task in your task scheduler

Check the radio button 'Run whether user is logged on or not

Set a name and add a trigger to set scheduling

set the action : program / script

	
		%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
	
	

argument with -command followed by the pass to your powershell script

	
		-executionpolicy unrestricted -command D:\PS1\Task1.ps1
	
	

Save your task

 

reset indexes of one content source only

PowerShell Export List Fields To Xml

By On 01/10/2018

param([string]$webUrl=http://fdi-sp2013-1,
[string]$listUrl="Lists/myList",
[string]$contentTypeName,
[boolean]$includeHiddenFields=$true,
[string]$excludeTypes="Computed;Lookup;Guid"
)
clear
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Push-Location
 
function AddType($typeAsString)
{
$types = $excludeTypes.Split(";");
return $types.Contains($typeAsString) -eq $true;
}
function AddField($field)
{
<##>
if(AddType($field.TypeAsString) -eq $false)
{
return;
}
 
$fields = $script:exportNode.SelectSingleNode("/List/Fields");
[System.XML.XMLElement]$oXMLField=$global:exportNode.CreateElement("Field");
#InternalName
$urlAt = $global:exportNode.CreateAttribute("InternalName");
$urlAt.Value = $field.InternalName;
$oXMLField.Attributes.Append($urlAt);
$fields.AppendChild($oXMLField);
#Title
$urlAt = $global:exportNode.CreateAttribute("Title");
$urlAt.Value = $field.Title;
$oXMLField.Attributes.Append($urlAt);
$fields.AppendChild($oXMLField);
#TypeAsString
$urlAt = $global:exportNode.CreateAttribute("TypeAsString");
$urlAt.Value = $field.TypeAsString;
$oXMLField.Attributes.Append($urlAt);
$fields.AppendChild($oXMLField);
#Hidden
$urlAt = $global:exportNode.CreateAttribute("Hidden");
$urlAt.Value = $field.Hidden;
$oXMLField.Attributes.Append($urlAt);
$fields.AppendChild($oXMLField);
#Required
$urlAt = $global:exportNode.CreateAttribute("Required");
$urlAt.Value = $field.Required;
$oXMLField.Attributes.Append($urlAt);
#Group
$urlAt = $global:exportNode.CreateAttribute("Group");
$urlAt.Value = $field.Group;
$oXMLField.Attributes.Append($urlAt);
$fields.AppendChild($oXMLField);
<# #>
}
 
$web = Get-SPWeb $webUrl -ErrorAction:SilentlyContinue;
if($web -eq $null)
{
read-Host "cannot access to $($webUrl) push any key to exit"
exit 0;
}
Write-Host "connected to $($webUrl) Title $($web.Title)"
 
$list = $web.GetList([Microsoft.Sharepoint.Utilities.SPUtility]::ConcatUrls($web.ServerRelativeUrl, $listUrl));
Write-Host "list $($list.Title) loaded"
 
#create xml document
$global:exportNode = New-Object System.Xml.XmlDocument
 
#add list node
[System.XML.XMLElement]$oXMLRoot=$global:exportNode.CreateElement("List")
 
 
#web Url attribute
$urlAt = $global:exportNode.CreateAttribute("url");
$urlAt.Value = $webUrl;
$oXMLRoot.Attributes.Append($urlAt);
 
#web title attribute
$urlAt = $global:exportNode.CreateAttribute("webTitle");
$urlAt.Value = $web.Title;
$oXMLRoot.Attributes.Append($urlAt);
 
#List Title attribute
$urlAt = $global:exportNode.CreateAttribute("ListTitle");
$urlAt.Value = $list.Title;
$oXMLRoot.Attributes.Append($urlAt);
 
#List Url attribute
$urlAt = $global:exportNode.CreateAttribute("ListUrl");
$urlAt.Value = $listUrl;
$oXMLRoot.Attributes.Append($urlAt);
 
#add list note to xmlDocument
$global:exportNode.appendChild($oXMLRoot);
 
$fields = $null;
 
if($includeHiddenFields)
{
$fields = $list.Fields |Sort-Object{$_.InternalName} | select Title, InternalName, TypeAsString, Hidden, Required, Group
}
else
{
$fields = $list.Fields |Sort-Object{$_.InternalName} | Where-Object {$_.Hidden -eq $false} | select Title, InternalName, TypeAsString, Hidden, Required, Group
}
 
#add fields
[System.XML.XMLElement]$oXMLFields=$global:exportNode.CreateElement("Fields")
$global:exportNode.FirstChild.AppendChild($oXMLFields);
foreach($field in $fields){
AddField($field);
}
 
#add ContentTypes
[System.XML.XMLElement]$oXMLContentTypes=$global:exportNode.CreateElement("ContentTypes")
$global:exportNode.FirstChild.AppendChild($oXMLContentTypes);
 
$oXMLContentTypes = $script:exportNode.SelectSingleNode("/List/ContentTypes");
 
foreach($contentType in $list.ContentTypes)
{
[System.XML.XMLElement]$oXMLContentType=$global:exportNode.CreateElement("ContentType");
$urlAt = $global:exportNode.CreateAttribute("Name");
$urlAt.Value = $contentType.Name;
$oXMLContentType.Attributes.Append($urlAt);
 
$oXMLContentTypes.AppendChild($oXMLContentType);
 
 
[System.XML.XMLElement]$oXMLCTFields=$global:exportNode.CreateElement("Fields");
$oXMLContentType.AppendChild($oXMLCTFields);
<##>
if($includeHiddenFields)
{
$fields = $contentType.Fields |Sort-Object{$_.InternalName} | select Title, InternalName, TypeAsString, Hidden, Required, Group
}
else
{
$fields = $contentType.Fields |Sort-Object{$_.InternalName} | Where-Object {$_.Hidden -eq $false} | select Title, InternalName, TypeAsString, Hidden, Required, Group
}
 
 
#fields in content type
foreach($field in $fields)
{
[System.XML.XMLElement]$oXMLCTField=$global:exportNode.CreateElement("Field");
#InternalName
$urlAt = $global:exportNode.CreateAttribute("InternalName");
$urlAt.Value = $field.InternalName;
$oXMLCTField.Attributes.Append($urlAt);
#Title
$urlAt = $global:exportNode.CreateAttribute("Title");
$urlAt.Value = $field.Title;
$oXMLCTField.Attributes.Append($urlAt);
#TypeAsString
$urlAt = $global:exportNode.CreateAttribute("TypeAsString");
$urlAt.Value = $field.TypeAsString;
$oXMLCTField.Attributes.Append($urlAt);
#Hidden
$urlAt = $global:exportNode.CreateAttribute("Hidden");
$urlAt.Value = $field.Hidden;
$oXMLCTField.Attributes.Append($urlAt);
#Required
$urlAt = $global:exportNode.CreateAttribute("Required");
$urlAt.Value = $field.Required;
$oXMLCTField.Attributes.Append($urlAt);
#Group
$urlAt = $global:exportNode.CreateAttribute("Group");
$urlAt.Value = $field.Group;
$oXMLCTField.Attributes.Append($urlAt);
 
$oXMLCTFields.AppendChild($oXMLCTField);
 
}
}
<# #>
#export to test file
$global:exportNode.OuterXml | Out-File "$($list.Title.Replace(" ", "_")).xml" -Encoding utf8
 
#dispose the web
$web.Dispose()

download file

Display Spfield from SPList

By On 29/09/2018

function getListFields() {
var listTitle = "Pages";
var showHidden = false;
var outPut = $("#fdiOutput");
var addOutput = outPut != null && (outPut.length > 0)? true : false;
var tbl = "<table class='fdi-table'>";
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('" + listTitle + "')/Fields",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
},
success: function (response) {
console.log(response);
if (addOutput)
tbl += "<tr><th>InternalName</th><th>Hidden</th><th>TypeAsString</th><th>Title</th></tr>";
for (var i = 0 ; i < response.d.results.length ; i++) {
var field = response.d.results[i];
if (!showHidden && field.Hidden) {
continue;
}
console.log(field.InternalName + " ; " + field.Hidden + " ; " + field.TypeAsString + " ; " + field.DisplayName);
if (addOutput)
tbl += '<tr><td>' + field.InternalName + '</td><td>' + field.Hidden + '</td><td>' + field.TypeAsString + '</td><td>' + field.Title + '</td></tr>';
}
tbl += "</table>";
if (addOutput)
$("#fdiOutput").append(tbl);
},
error: function (data) {
console.log("error getListFields " + listTitle);
console.log(data);
debugger;
}
});
}

get script

Sharepoint PowerShell query search service

By On 29/09/2018

SharePoint PowerShell query search service

param([string]$siteCollectionUrl="http://mySiteUrl" ,
$keyword="ContentTypeId:0x010100020D149374FFC4DF792F30EFC030C9D01* ",
$rowLimit=500,
$SelectProperties="Title,SPWebUrl,Path"
)
 
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
$site = Get-SPSite $siteCollectionUrl
$keywordQuery = New-Object Microsoft.Office.Server.Search.Query.KeywordQuery($site);
 
#set request
$keywordQuery.QueryText = $keyword
 
#set managed properties to retreive
foreach($mnp in $SelectProperties.Split(","))
{
$keywordQuery.SelectProperties.Add($mnp.Trim());
}
$keywordQuery.RowLimit = $rowLimit
 
$searchExec = New-Object Microsoft.Office.Server.Search.Query.SearchExecutor
$searchResults = $searchExec.ExecuteQuery($keywordQuery)
 
#display results
$table = $searchResults.Table
$table | Select Title, SPWebUrl, Path
 
$site.Dispose()

Sharepoint Execute Job With Powershell

By On 28/09/2018

$webApplication = Get-SPWebApplication $siteUrl
$jobName = "lmlhmohmo"
$variationsJob = $webApplication.JobDefinitions | Where {$_.Name -like "$($jobName)*"}
Get-Date
foreach($job in $variationsJob)
{
$lastRunTime = $job.LastRunTime
$job.RunNow()
Write-Host $job.Name + " - " + $job.LastRunTime + " - " + $siteUrl + " - " + $job.Title
 
while ($lastRunTime -eq $job.LastRunTime){
Write-Host -NoNewline "."
Start-Sleep -Seconds 5
}
}
Get-Date

Sharepoint Add SPFolder To SPList By Code

By On 28/09/2018

use code below to add a folder in your SPList or SPFolderCollection
 
SPFolder rollupFolderNAme = styleLib.RootFolder.SubFolders.Cast<SPFolder>().FirstOrDefault(o => o.Name == "new folder");
if (rollupFolderNAme == null)
{
SPFolder newFolder = styleLib.RootFolder.SubFolders.Add("new folder");
newFolder.Update();
}

Sharepoint Powershell Clear Search Cache

By On 28/09/2018

Stop-Service SPTimerV4
$folders = Get-ChildItem C:\ProgramData\Microsoft\SharePoint\Config
foreach ($folder in $folders)
{
$items = Get-ChildItem $folder.FullName -Recurse
foreach ($item in $items)
{
if ($item.Name.ToLower() -eq "cache.ini")
{
$cachefolder = $folder.FullName
}
}
}
$cachefolderitems = Get-ChildItem $cachefolder -Recurse
foreach ($cachefolderitem in $cachefolderitems)
{
if ($cachefolderitem -like "*.xml")
{
$cachefolderitem.Delete()
}
}
 
$a = Get-Content $cachefolder\cache.ini
$a = 1
Set-Content $a -Path $cachefolder\cache.ini
 
read-host "Do this on all your SharePoint Servers and THEN press ENTER"
Start-Service SPTimerV4

testsOnly

By On 28/09/2018

coucou