Wednesday, May 29, 2013

How to Delete a Timer Job in SharePoint using PowerShell

But wait! why do we delete a Timer Job in SharePoint? Well, because:
  • Your custom timer job may be in stuck state
  • You may have orphaned Timer jobs (Timer job without "Server" from Timer job status page in Central Admin)
  • Your custom timer job may have created more than one instances (duplicate timer job)
In my case, a custom timer job deployed in our SharePoint 2013 environment had a bug and left two instances of the same timer job. so we wanted to delete that.

Delete a Custom Timer Job in SharePoint
There is no Central Admin UI to delete timer jobs in SharePoint. So, lets seek help from PowerShell to delete a timer job in SharePoint.
how to delete sharepoint timer job using powershell

How to Delete a Timer Job in SharePoint using PowerShell
  • Step 1: Obtain the GUID of your target timer job to delete
    Get-SPTimerJob | where { $_.name -like "YOUR-Timer-Job-Name" } | Format-Table  -autosize -Property LastRunTime,id,name,DisplayName,Status
  • Step 2: Get the timer job and delete
    Once you obtained the GUID of your timer job to delete, Run this PowerShell cmdlets:
    $Timerjob = Get-SPTimerJob -id <Timer Job's GUID>
    
    $Timerjob.Delete()
This PowerShell script removes the given SharePoint timer job!
Do not delete any OOTB timer job unless you are very sure what you are doing! If you delete any SharePoint's critical timer jobs, You'll end up re-provisioning SharePoint on the server again.

Lesson Learnt: Developers - Make sure your Feature deactivation module contains code to delete your custom timer job in SharePoint.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Get Form Field Values from DispForm.aspx, EditForm.aspx Pages in SharePoint

If you have a requirement to extract field values from Display Form or Edit Form pages in SharePoint lists, Use these jQuery scripts:

Get Form field value in Display Form (DispForm.aspx):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>

<script language="javascript" type="text/javascript">
 
  $(document).ready(function() {
     var fldValue = $('h3:contains("Last Name")').closest('td').next('td').text();
     alert(fldValue.trim());
   });

</script>

Get Form field value in Edit Form (EditForm.aspx):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
 
  $(document).ready(function() {
var fldValue = $("input[title*='Last Name']").val();
alert(fldValue.trim());
});

</script>

Use the control tags and attributes accordingly. E.g. For Drop-downs, Instead of "Input" You got to use "Select" tag. 
Use Firebug/IE developer tool to fetch the Tag/Title/ID attributes of required controls!


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, May 25, 2013

Set Outgoing E-Mail Settings for SharePoint Central Admin using PowerShell

Its a common task that every SharePoint administrator will have to perform is enabling SharePoint to send E-mails. Outgoing email settings can be configured within the Central Administration site by navigating to:
  • Central Administration >> System Settings 
  • Click on "Configure outgoing e-mail settings"
  • Provide Outbound SMTP Server, From and To Addresses, and the character set.
  • Click "OK" to save your changes.

Set Outgoing E-Mail Settings for SharePoint 2013 using PowerShell:
Here is the PowerShell script in SharePoint 2013 to configure outgoing email

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Define Outgoing E-mail settings 
$outboundServer = 'g1exchangehub.crescent.org'
$FromAddress = 'Teamsites@crescent.org'
$ReplyAddress = 'SharePointSupport@crescent.org'
$Charset = 65001

#Get Central Administrtion Web site 
$WebApp = Get-SPWebApplication -IncludeCentralAdministration | Where { $_.IsAdministrationWebApplication }

#Apply the Settings
$WebApp.UpdateMailSettings($outboundServer, $FromAddress, $ReplyAddress, $Charset)

This script sets outgoing email settings in SharePoint central Administration site.
Set Outgoing E-mail Settings with PowerShell 
PowerShell to Configure Outgoing Email Settings for SharePoint 2016: 
SharePoint 2016 introduces two more parameter to outgoing email settings: SMTP port and TLS Encryption. Here is the script to set outgoing email configurations for SharePoint 2016.
sharepoint 2016 configure outgoing email powershell

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Define Outgoing E-mail settings 
$outboundServer = "smtp.crescent.com"
$FromAddress = "Portal@Crescent.com"
$ReplyAddress = "Portal@Crescent.com"
$Charset = 65001
$TLSEncryption = $False
$SMTPport = 25
 
#Get Central Administrtion Web site 
$WebApp = Get-SPWebApplication -IncludeCentralAdministration | Where { $_.IsAdministrationWebApplication }
 
#Set outgoing Email settings
$WebApp.UpdateMailSettings($outboundServer, $FromAddress, $ReplyAddress, $Charset, $TLSEncryption, $SMTPport)

If you want set outgoing Email settings in MOSS 2007, Use:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$CentralAdmin = New-Object Microsoft.SharePoint.Administration.SPGlobalAdmin
$CentralAdmin.UpdateMailSettings($outboundServer, $FromAddress, $ReplyAddress, $Charset)

Setup outgoing Email for a particular web application:
Its also possible to set outbound Email settings per web application. But in Central Administration, outgoing email settings are set globally to the Farm but not per web application. Say for e.g, We need different From/To addresses for different departments in the organization. Say, IT@Company.com or IT departments and Sales@company.com for sales department.

This is where PowerShell comes to handy!We can set outbound Email settings per web application using PowerShell:
Get-SPWebApplication -Identity <web-app-url>
Set-SPWebApplication -OutgoingEmailAddress SharePointSupport@crescent.org -ReplyToEmailAddress SharePointSupport@crescent.org -SMTPServer emailserver.crescent.org

Its also possible to set outbound Email using STSADM command line. To setup outgoing Email for a particular web application:
stsadm -o email -outsmtpserver emailserver.crescent.org -fromaddress SharePointSupport@crescent.org -replytoaddress SharePointSupport@crescent.org -codepage 65001 -url http://server_name


To get outgoing email Server Settings using PowerShell:
At times, you may have to retrieve outgoing email settings using PowerShell, Say you want to send Email from the PowerShell script.
(Get-SPWebApplication -IncludeCentralAdministration | Where { $_.IsAdministrationWebApplication } ) | %{$_.outboundmailserviceinstance.server}

Technet Reference: Configure outgoing e-mail for SharePoint Server 2016

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Delete Folders, Sub-Folders from SharePoint Library Programmatically

I need to delete a Folder from SharePoint 2010 document library using object model programmatically. Here is the code to delete the sub-folder from SharePoint document library:

To Delete a Sub-folder from SharePoint Document Library Programmatically:
            String siteURL = "http://sharepoint.crescent.com/sites/sales"; 
            String listName = "Documents";
            String folderToDelete = "v2";

            using (SPSite site = new SPSite(siteURL))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPFolderCollection folders = web.Folders[listName].SubFolders;

                    foreach (SPFolder folder in folders)
                    {
                        if (folder.Name == folderToDelete)
                        {
                           web.Folders[listName].SubFolders.Delete(folder.Url);
                        }
                    }                    
                }
            }
PowerShell script to delete folder in SharePoint 2013:
The above code can be converted to PowerShell also, to delete folders programmatically: 

 Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

        $siteURL = "http://sharepoint.crescent.com/sites/sales"
        $listName = "Documents"
        $folderToDelete = "v2"
  
        #Get the Web
        $web = Get-SPWeb $siteURL  
  
        #Get all Sub folders
        $folders = $web.Folders[$listName].SubFolders

                    Foreach ($folder in $folders)
                    {
                        if ($folder.Name -match $folderToDelete)
                        {
                             $web.Folders[$listName].SubFolders.Delete($folder);
                             Write-Host "Folder has been deleted!"
                        }
                    }                    


If you want to Delete All Folders from a Library:
 

  Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
  $siteURL = "http://sharepoint.crescent.com/sites/sales"
  $listName = "Documents"
  
  #Get the Web
  $web = Get-SPWeb $siteURL  
  
  #Get the list
  $list = $web.lists[$listName]
  
  #Get all folders under the list
  $query =  New-Object Microsoft.SharePoint.SPQuery
  $camlQuery = '<Where><Eq><FieldRef Name="ContentType" /><Value Type="Text">Folder</Value></Eq></Where>'

  $query.Query = $camlQuery
  $query.ViewAttributes = "Scope='RecursiveAll'"
  $folders = $list.GetItems($query)

  for ($index = $folders.Count - 1; $index -ge 0; $index--)
  {
       Write-Host("Deleting folder: $($folders[$index].Name) at $($folders[$index].URL)")
       $folders.Delete($index);
  }
                

Related Post: Create Folders and Sub-Folders in SharePoint Programmatically

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Friday, May 24, 2013

PowerGUI Error: Microsoft SharePoint is not supported with version 4.0.30319.1 of the Microsoft .Net Runtime

PowerGUI is my favorite IDE for creating PowerShell scripts. When I upgraded PowerGUI to a newer version 3.5, all my scripts stopped working and I started receiving below error:

"Get-SPWeb : Microsoft SharePoint is not supported with version 4.0.30319.1 of the Microsoft .Net Runtime."
PowerGUI Error: Microsoft SharePoint is not supported with version 4.0.30319.1 of the Microsoft .Net Runtime
Root Cause:
SharePoint cmdlets do not work with .NET framework 4! In PowerGUI's configuration, We got to Remove that!

Solution:
Open the "ScriptEditor.exe.config" file from the location where PowerShell GUI is installed. Typically, "C:\Program Files (x86)\PowerGUI\".

Find the Line: " <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" /> " under "startup" node SharePoint PowerGUI Get-SPWeb Error
Comment that line, Save & Close.

Now, Restart the Script Editor. All should be working now.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, May 23, 2013

The default termstore for this site cannot be identified - Error on Creating Local Term Set Managed Metadata Column

When trying to create a Local term set by Selecting the option "Customize your term set:", Got the error message :
"The default termstore for this site cannot be identified"
 
Cause: 
This is because: Managed Metadata Service Application Service Application to set default storage location for Term Sets is not specified!

Solution:
Go to Central Administration >> Manage Service Applications >> Highlight your Managed Metadata Service Application >> Click on the Service Connection >> Properties icon in the ribbon >> Enable "This service application is the default storage location for column specific term sets." 
The default termstore for this site cannot be identified - Error on Creating Local Term Set Managed Metadata Column
This will fix the problem!



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, May 20, 2013

The web server process that was being debugged has been terminated by Internet Information Services (IIS)

While debugging a SharePoint object model code in Visual studio, Got this error message: "The web server process that was being debugged has been terminated by Internet Information Services (IIS). This can be avoided by configuring Application Pool ping settings in IIS.  See help for further details."
The web server process that was being debugged has been terminated by Internet Information Services (IIS)
Cause: 
IIS performs health monitoring by pinging worker processes to ensure they are up and running. IIS will terminate any worker process that does not respond to a ping request within the specified response time. So when the code execution is at a break-point in debugging mode and do not resume within the default response time of 90 seconds, IIS forcefully terminates the process and detach the debugger.

Fix:
To fix this error,  increase the Ping Maximum Response Time of the application pool in IIS. Following steps:
  • Go to Internet Information Services (IIS) Manager. (RUN >> InetMgr)
  • Expand the server tree , choose Application Pools.
  • Choose the Application Pool corresponding to your IIS website (usually it has the same name as your IIS website)
  • In Right side Property Pane choose Advanced Settings. (or right-click the name of the pool your application runs in, and then click Advanced Settings. )
  • Under the Process Model section, change "Ping Maximum Response Time (seconds)" to a higher value.
application pool Ping Maximum Response Time (seconds)
(E.g. I have set the value to 300 seconds which is 5 minutes). Alternatively, you can also set the Ping Enabled property to False.

Now, re-attach the W3WP process from Visual Studio, you should not get the error message!
Don't do this in Production environments! That will affect the performance!!


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sunday, May 19, 2013

Find the Number of Users Currently Connected to SharePoint Site

Had to perform an unplanned IIS Reset to fix an issue in production SharePoint Farm. But executing IISReset breaks ongoing user sessions and give "Service Unavailable" error message, isn't it? Wouldn't it be a good idea to find the No. of users currently connected with the SharePoint site and do the IISReset for a minimal impact? Sure!

How to find how many users connected with SharePoint sites? use Performance Monitor!
  • Go to Start >> Run >> Type "Perfmon", to fire up Performance Monitor.
  • Click on "Performance Monitor" , Right click "Add Counters" in Graph windowsharepoint how many users connected
  • Under the available Counters, Pick "Web Service" expand the node and select "Current Connections"
  • Under "Instances of Selected object" You can either select "Total" or pick a particular web applicationFind the number of users Currently Connected to SharePoint Site
  • Click on Add button to add the selected counter, and click "OK" button
Now the graph will show the how many users connected to your SharePoint Site(s).
sharepoint number of users connected
Please not, this gives only the no of user sessions currently ongoing. But not the one already completed (Doesn't count the users already opened the site and left it idle!) There are possibilities that users may hit the SharePoint URL meanwhile and receive "Service Unavailable" message since IIS is reset!

PowerShell to get current number of users connected:
We can also use PowerShell to get number of users connected:
$servername = "Cres-SPWFE01"
Get-Counter -Counter 'web service(_total)\current connections' -ComputerName $servername
This gets you the number of users connected with all web sites in the server.

Lets get number of users connected for a particular web site:
$servername = "Cres-SPWFE01, Cres-SPWFE02, Cres-SPWFE03"
$WebSiteName="Intranet Portal" #Web site name in IIS
Get-Counter -Counter "web service($WebSiteName)\current connections" -ComputerName $ServerNames


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Print SharePoint Listview Web Part using JavaScript

Requirement is to Print a SharePoint List view web part with JavaScript.

Solution: Found this code somewhere on the Technet Forums: Place this code in a CEWP, This will add a "Print" button, on clicking the button, Script fetches the list view web part, place it in a new window and sends to Print.

<INPUT type="button" onclick="javascript:void(printwebpart('WebPartWPQ2'))" value="Print"/>

<script type="text/javascript">
function printwebpart(webpartid)
{
var WebPartElementID = webpartid;
var bolWebPartFound = false;

if (document.getElementById != null)
   {
  //Create html to print in new window
  var PrintingHTML = '<html>\n<head>\n';

 //Take data from Head Tag

  if (document.getElementsByTagName != null)
  {
  var HeadData= document.getElementsByTagName("HEAD");

  if (HeadData.length > 0)
  PrintingHTML += HeadData[0].innerHTML;
  }

  PrintingHTML += '\n</HEAD>\n<BODY>\n';
 var WebPartData = document.getElementById(WebPartElementID);

 if (WebPartData != null)
 {
  PrintingHTML += WebPartData.innerHTML;
  bolWebPartFound = true;
 }
 else
 {
   bolWebPartFound = false; alert ('Cannot Find Web Part'); 
 } 
   } 
  PrintingHTML += '\n</BODY>\n</HTML>';
 
  //Open new window to print

  if (bolWebPartFound)
  {
   var PrintingWindow = window.open("","PrintWebPart", "toolbar,width=800,height=600,scrollbars,resizable,menubar");
   PrintingWindow.document.open();
   PrintingWindow.document.write(PrintingHTML);
   PrintingWindow.document.close();
   PrintingWindow.focus();

   // Open Print Window
   PrintingWindow.print();
   PrintingWindow.close();
  }

}

</script>  
Output:


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, May 18, 2013

Audience Targeting Missing in SharePoint 2010?

Audience Targeting feature in SharePoint 2010 targets content (pages, Web Parts, documents, list items and content) to audiences. Audiences may consists of SharePoint Groups, Security groups, distribution-lists or Global Audience groups which are compiled in Central Administration.

Audience targeting missing in SharePoint 2010?
Audience Targeting will not be enabled on lists & libraries by default! You must turn it ON by going to List Settings >> Audience Targeting Settings >> Enable audience targeting to turn audience targeting ON in SharePoint 2010.
sharepoint 2010 audience targeting

SharePoint 2010 audience targeting links not available?  
Audience targeting option missing in web part advance properties? Couldn't find Audience targeting in Top Navigation and Quick Launch Menus?

Here are the reasons & solutions for SharePoint 2010 audience targeting missing:

1. Enable audience targeting in SharePoint 2010 Site Collection
Go to Site Actions >> Site Setting >> Click on "Site collection navigation" >> under Site Collection Administration >> Make sure "Enable Audience targeting" is checked.

Audience Targeting Missing in SharePoint 2010
2. Audience Targeting feature is depending on SharePoint Publishing feature. So, Go to Site Settings >> Site collection features >> SharePoint Server Publishing Infrastructure” Activate publishing feature on your site collection.

3. For Audience Targeting, We need "User Profile Service Application"! So make sure the user profile service application is provisioned and running. Check the status of "User Profile Service" and "User Profile Synchronization Service" . Verify the UPSA is associated with your Web Application, by going to:
  • Central Administration >> Application Management 
  • Manage Web Applications >> Highlight Your Web Application 
  • Service Connections >> Make sure User Profile Service Application is checked.
Restart IIS!

This fixes the SharePoint 2010 web part audience targeting missing issue.

BTW, Global Audience groups compiled in Central Administration from Individual users, Distribution List members, or based on User's Active Directory Properties (such as Skills, Location, Department, etc).
sharepoint 2010 audience targeting central admin
In MOSS 2007, I had the similar issues long back, where the cause was: Shared Service Provider isn't created or associated with the particular web application.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, May 13, 2013

Set SharePoint Web Application Recycle Bin configuration Programmatically with PowerShell

In continuation to my article SharePoint Recycle bins - Lets get it crystal clear , There are situations to set SharePoint recycle bin options programmatically with either object model code (C#) or with PowerShell.

SharePoint 2010 powershell Script to Configure Recycle Bin:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the Web Application
$WebApp = Get-SpWebApplication "http://SharePoint.crescent.com"

#*** Set Recycle bin Options ***
#Enable Recycle bin
$WebApp.RecycleBinEnabled = $true

#Set Retention Period to 90 days
$WebApp.RecycleBinRetentionPeriod = 90 
#To Turnoff Recycle bin Retention, use: $WebApp.RecycleBinCleanUpEnabled=$false

#Set Second Stage Recycle bin Quota %
$WebApp.SecondStageRecycleBinQuota = 100
#To turn OFF Second Stage recycle bin, use: $WebApp.SecondStageRecycleBinQuota = 0

#Apply the changes
$WebApp.Update()

Write-Host "Recycle bin Settings Updated!"

SharePoint Recycle bin configuration with STSADM:
  • stsadm -o setproperty -pn Recycle-bin-enabled –pv {On | Off} -url <web-app-url>  
  • stsadm -o setproperty -pn Recycle-bin-cleanup-enabled –pv {On | Off} -url <web-app-url>
  • stsadm -o setproperty -pn Recycle-bin-retention-period –propertyvalue <Numeric value indicating the number of days> [-url] <URL>
  • stsadm -o setproperty -pn Second-stage-recycle-bin-quota -pv 60 -url <web-app-url>


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, May 11, 2013

Disable Delete List Option in SharePoint

What? We've a SharePoint list provisioned to store & retrieve custom application settings in a SharePoint site. Its critical to prevent this list from any accidental deletion, so we want to disable delete list option from list settings in SharePoint.

How? We can disable "Delete this list" link in SharePoint by setting the List or Library's AllowDeletion Property to "False". Once set, delete option will go hidden.
SharePoint list hide delete option
Disable delete in SharePoint list
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Get the web where the particular list lives
$web = Get-SPWeb "http://sharepoint.crescent.com/sites/operations"
#Get the list
$list = $web.Lists["AppConfig"]
#Make the list 
$list.AllowDeletion = $false
$list.Update()
Result: SharePoint delete list missing! sharepoint 2010 delete list missing
By this way, we stop users from deleting SharePoint lists. If you notice, in some of the SharePoint lists & libraries (E.g. "Farm Templates" library), "Delete this List" or "Delete this Document Library" links are missing by default to prevent delete option.

Revert the flag "AllowDeletion" to "True" programmatically, if you must delete a list that doesn't offer "Delete this list" link. Once this flag set to false, we can't delete it even programmatically! you will get "This list cannot be deleted." error if you try to delete it.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, May 9, 2013

SharePoint 2010 Create Permission Level Programmatically

While its relatively easy to Create permission levels in SharePoint 2010 UI, We had 2000+ site collections in a web applications and scripting/programmatic way to create permission level would be the best choice.

We wanted to do a SharePoint permission level customization by eliminating delete capability from contributor permission level. Lets copy the contributor permission and remove the "Delete" capability from it.

Copy Existing Permission level and change permission level Permissions:
          using (SPSite site = new SPSite("http://sharepoint.crescent.com"))
            {
                using (SPWeb web = site.OpenWeb())
                {

                            //Get the Contributor permission level
                            SPRoleDefinition roleDefContributor = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                            
                            //copy Contributor permission level
                            SPRoleDefinition roleDefContributorNoDelete = new SPRoleDefinition(roleDefContributor);

                            //Retain all permissions but Remove the DeleteItems rights from the  permission level (You can use: | to Add, & to remove all but the specified permission)
                            roleDefContributorNoDelete.BasePermissions ^= SPBasePermissions.DeleteListItems;

                            roleDefContributorNoDelete.Name = "Contributor without Delete";

                            roleDefContributorNoDelete.Description = "Contributor without Delete";

                            web.RoleDefinitions.Add(roleDefContributorNoDelete);

                    }

                }
For complete SharePoint 2010 permission levels and permissions definition, Refer this SharePoint 2010 permission levels matrix: http://office.microsoft.com/en-us/templates/sharepoint-server-2010-groups-and-permissions-reference-chart-TC101977256.aspx

Create permission level programmatically object model c#
Alternatively, you can create a permission level from the scratch. Here is how:
 using (SPSite site = new SPSite("http://sharepoint.crescent.com"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    //Get all Permission Levels
                    web.AllowUnsafeUpdates = true;
                    
                    //Create New Permission Level
                    SPRoleDefinition roleDef = new SPRoleDefinition();
                    
                    //Set the base Permissions for the Permission Level
                    roleDef.BasePermissions = SPBasePermissions.ViewListItems | SPBasePermissions.AddListItems | SPBasePermissions.EditListItems |  SPBasePermissions.OpenItems |  SPBasePermissions.ViewVersions | SPBasePermissions.ManagePersonalViews | SPBasePermissions.ViewFormPages |  SPBasePermissions.Open | SPBasePermissions.ViewPages | SPBasePermissions.CreateSSCSite | SPBasePermissions.BrowseDirectories | SPBasePermissions.BrowseUserInfo | SPBasePermissions.AddDelPrivateWebParts | SPBasePermissions.UpdatePersonalWebParts | SPBasePermissions.UseClientIntegration | SPBasePermissions.UseRemoteAPIs | SPBasePermissions.CreateAlerts | SPBasePermissions.EditMyUserInfo;

                    roleDef.Name = "Contribute without Delete";
                    roleDef.Description = "Contribute without Delete Permission Level";
                    
                    //Add the Permission Level
                    web.RoleDefinitions.Add(roleDef);

                    web.Update();

                   Console.ReadLine();    
                }
            }
This will add a permission level programmatically. To modify the permissions, you have to use the BasePermissions property (SPBasePermissions enumeration): http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spbasepermissions%28v=office.14%29.aspx


Add Permission Level in PowerShell code
In SharePoint 2010 create permission level programmatically using Powershell, here is the script:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the Target Site collection's Root web
$web = Get-SPWeb "http://sharepoint.crescent.com/sites/operations"

#Get Contributor Base Permission
#$Contributor = $Web.RoleDefinitions["Contribute"]
#write-host $Contributor.BasePermissions
#or you can use: [System.Enum]::GetNames("Microsoft.SharePoint.SPBasePermissions") to get all base permissions

#Create New Permission Level
$ContributeNoDelete =New-Object Microsoft.SharePoint.SPRoleDefinition
$ContributeNoDelete.Name="Contribute without Delete"
#permission level description
$ContributeNoDelete.Description="Contribute without Delete Permission Level"
#Set the Base Permissions 
$ContributeNoDelete.BasePermissions="ViewListItems, AddListItems, EditListItems,  OpenItems, ViewVersions, ManagePersonalViews, ViewFormPages, Open, ViewPages, CreateSSCSite, BrowseDirectories, BrowseUserInfo, AddDelPrivateWebParts, UpdatePersonalWebParts, UseClientIntegration, UseRemoteAPIs, CreateAlerts, EditMyUserInfo"

#Add the Permission Level
$web.RoleDefinitions.Add($ContributeNoDelete);
write-host "Permission level created successfully"

#Grant Permission Level Access to a SharePoint Group directly
$SPGroup = $web.SiteGroups["Operations Members"]

$RoleAssignment= new-object Microsoft.SharePoint.SPRoleAssignment($SPGroup)
#Get the permission levels to apply
$RoleDef = $web.Site.RootWeb.RoleDefinitions["Contribute without Delete"]
#Assign the groups to the permission level
$RoleAssignment.RoleDefinitionBindings.Add($RoleDef)
#Add to web 
$web.RoleAssignments.Add($RoleAssignment)

$web.Update()
Write-Host "Permission Level granted to the Group"

$web.Dispose()
This will create a SharePoint 2010 custom permission level"Contribute without Delete" and add permission level to group: "Operations Members" with the created permission level.

Similarly, To remove a permission level from an existing SharePoint group, the PowerShell code goes like:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the Target Site collections's Root web
$web = Get-SPWeb "http://sharepoint.crescent.com/sites/operations"

#Remove Permission Level From a SharePoint Group
#Get the SharePoint Group
$SPGroup = $web.SiteGroups["Operations Members"]

#Get the Role Assignment 
$RoleAssignment= $web.RoleAssignments.GetAssignmentByPrincipal($SPGroup)
#Remove the Role Definition
$RoleAssignment.RoleDefinitionBindings.Remove($web.RoleDefinitions["Contribute"])
$RoleAssignment.Update();

$web.Dispose()

SharePoint 2010 change permission level for group
sharepoint 2010 change permission level for a group

To Change Permissions of a existing Permission Level:
 using (SPSite site = new SPSite("http://sharepoint.crescent.com"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPRoleDefinition roleDef = web.RoleDefinitions["Contribute without Delete"];

                    //Update Permissions for the Role Definition
                    roleDef.BasePermissions = SPBasePermissions.AddListItems | SPBasePermissions.BrowseDirectories | SPBasePermissions.EditListItems | SPBasePermissions.Open | SPBasePermissions.OpenItems | SPBasePermissions.ViewListItems | SPBasePermissions.ViewFormPages | SPBasePermissions.ViewPages | SPBasePermissions.CancelCheckout | SPBasePermissions.DeleteListItems | SPBasePermissions.ApproveItems;

                      roleDef.Update()
                }
           }

Delete custom role definition (Permission Level) Programmatically:
If you want to remove an existing permission level, use this code:
using (SPSite site = new SPSite("http://sharepoint.crescent.com"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                   web.RoleDefinitions.Delete("Contribute without Delete");
                 
                   Console.ReadLine();    
                }
            }


SharePoint 2010 get permission levels
To check SharePoint permission level programmatically:
 using (SPSite site = new SPSite("http://sharepoint.crescent.com"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    //Get all Permission Levels
                    foreach (SPRoleDefinition role in web.RoleDefinitions)
                    {
                       Console.WriteLine(role.Name.ToString());
                    }

                   Console.ReadLine();    
                }
            }

Related Post: SharePoint 2010 Permission Levels - Explained


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, May 8, 2013

How to Create New Permission Level in SharePoint 2010

There are scenarios where requirements couldn't be fulfilled by OOTB permission levels. Here is one among them: User who has contribute permissions can add, edit, open, view and delete an item. What we want is to permit a user to add, edit, view but not delete an item. So, I needed to create a custom level permission to restrict a group of users from deleting items.

Create Permission Level by Copying existing Permission Level in SharePoint 2010
Lets take an existing permission level "Contribute",  Copy and remove the ability to "Delete Items" from it.
  1. Open your SharePoint site collection (Root Web) in browser as a site owner.
  2. Click on Site Actions >> Site Permissions 
  3. Click on Permission Levels from the Ribbon to open the Permissions page.
  4. Because we planned to copy Contribute permission level, click on it to open its detailed permissions.
    sharepoint 2010 permission levels
  5. Scroll to the end of this form and click Copy Permission Level. This gives you a new, unnamed form with the exact same permissions as Contribute.
    sharepoint 2010 copy permission level
  6. Enter a name for this new level; Lets name it as "Contribute Without Delete" , and a description: 
  7. In List Permissions Uncheck the "Delete items - Delete items from a list and documents from a document library"
    sharepoint 2010 change permission level
  8. Click OK to save and close.
sharepoint 2010 custom permission level
Now we've got the newly added Permission level Contribute without delete, we can assign this new permission level to users and group.


How to Create a Custom  Permission level from SharePoint UI from the scratch:
Instead of copying existing permission level, To create your own custom permission level from the scratch, follow these steps:
  1. Log on to your SharePoint site collection as a site owner on which you want to create the custom permission level
  2. Select Site Actions >> Site Permissions
  3. Click to Permission Levels button in the Manage section of the Ribbon.
  4. Click to Add Permission Level.
  5. Enter the Name and Description values.
  6. In the Permissions section, select the permissions to include in the new permission level.
  7. Click Create to create the new permission level.

Grant access to User or Group with the Permission Level
Follow these steps to Assign Permission Level to a User or Group:
  1. Open the site (top level site) as a site owner.
  2. Click Site Actions >> Site Permissions and click Grant Permissions on the Ribbon.
    sharepoint 2010 add permission level
  3. In the Grant Permission form that appears, enter the user account (or security group) in the users/Groups box, then select Grant Users Permissions Directly, and select Read - Can View
  4. Pages and List Items and Download Documents.
  5. Click OK to save and close.
Its a best practice to add users to SharePoint group instead directly granting them through permission levels. 


Assign Permission Level to a User on a List or Document Library: E.g. "Shared Documents"
So we've the custom permission level created and have to grant access to users and groups.
  1. Click on Shared Documents to open this library.
  2. Switch to the Library tab on the ribbon.
  3. Click on the Library Permissions button
  4. To Grant permission to a Library , we must break the inherited permissions and switch to unique permissions. Click Stop Inheriting Permissions, and then click OK to confirm.
  5. Click Grant Permissions.
  6. Enter the Users/Groups field, and click Check Names.
  7. Select the "Grant users permission directly" option, and select Contribute.
    sharepoint 2010 change permission level group
  8. Click OK to save and close. 
now users/groups have Contribute permissions to this document library and all its content.


SharePoint Check group/User permission level:
In SharePoint Server 2010, you can easily check the permission assigned to a user or group from within Site Settings. Access Site Setting from the root of the site collection and then open Site Permissions >>  from there you can pick the required group >> Select Settings >> View Group Permissions to see the applicable permissions for the currently selected group as shown in below screen.
sharepoint check group permission level


SharePoint 2010 change permission level for a group
To change permission level for an existing user or group follow these steps:
  • Open your SharePoint site. Go to: Site Actions > Site Permissions
  • Check the box next to the person or group you want to modify
  • Select the Edit User Permissions button
    sharepoint 2010 change permission level for a group
  • Choose any additional permission level for the selected group.
    sharepoint 2010 assign permission level to group
  • Click OK to save changes.
Related Links:


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, May 7, 2013

How to Add User to Farm Administrator Group in SharePoint 2010

By default, the account which was used (logged in) to install SharePoint becomes the SharePoint Farm Administrator. There are situations, where we need to add additional Farm Administrators to our SharePoint farm in order to delegate the tasks. Follow these three steps to add a farm administrator in SharePoint.
  1. Add user to Central Administration Farm Administrator Group
  2. Add user to Web Application Policy with FULL control
  3. Add user as a ShellAdmin for all SharePoint databases.

1. SharePoint 2010 add new user to farm administrator group from Central Administration:

To add farm administrator in SharePoint 2010, Navigate to Central Administration >> Security >> Manage the farm administrator group >> Add the user by clicking New >> Add Users
how to add sharepoint farm administrator
SharePoint Farm Administrators group by default consists of Local server administrators. So, You can see (BUILTIN\Administrators) group is already referenced in the Farm Administrators group in Central Administration.

Add user to SharePoint 2010 farm administrators group using PowerShell: 
Adding farm admin in SharePoint 2010 can be done in PowerShell also. Here is the PowerShell script to add new farm admin.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#User to Add
$UserID="domain\userID"

#Get Central Admin Web App
$CAWebApp = Get-SPWebApplication -IncludeCentralAdministration | where-object {$_.DisplayName -eq "SharePoint Central Administration v4"} 

#Get Central Admin site
$CAWeb = Get-SPweb($CAWebApp.Url) 
#Get Farm Administrators Group
$FarmAdminGroup = $CAWeb.SiteGroups["Farm Administrators"] 
#Add user to the Group
$FarmAdminGroup.AddUser($UserID,"",$UserID , "")
Write-Host "User: $($UserID) has been added to Farm Administrators Group!"
$CAWeb.Dispose()
    Create a new SharePoint farm administrator with STSADM command line:
    The Equallent STSADM command for the above:
    stsadm -o adduser -url <Central Admin URL> -userlogin "Global\FarmAdmin" -useremail "FarmAdmin@domain.com" -group "Farm Administrators" -username "Farm Administrator"


    2. Add user to Web Application Policy with FULL control

    Just adding user to SharePoint Farm administrators group will not serve the purpose. If users are only added to central administration farm administrators group (and below two steps are skipped!), they will get "Access denied" error when they try to invoke STSADM command.

    They will get: "The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered." Error if they try to use SharePoint PowerShell cmdlets.
    sharepoint farm administrator gets access denied
    So the solution is: To add a web application policy for SharePoint 2010 farm administrator account on the selected/all web application(s).  Follow SharePoint 2010 user policy for web application. We can also use PowerShell to create web application user policy which is explained in the provided link.

    Once granted FULL control via web application policy, SharePoint Farm administrators group gets full control as site collection administrator access to all site collections of a particular web application.


    3. Add user as a ShellAdmin for all SharePoint databases

    The next step is to grant "Shell Admin" Access to the user, via PowerShell.
    You must run this cmdlet from an existing Farm Administrator account's context, otherwise you'll get an error!
    Add-SPShellAdmin -UserName "domain\user' -database (Get-SPContentDatabase -Identity "SharePoint_Database_Name)

    This cmdlet grants Farm Administrators necessary SQL permissions and adds the account to a local server group WSS_ADMIN_WPG group in local windows server. We can verify the access by Log on to the SQL Server > SQL Server Management Studio > verify the new login created for the new user.
    sharepoint farm administrator sql permissions
    and the user is mapped to SharePoint databases and will add the user to SharePoint 2010 farm administrator SQL permissions: db_owner, public and SharePoint_Shell_Access Roles for all SharePoint databases in the server farm. This gives user permission to do things that require changes to the database.
    sharepoint farm administrator sql permissions

    SharePoint 2010: Add farm admin using PowerShell
    So, the complete Script to Add user to Farm Administrator Group in SharePoint,
    Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    
    #User to Add
    $UserID="domain\user
    
    #*** Add User to SharePoint 2010 Farm Administrator Group ***
    #Get Central Admin Web App
    $CAWebApp = Get-SPWebApplication -IncludeCentralAdministration | where-object {$_.DisplayName -eq "SharePoint Central Administration v4"} 
    #Get Central Admin site
    $CAWeb = Get-SPweb($CAWebApp.Url) 
    #Get Farm Administrators Group
    $FarmAdminGroup = $CAWeb.SiteGroups["Farm Administrators"] 
    #Add user to the Group
    $FarmAdminGroup.AddUser($UserID,"",$UserID , "")
    Write-Host "User: $($UserID) has been added to Farm Administrators Group!"
    $CAWeb.Dispose()
    
    #***Add user to Web App Policy ***
       Get-SPWebApplication | foreach-object {
                    $WebAppPolicy = $_.Policies.Add($UserID, $UserID)
                    $PolicyRole = $_.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullControl)
                    $WebAppPolicy.PolicyRoleBindings.Add($PolicyRole)
                    $_.Update()
        Write-Host "Added user to $($_.URL)"
                    } 
    
    #*** Grant Shell Admin Access *** 
    #Get All Content Databases and Add user into Shell Admin access
    Get-SPDatabase | Add-SPShellAdmin -Username $UserID
    
    Now the Members of this group can perform tasks from SharePoint Central Administration.
    If you planned to use this account as: Server Farm Account, then grant these server roles in SQL Server: dbcreator & securityadmin.

    To run Add-SPShellAdmin, Your account must have:
    • Security_Admin role on SQL Server instance
    • db_owner on the SharePoint content database
    • Member of Local administrator Group on SharePoint server
    Tail:
    • To get all Shell Administrators, use: Get-SPShellAdmin
    • To Remove a user from Shell Admin Group: Remove-SPShellAdmin -UserName "Domain\User"

    SharePoint 2010 find farm administrators using PowerShell
    You may want to check if SharePoint user is a farm administrator.To check SharePoint farm administrator below code can help:
    Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    
    #Get Central Admin Web App
    $CAWebApp = Get-SPWebApplication -IncludeCentralAdministration | where-object {$_.DisplayName -eq "SharePoint Central Administration v4"} 
    
    #Get Central Admin site
    $CAWeb = Get-SPweb($CAWebApp.Url) 
    
    $FarmAdminGroup = $CAWeb.SiteGroups["Farm Administrators"] 
      foreach ($Admin in $FarmAdminGroup.users) 
          { 
           write-host $Admin.LoginName
          }
    


    You might also like:
    SharePoint Usage Reports
    Usage reports, collaboration and audit for SharePoint.
    Document SharePoint Farm
    Automatically generate SharePoint documentation.
    *Sponsored


    Monday, May 6, 2013

    Sharepoint 2010 Farm Administrator Gets Access Denied

    Its a common misconception that SharePoint Farm Administrator will get access to all SharePoint sites in the farm automatically! Farm administrator get access denied error in SharePoint 2010 site collection when trying to browse.
    sharepoint 2010 farm administrator access denied
    Solution: Its a misconception that, Farm Administrator gets access to everything automatically!
    Farm Administrators gets control over SharePoint Central Administration, but not all sites. So, we have to explicitly grant access to required web applications to the Farm Administrator through web application user policies by navigating to:
    • Central Administration  >>
    • Security >>
    • Specify web application user policy >>
    sharepoint farm administrator permissions
    Add web application user policy in SharePoint 2010 with PowerShell 
    Above step can be automated for all web applications using PowerShell.  
    Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    
    #User to Add
    $UserID="Global\SPAdmin"
    
    #Add user to Web App user Policy
    
    #Get All Web Applications and Iterate through
       Get-SPWebApplication | foreach-object {
                    $WebAppPolicy = $_.Policies.Add($UserID, $UserID)
                    #Set Full Access 
                    $PolicyRole = $_.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullControl)
                    $WebAppPolicy.PolicyRoleBindings.Add($PolicyRole)
                    $_.Update()
      Write-Host "Added user to $($_.URL)"
                    } 


    You might also like:
    SharePoint Usage Reports
    Usage reports, collaboration and audit for SharePoint.
    Document SharePoint Farm
    Automatically generate SharePoint documentation.
    *Sponsored


    Wednesday, May 1, 2013

    SharePoint People Picker Showing Deleted Users? Remove with PowerShell

    Problem:
    Few consultants left the company after their contract is over. Their AD account was deleted, They are removed from SharePoint site collections even. But still, SharePoint People picker showing deleted users!

    Root cause:
    Because, People picker gets users NOT only from AD, But from "User Information List" of the site collection also, which is explained in one of my post: SharePoint People Picker Showing Deleted User Accounts from Active Directory and SharePoint Site

    Solution:
    We've to remove the users from hidden User Information list. For a quick fix, we can navigate to: http://your-sharepoint-site/_layouts/people.aspx?MembershipGroupID=0 and remove users from User Information List to fix this problem.

    But how about removing multiple users in bulk from all site collections? Well, I wrote an utility to remove users from User Information List in C# SharePoint Object Model  Delete Users and Clean up User Information List

    This time, Lets do it with PowerShell.

    PowerShell Script to fix SharePoint People Picker Showing Deleted Users:
    Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    
    #Define the Array with List of Users
    $Users =@('ME\JamieT', 'Corp\EinstinS', 'Global\MarcM')
    
    #Get all Site Collections
    $SiteColl = Get-SPWebApplication "http://sharepoint.crescent.com" | Get-SPSite -Limit All
    
    #Iterate through all Site Collections
    foreach($site in $SiteColl)
    {
     #Iterate through the users to Remove
     foreach($user in $Users)
     {
       #Check if User Exists in Site
       if ($Site.RootWeb.SiteUsers | Where {$_.LoginName -eq $User})
       {
          $Site.RootWeb.SiteUsers.Remove($User)  #You can also use: Remove-SPUser cmdlet
       Write-Host "$($user) has been Removed from $($Site.RootWeb.URL)"
       }
      }
     
    }


    You might also like:
    SharePoint Usage Reports
    Usage reports, collaboration and audit for SharePoint.
    Document SharePoint Farm
    Automatically generate SharePoint documentation.
    *Sponsored


    SharePoint Sign in as Different User - How to Clear Cached Password?

    There is a weird issue when SharePoint users try to sign in as different user. Here is the scenario:
    1. User "A" logged in with his account in his PC.
    2. User "B" wants to login on SharePoint 2010 site with his credentials on user "A" machine by selecting "Sign in as Different User"
    3. User "B" will successfully logged in. Once user "B" sign out and user "A" opens the IE browser, he will still see SharePoint uses user "B" credentials and automatically logged with User "B" Login details, even if he tries to close all browsers and re-open same issue, unless we have to re-login again by Signing in with Different User i.e. user "A"
    sharepoint sign in as different user problem
    They tried clearing the saved passwords from Browser by: Going to Internet Explorer >> Tools menu  >> Internet Options >> General >> Delete >> Select "Passwords" and clicking OK. But no luck!

    Root Cause: This is due to saved/cached credentials! Go to Control Panel >> User Accounts >> Manage Your Credential and remove any credentials stored user name and password.

    Here is the solution to fix this permanently:
    • Go to Start >> Administrative Tools
    • Local Security Policy >> Local Policies >> Security Option 
    • "Interactive logon: Number of previous logons to cache (in case domain controller is not available)" >> Change it to 0. (It is set to "10" by default).sharepoint 2010 sign in as different user not working
    Ideally we have to make this change in AD group policies! But I've made this change in Client machine for the immediate effect. This fix also resolves the issue: sign in as different user not switching user! it just refreshes the user credentials.

    Disadvantage: Once you disable caching, You must be connected to the network, in order to login to your PC. Or you must have a local administrator account created already. (Since we disabled password caching, your computer will try to authenticate your account from domain controller directly!)

    Don't want User to be logged in Automatically?
    If you don't want a particular account to be logged in by default, Remove the stored credentials from "Credential Manager". Go to:
    • Control Panel >> Credential Manager 
    • Locate the Domain and Account and Remove from Vault.
    Another factor impacting this behavior is: Browser Setting. Go to IE >> Tools >> Internet Options >> Security >> Custom Level >> Change it to " Prompt for User name and Password."

    It could be because of cookies if your environment uses publishing servers such as TMG. Try clearing browser cache including cookies!

    You might also like:
    SharePoint Usage Reports
    Usage reports, collaboration and audit for SharePoint.
    Document SharePoint Farm
    Automatically generate SharePoint documentation.
    *Sponsored


    You might also like:

    Related Posts Plugin for WordPress, Blogger...