0

Update Master Page of SharepointSite Using PowerShell

Hi

In this post i have written about how to Update master page of any site of SharePoint.
It can also achieve through OOTB within few click, but it can also achieve using powershell

$site = Get-SPSite http://sp:2000/sites/Ex15
foreach ($web in $site.AllWebs)
{
    $web.MasterUrl = $site.RootWeb.ServerRelativeUrl +  "/_catalogs/masterpage/oslo.master";
    $web.CustomMasterUrl = $site.RootWeb.ServerRelativeUrl + "/_catalogs/masterpage/oslo.master";
    $web.Update();
    Write-Host $web.Url $web.MasterUrl $web.CustomMasterUrl;
}
$site.Dispose()

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    #Get All site collections
    $SiteCollections = Get-SPWebApplication | Get-SPSite -Limit All
    #Loop through all site collections
       foreach($Site in $SiteCollections)
        {
            #Loop throuh all Sub Sites
           foreach($Web in $Site.AllWebs)
           {
		$web.MasterUrl = $site.RootWeb.ServerRelativeUrl +  "/_catalogs/masterpage/oslo.master";
		$web.CustomMasterUrl = $site.RootWeb.ServerRelativeUrl + "/_catalogs/masterpage/oslo.master";
		$web.Update();
		Write-Host $web.Url $web.MasterUrl $web.CustomMasterUrl;
           }
        }

Thanks
SPS

0

Delete Site Collection Using PowerShell

Hi,

Here is Power Shell Code for Delete Site Collection from Particular webApplication

$tmpRoot = Get-SPWebApplication -Identity http://SP:2000
$tmpRootColl=$tmpRoot.Sites
#Enumerate through each site collection
for ($index=$tmpRootColl.Count-1 ; $index-ge 0 ; $index–-)
{
  Remove-SPSite -Identity $tmpRootColl.Item($index) -GradualDelete -Confirm:$false
}
Get-SPDeletedSite | Remove-SPDeletedSite

Thanks
SPS

3

Exports Site Columns Using Powershell

Hi

Here is I am  Explain you  how to export site column using Power shell

Open your notpade++  and copy past below code inthe file save file as .ps1

in this powerhsell code i have generate log file you can notice it from code snippet

just give Export location as per your convince

I assume that you are aware of how to run power shell script in SharePoint managment Shell

pass webUrl as parameter

Remarks-Change groups name with your Group name which you want toin Code


#Necessary Parameters
#Necessary Parameters
[CmdletBinding()]
param 
(
	[string] $Web
)
#/// <summary>
#/// Remove Default Group Permission
#/// </summary>
Function ExportSiteColumnXml([string] $web)
{ 
    try
	{  
      		if($web -ne "")
			{  
              
			    $sourceWeb = Get-SPWeb $web
				$xmlFilePath = "C:\Script-SiteColumns.xml"

				#Create Export Files
				New-Item $xmlFilePath -type file -force

				#Export Site Columns to XML file
				Add-Content $xmlFilePath "<?xml version=`"1.0`" encoding=`"utf-8`"?>"
				Add-Content $xmlFilePath "`n<Fields>"
				$sourceWeb.Fields | ForEach-Object {
					if ($_.Group -eq "Your Site Columns Group Name") {
						Add-Content $xmlFilePath $_.SchemaXml
					}
				}
				Add-Content $xmlFilePath "</Fields>"	                            
             }
             else
             {
                 Write-Host "Please provide proper parameters" -ForegroundColor Red
				LogInfo "Please provide proper parameters"
             }
    }
    catch
    {
      Write-Host "Something went wrong. Please check Logs for additional information" -ForegroundColor Red
        LogError $_

    }
    finally
    { 
        #Dispose your site when process end Successivly
		 if($sourceWeb -ne $null)
			{
				$sourceWeb.Dispose();
			}
			LogInfo "Process Ended"
    }
  

}

#/// <summary>
#/// Prints errors if generated
#/// </summary>
Function LogError($message)
{
     $timeStamp = Get-Date -format "dd/MM/yyyy HH:mm:ss"
     $outContent = "$timeStamp`tError`t`t$message`n"
     Add-Content $Logfile $outContent
}

#/// <summary>
#/// Prints logs in log file
#/// </summary>
Function LogInfo($message)
{
     $timeStamp = Get-Date -format "dd/MM/yyyy HH:mm:ss"
     $outContent = "$timeStamp`tInfo`t`t$message`n"
     Add-Content $Logfile $outContent
}




#/// <summary>
#/// Load the SharePoint Snapin 
#/// </summary>
#/// <returns>
#/// </returns>
Function Load-SharePoint-Powershell
{ 
    Write-Host "TEST"
	if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
	{    
	      Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop
          
	}
     
}

$Logfile = "c:\RTED\RTED-$(get-date -f MMddyyyy_HHmmss).log";
Load-SharePoint-Powershell
ExportSiteColumnXml $web


&nbsp;
0

Get User Profile Properties From SharePoint Online Using CSOM Console application

Hi,

Explain you and share Code How to retrieve User profile Properties For SharePoint online site

Step1-Create Console application From VS

Step2-Put SharepointClient.dll and SharepointClient.Runtime.dll in you dll Folder

Step3-Go to your Solution add dll From your bin Folder path

Step4-Copy past below Code

step5-Change in bold text in Code(SiteUrl,Password,User)

Step6-Run Solution , Properties Export in CSV Format

using System;
using System.Security;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.UserProfiles;
using Microsoft.Web.Hosting.Administration;
namespace UserProfileProp
{
class Program
{
static void Main(string[] args)
{
using (ClientContext tenantContext = new ClientContext(“Sharepoint Online SiteURL”))
{
SecureString passWord = new SecureString();
foreach (char c in “password”.ToCharArray())
passWord.AppendChar(c);
tenantContext.Credentials = new SharePointOnlineCredentials(“Username”, “password”,);

PeopleManager peopleManager = new PeopleManager(tenantContext);

UserCollection users = tenantContext.Web.SiteUsers;
tenantContext.Load(users);
tenantContext.ExecuteQuery();

string csvFilePath = @”C:\Users\sp_admin\Desktop\users.csv”;
StringBuilder items = new StringBuilder();

//PeopleManager peopleManager = new PeopleManager(tenantContext);
PersonProperties personProperties = peopleManager.GetMyProperties();

tenantContext.Load(personProperties);
tenantContext.ExecuteQuery();

tenantContext.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);
tenantContext.ExecuteQuery();
string[] userProfileProperties = new string[personProperties.UserProfileProperties.Count+1];

// string[] userProfileProperties = { “AccountName”, “FirstName”, “LastName”, “PreferredName”, “Manager”, “AboutMe”, “PersonalSpace”, “PictureURL”, “UserName”, “WorkEmail”, “SPS-Birthday” };
int i = 0;
foreach (string key in personProperties.UserProfileProperties.Keys)
{

userProfileProperties[i] = key;
i++;
}
foreach (string propertyKey in userProfileProperties)
{
items.Append(propertyKey);
items.Append(“,”);
}
items.AppendLine();

foreach (Microsoft.SharePoint.Client.User user in users)
{
try
{
if (user.PrincipalType != Microsoft.SharePoint.Client.Utilities.PrincipalType.User) continue;

UserProfilePropertiesForUser userProfilePropertiesForUser = new UserProfilePropertiesForUser(tenantContext, user.LoginName, userProfileProperties);
IEnumerable<string> profileProperties = peopleManager.GetUserProfilePropertiesFor(userProfilePropertiesForUser);
tenantContext.Load(userProfilePropertiesForUser);
tenantContext.ExecuteQuery();
foreach (string property in profileProperties)
{
items.Append(property);
items.Append(“,”);
}
items.AppendLine();
}
catch (Exception ex)
{
throw ex;
}

}

System.IO.File.WriteAllText(csvFilePath, items.ToString());
}
}
}
}

dO

 

Remarks: when you want to run this console in client machine where share point is not installed To run your Console Followe below step in your solution
– you have to change your dll property Name Copy To Local= True
-Change solution to Release mode and build solutions
-after that copy Release Folder and past in client machine after that run your Exe from that Folder

Hope its Help you

Thanks
SPS

0

Content Editor WebPart Slider using Adaptor Slider(CSOM)

Hi

Description:CEWP Slider using Adaptor Slider

Just Follow the step:

Create Index.html File and Copy past below code into this
you can download Adaptor JS File and Css From this Link
http://www.jqueryscript.net/demo/Adaptor-Cool-3D-jQuery-Content-Slider/

In My case i have Put all File in asset Library bcoz i have used sub site
you can put it in Item Style also but after that Change all reference of file in your html File accordingly

Ok now Goto your sp site and Edit webpart and give reference of your HTML File and Save it
your slider is ready to slide

<!DOCTYPE html>
<html>
<head>
<title>slider</title>
<script type=”text/javascript” src=”../SiteAssets/Adaptor-Cool-3D/jquery-1.7.2.min.js”></script>
<script type=”text/javascript” src=“../SiteAssets/Adaptor-Cool-3D/box-slider-all.jquery.min.js“></script>
<script type=”text/javascript” src=”../SiteAssets/Adaptor-Cool-3D/modernizr.min.js”></script>
<link href=”../SiteAssets/Adaptor-Cool-3D/screen.css” rel=”stylesheet”>

<script type=”text/javascript” >
ExecuteOrDelayUntilScriptLoaded(loadSlideImages, “sp.js”);
function loadSlideImages()
{
var clientContext=new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle(‘AdaptorImages‘);// Get List
var camlQuery = SP.CamlQuery.createAllItemsQuery();

this.frontPictureItems = oList.getItems(camlQuery);
clientContext.load(frontPictureItems, ‘Include(Id, DisplayName, FileLeafRef,EncodedAbsUrl)’);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
var carousel_html=””;
var listItemInfo = ”;
var listItemEnumerator = frontPictureItems.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var PicUrl=oListItem.get_item(“EncodedAbsUrl“);
carousel_html += “<figure class=’slide’><img src='”+PicUrl+”‘></img></figure>”;

}
$(‘#box’).html(carousel_html);
applyslider();
}
function applyslider() {

var $box = $(‘#box’)
, $indicators = $(‘.goto-slide’)
, $effects = $(‘.effect’)
, $timeIndicator = $(‘#time-indicator’)
, slideInterval = 5000;

var switchIndicator = function ($c, $n, currIndex, nextIndex) {
$timeIndicator.stop().css(‘width’, 0);
$indicators.removeClass(‘current’).eq(nextIndex).addClass(‘current’);
};

var startTimeIndicator = function () {
$timeIndicator.animate({width: ‘680px’}, slideInterval);
};
// initialize the plugin with the desired settings
$box.boxSlider({
speed: 1000
, autoScroll: true
, timeout: slideInterval
, next: ‘#next’
, prev: ‘#prev’
, pause: ‘#pause’
, effect: ‘scrollHorz3d’
, blindCount: 15
, onbefore: switchIndicator
, onafter: startTimeIndicator
});

startTimeIndicator();

// pagination isn’t built in simply because it’s easy to
// roll your own with the plugin API methods
$(‘#controls’).on(‘click’, ‘.goto-slide’, function (ev) {
$box.boxSlider(‘showSlide’, $(this).data(‘slideindex’));
ev.preventDefault();
});

$(‘#effect-list’).on(‘click’, ‘.effect’, function (ev) {
var $effect = $(this);

$box.boxSlider(‘option’, ‘effect’, $effect.data(‘fx’));
$effects.removeClass(‘current’);
$effect.addClass(‘current’);

switchIndicator(null, null, 0, 0);
ev.preventDefault();
});

}
function onQueryFailed(sender, args) {
alert(‘Request failed. ‘ + args.get_message() + ‘n’ + args.get_stackTrace());
}
</script>
</head>
<body>
<div id=”viewport” style=”position: relative; perspective: 1000px; overflow: visible; top: auto; left: auto; display: block; width: 680px; height: 460px;”>
     <div id=”box”>
     </div>
   </div>

</body>
</html>

THANKS SPS

0

How to Get web/site/List/ Tittle in CQWP.

Hi

Explain you here How to Get web/site/List/ Title in CQWP.

Once I got this requirement How to get Web Title or web title where Item is coming and Bind in CQWP

I have done lot`s of R&D For that but there no provision to get web Title or List Title Direct From ItemStyle.xml

It is Possible but How Let `s See

  • Open your .webpart File
  • Find “ViewFieldsOverride” Property
  • In this Property we have to override SharePoint default column like (created, Modified)+your view Column that you use to display in CQWP
  • But Best Practice is just Taking all Field and put it in to this in My Case I have use Task List
  • Now if you want to get Web Title then Define “<ProjectProperty Name=”Title” />”  ,This will return you web/Site Title
  • Same as if you want to get List Title <ListProperty Name=”Title” /> in same manner you can notice in below code
  • Remarks Must Define your FieldRef and Properties inside  <![CDATA[ ]]>  ok now save and upload your web part

<property name=”ViewFieldsOverride” type=”string”><![CDATA[
<FieldRef ID=”{fa564e0f-0c70-4ab9-b863-0177e6ddd247}” Nullable=”True” Type=”Text” />
<FieldRef ID=”{64cd368d-2f95-4bfc-a1f9-8d4324ecb007}” Nullable=”True” Type=”DateTime” />
<FieldRef ID=”{cd21b4c2-6841-4f9e-a23a-738a65f99889}” Nullable=”True” Type=”DateTime” />
<FieldRef ID=”{53101f38-dd2e-458c-b245-0c236cc13d1a}” Nullable=”True” Type=”User” />
<FieldRef ID=”{d2311440-1ed6-46ea-b46d-daa643dc3886}” Nullable=”True” Type=”Number” />
<FieldRef ID=”{7662cd2c-f069-4dba-9e35-082cf976e170}” Nullable=”True” Type=”Note” />
<FieldRef ID=”{c3a92d97-2b77-4a25-9698-3ab54874bc6f}” Nullable=”True” Type=”Lookup” />
<FieldRef ID=”{a8eb573e-9e11-481a-a8c9-1104a54b2fbd}” Nullable=”True” Type=”Choice” />
<FieldRef ID=”{c15b34c3-ce7d-490a-b133-3f4de8801b76}” Nullable=”True” Type=”Choice” />
<FieldRef ID=”{8c06beca-0777-48f7-91c7-6da68bc07b69}” Nullable=”True” Type=”DateTime” />
<FieldRef ID=”{1df5e554-ec7e-46a6-901d-d85a3881cb18}” Nullable=”True” Type=”User” />
<FieldRef ID=”{28cf69c5-fa48-462a-b5cd-27b6f9d2bd5f}” Nullable=”True” Type=”DateTime” />
<FieldRef ID=”{d31655d1-1d5b-4511-95a1-7a09e9b75bf2}” Nullable=”True” Type=”User” />
<FieldRef Name=”PublishingRollupImage” Nullable=”True” Type=”Image” />
<FieldRef Name=”_Level” Nullable=”True” Type=”Number” />
<FieldRef Name=”Comments” Nullable=”True” Type=”Note” />
<ListProperty Name=”Title” /><ProjectProperty Name=”Title” />
]]></property>

-Now open you ItemStyle.xml

you can access Project title  and List Title by

<xsl:value-of select=”ProjectProperty.Title”/>  //Get Web Title

<xsl:value-of select=”ListProperty.Title”/>   // Get List Tittle

Remark Once you modified your webpart ovverride List in  <ProjectProperty Name=”Title” />

in ItemStyle.xslt you will not Get absolute URL [&SiteUrl,$LinkUrl,$PageUrl]

you will get break url in these object so it is tuff to manipulate this URL and get Absolute URL

if you want to get URL For Item you can define <ProjectProperty Name=”Url” /> inside ViewFieldsOverride

now you can access url in Item Style <xsl:value-of select=”ProjectProperty.Url”/>

Hope you Get your issue Resolve from this

Thanks SPS

0

Create Site Column Programmatically in SharePoint

Hi

Today I am going to explain you How to create Site column Programmatically (xml)

It should be also created through OOTB and PowerShell

What is site column

Site column is pre define site column which are reused in various content type and List, Libraries

For e.g. you can create a site column “Sample” with a Single Line of text data type . This column then can be added to any content type in your list or library.

We can achieve it two ways

Using Declarative XML

code (Feature Activation Event Receiver)

In this blog we can achieve it through xml..

Ok let`s start

Continue reading

0

Modules to Include Files In Sharepoint (Basics)

Hi,

I am going To Explain you Basic Concept of module in share point this is just basic Example How Module is Work actually in sharepoint

Not Confused with Visual Code Module ,Basic use of module Just place File in your Sharepoint Server at specific Locations by Deploying your Solutions

ok Let`s Start the stuff Just Follow Below steps

1.Open Visual Studio and Create New Empty Solution Name (Module Test)

2.Now Open Your Solution Explorer and Right Click on IT

3 Go To add New Item add Module(Name -Module1)

4 Now you can Notice module is Add in your Solution Which Contain two Default File(Element.xml,Sample.txt)

5.Open your Element.xml you can notice Default code Like Below

<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”&gt;

<Module Name=”Module1″>

<File Path=”Module1\Sample.txt” Url=”Module1/Sample.txt” />

</Module>

</Elements>

6. Do not change any thing just Deploy solutions and check you sharepoint site Sample.txt File on placed at Module/Sample.txt

File Element has Following Attributes

Attribute Name Description
Path The name and location of the file in the SharePoint solution. The format is,Path=”Module1\Sample.txt”.
Url The location where the file will be deployed on the SharePoint server. The format is,Url=”Module1/Sample.txt”.
Type An optional attribute that has two settings: GhostableInLibrary and Ghostable. The format is,Type=”GhostableInLibrary”. Specifying GhostableInLibrary means the file will be added to a document library in SharePoint together with a list item to accompany the file when it is added to the library. Specifying Ghostable causes the file to be added to SharePoint outside the document library

This is just basic example for your Understanding  I will write more example of Module.Soon

Enjoy..!!!

Thanks

SPS

1

Rendering On Sharepoint TaskList Using JSLink( Client-Side Rendering in SharePoint 2013)

Hi,

Here i am giving you demo of JSlink(Client side Rendering) on SharePoint Task List

This is one of the cool feature of SharePoint and in this blog i go through ,what it is Actually

Summary: Add Task Status Indicators in Task List SharePoint 2013 using JS Link, Customize Status Field in Task list with JSLink

Continue reading

0

Display and slide picture From Picture Library in Content Editor webpart using CSOM in 2010/13

Hi,

Today,I am going to Explain you here How to Display and slide picture From Picture Library in Content Editor webpart using CSOM

this is simple task Just Follow below step you will get the output

  • Create Js File or txt File and copy past below code in your File (Explainationcode of  code Find with comment in code file)
  •  Uplode file in style Library(Recomended) or any Library
  • Create Picture Library or you can use asset Library as well and uplode some slider images.
  •  Go to Your SP site and add Content Editor web part..
  • Editwebpart and   link with your JS(provide full URL or path of your Js which you have uplode in Style Library)
  • Apply and Ok now your Images is Ready to Slides in CEWP Cheers!!!

Below is Code for your JS or txt File

<div style="position: relative" id="imgCntr" paddingLeft="5px" peddingRight="5px">

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<script type="text/javascript">

ExecuteOrDelayUntilScriptLoaded(loadSlideImages, "sp.js");
//Recommended to define this fun First 

function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = frontPictureItems.getEnumerator();
var listItems = '';
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItems += '<img src="http://sp:1000/student/iin/MySlider1/' + oListItem.get_displayName() + '.jpg" style="position:absolute" height="300px" width="900px"/>';
}

$('#imgCntr').html(listItems);
initSlider();
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + 'n' + args.get_stackTrace());
}

function initSlider() {
$('#imgCntr img:gt(0)').hide();
setInterval(function(){$('#imgCntr :first-child').fadeOut().next('img').fadeIn().end().appendTo('#imgCntr');}, 6000);
}

var siteUrl='http://sp:1000/student/iin';
//i have taken static URL here you can used Absolute URL as well

function loadSlideImages() {
var clientContext = new SP.ClientContext(siteUrl); 
var oList = clientContext.get_web().get_lists().getByTitle('MySlider');//get PicLibrary

var camlQuery = SP.CamlQuery.createAllItemsQuery();
//you can use caml syntax to get desire result i have Just take all field
   		
this.frontPictureItems = oList.getItems(camlQuery);
clientContext.load(frontPictureItems, 'Include(Id,DisplayName,FileLeafRef,FileDirRef)');
//load neccessary Field to load image

clientContext.executeQueryAsync(
 Function.createDelegate(this, this.onQuerySucceeded),
 Function.createDelegate(this, this.onQueryFailed));
}

</script>

now Run your site…. wow your CEWP Image slider is ready

Happy Coding

Thanks
SPS