How To: Decode user name from claims format in SharePoint 2013

Intro

After converting a SharePoint web application to Claims Authentication mode, it is often required to write some code to decode and extract the regular user name in the way of domain\username. This is due to the fact that calling  SPContext.Web.CurrentUser.LoginName will now return an encoded string.

E.g: “i:0#.w|mydomain\luis.carrazana”.

A great explanation about how claims are formatted and how to identify the different claim types is provided by my colleague Wictor Wilén here.

In this post I’ll share a method for getting the regular user name without having to manually parse the encoded claim identity, and leveraging SharePoint built-in API. Here, I’m extending an original solution provided by Tobias Zimmergren, in order to address an issue when using HttppContext instead of SPContext.

Context about my scenario

In my case, I was maintaining a custom ASP.NET solution, which was originally built on top of SharePoint 2010. The platform was being upgraded to SharePoint 2013, and the web application was migrated to use claims authentication. The custom ASP.NET components made heavy used of the current logged in user name, which in some cases was retrieved using SPContext.Web.CurrentUser.LoginName and in other cases using HttpContext.Current.Identity.User.Name.

Tobias Zimmergren posted a great solution for getting the user name by leveraging the SharePoint built-in functions. I leveraged this solution in my project, but I faced the following issue:

When HttpContext.Current.Identity.User.Name is used to get the current user name, the encoded formatted string doesn’t contain the claim’s identity identifier. In this case, the encoded claim format for the user name will be something like “0#.w|mydomain\luis.carrazana” instead of “i:0#.w|mydomain\luis.carrazana” (notice how the “i:” is missing from the string). For this reason, the SharePoint built-in function SPClaimProviderManager.IsEncodedClaim will not work as intended.

Please share your comments if you know the reason behind this behavior and a better solution to address it.

Solution

To completely address this scenario and support both SPContex and HttpContext, I updated Tobias’ solution and added  another condition in case IsEncodedClaim method doesn’t work as expected. I check if the user name contains the ‘|’ character, in which case the string is converted back to the proper claims format and then decoded.

See the code below with my updated version.

public string GetUserLoginNameFromClaim(string userLoginName)
{
 using (new SPMonitoredScope("GetUserLoginNameFromClaim method called for " + userLoginName))
 {
 try
 {
 SPClaimProviderManager spClaimProviderMgr = SPClaimProviderManager.Local;
 if (spClaimProviderMgr != null)
 {
 if (SPClaimProviderManager.IsEncodedClaim(userLoginName))
 {
 // return the normal domain/username without any claims identification data
 userLoginName = spClaimProviderMgr.ConvertClaimToIdentifier(userLoginName);
 }
 else if (userLoginName.IndexOf('|') > -1)
 {
 //This case will occur if the user name was obtained from calling HttpContext.Current.User.Identity.Name
 //In this case, the encoded claim format for the user name will be something like "0#.w|mydomain\luis.carrazana" instead of "i:0#.w|mydomain\luis.carrazana"

 //This line will convert to the proper claim format, so we can later decode it.
 userLoginName = spClaimProviderMgr.GetUserIdentifierEncodedClaim(userLoginName);

 // return the normal domain/username without any claims identification data
 userLoginName = spClaimProviderMgr.ConvertClaimToIdentifier(userLoginName);
 }
 }
 }
 catch (Exception ex)
 {
 //Log exception here
 }

 return userLoginName;
 }
}

Summary

When a SharePoint web application is converted to use claims authentication, the current user name is encoded. This articles showed some code to properly use the SharePoint built-in methods for decoding the user name. It also addressed the issue when HttpContext is used, and the encoded string doesn’t contain the identity identifier.

Reference

How Claims encoding works in SharePoint 2010 – Wictor Wiléen

Tip: Getting the normal domain username from the claims username in SharePoint 2013 – Tobias Zimmergren

SPClaimProviderManager.GetUserIdentifierEncodedClaim method – MSDN Reference

Programmatically converting login name to claim and vice versa – Waldek Mastykarz

 

Advertisements

How to enable the Developer Dashboard in SharePoint 2013

Intro

The SharePoint Developer Dashboard is a built-in tool that has been available since SharePoint 2010. It provides diagnostic information that can be used by developers and system administrators to identify and troubleshoot issues related to page components. It also makes it easier to identify performance issues and resource usage right from the current page, which is easier than analyzing raw data from the ULS logs.

This post provides some details about changes to the developer dashboard in SharePoint 2013 and a PowerShell script to enable and disable the dashboard.

Changes to Developer DashBoard in SharePoint 2013

  • In SP 2010, the Developer Dashboard was rendered as a control in the master page, and it only showed information about the current request. In SP 2013 it shows as a separate window and it shows information about all request since the dashboard was enabled
  • The dashboard depends on “Usage and Health Data Collection Service Application”. This service must have been created and it must be running, otherwise no data trace data will be displayed (see Wictor Wilén post below).
  • The dashboard can be enabled (On) and disabled (Off). See the PowerShell below for performing these two actions.
  • The following tags must be present in the master page:
<SharePoint:DeveloperDashboard runat="server" />
<SharePoint:DeveloperDashboardLauncher
    ID="DeveloperDashboardLauncher"
    ThemeKey="spcommon"
    TouchMode="true"
    TouchModeWidth="30"
    TouchModeHeight="30"
    TouchModePaddingLeft="7"
    TouchModePaddingTop="7"
    TouchModePaddingRight="7"
    TouchModePaddingBottom="7"
    NavigateUrl="#"
    OnClick="ToggleDeveloperDashboard();return false"
    OuterCssClass="ms-dd-button ms-qatbutton"
    runat="server"
    ImageUrl="/_layouts/15/images/spcommon.png"
    AlternateText="<%$Resources:wss,multipages_launchdevdashalt_text%>"
    ToolTip="<%$Resources:wss,multipages_launchdevdashalt_text%>"
    OffsetX="237"
    OffsetY="30"
    HoverOffsetX="219"
    HoverOffsetY="66"
    Height="16"
    Width="16" />

PowerShell Script

The following script can be used to enable or disable the developer dashboard in a SharePoint 2013 farm:

# Add SharePoint cmdlets reference 
Add-PSSnapin "Microsoft.SharePoint.Powershell" -ErrorAction SilentlyContinue

#Enable Dashboard
$contentSvc = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$devDahsboardSettings = $contentSvc.DeveloperDashboardSettings
$devDahsboardSettings.DisplayLevel = "On"
$devDahsboardSettings.Update()

#Disable Dashboard
$contentSvc = ([Microsoft.SharePoint.Administration.SPWebService]::ContentService)
$devDahsboardSettings =$contentSvc.DeveloperDashboardSettings
$devDahsboardSettings.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::Off
$devDahsboardSettings.Update()

Summary

The SharePoint developer dashboard is a great tool to identify and troubleshoot page issues. In addition to ULSViewer, the dashboard is a great addition to the developer toolset for assisting in fine tuning custom components and ensuring good performance.

Reference

Using the Developer DashBoard (MSDN)

Developer Dashboard in SharePoint 2013

SharePoint 2013: Developer Dashboard shows no data “issue” (Wictor Wilén)

 

Testing content database before migrating to SharePoint 2013

Introduction

One of the steps in the SharePoint 2013 migration process is to test the content databases to identify potential issues before migrating to the new 2013 schema. This article shows a PowerShell script to execute the validation and export the results to a CSV file. Special kudos to Joe Rodgers for the original algorithm. I modified the code a little bit to be able to pass the parameters and focus on one DB at the time.

Script

Param(
 [Parameter(Mandatory=$true)] [string]$DBName,
 [Parameter(Mandatory=$true)] [string]$WebAppUrl
)

# array to store the output
$results = @()

Test-SPContentDatabase -Name $DBName -WebApplication $WebAppUrl | % {
   # get the SPContentDatabaseTestResultObject
   $databaseTestResult = $_

   # create a hash table
   $props = @{}

   # add the database name to the output
   $props.Add("DatabaseName", $DBName) 

   # dynamically add all of the SPContentDatabaseTestResult properties to the output
   $_ | Get-Member -MemberType *Property | % { 
     $props.Add($_.Name, $databaseTestResult.($_.Name)) 
   } 

   # add the hashtable to the output array
   $results += New-Object PSObject -Property $props
}

# dump the output to csv
$results | Export-Csv $("Test-ContentDatabaseResults_{1}_{0}.csv" -f (Get-Date).ToString("yyyy-MM-dd_hhmmss"), $DBName) -NoTypeInformation

How to use the Script

  1. Copy the above code into a file a name it “TestDB.ps1
  2. Save the file to a local directory in the SharePOint Server i.e: “c:\temp”
  3. Open SharePoint Management Shell
  4. Navigate to the script location i.e: “PS> cd c:\temp”
  5. Execute the script with the two parameters. i.e: PS> TestDB.ps1 -DBName <NameOfDatabase> -WebAppUrl <UrlOfWebApp>
  6. On successful completion, a CSV file is generated containing the DB name and the time stamp in the title i.e: Test-ContentDatabaseResults_DBName_2016-07-05_025815.csv
  7. Repeat the steps for each content DB to be upgraded

Reference

Upgrade Content Databases to SharePoint 2013

Export Test-SPContentDatabase Results to a CSV File

 

Setup SharePoint 2013 Single Server Environment – Part 4: SQL Server setup

Intro

This series describes the details and required steps for setting up a SharePoint 2013 Single Server Environment. This is typically used by developers in order to write custom solutions without interfering with one another. This type of environment is also is good for evaluation, training and demonstration purposes.
The series contains 6 parts:
  1. Environment Details
  2. VM setup
  3. Windows Server 2012 setup
  4. SQL Server setup
  5. SharePoint Installation and Initial Configuration
  6. Post-Installation Steps

SQL Server setup

This article contains the required steps to properly setup the SQL Server environment to properly run a single server SharePoint 2013 environment.

Install SQL Server 2012 Features

As per the previous article in this series, we should have downloaded the SQL Server 2012 ISO installation file and added it to the VM as a Virtual Optical Drive by now.
  1. From the virtual drive containing SQL installation, Run SETUP.EXE
  2. Select at least the following Core Features:
    1. Database Engine Services
    2. Management Tools – Basic
    3. Management Tools – Complete
  3. Select additional features based on specific needs

Setup Max Degrees of parallelism

Update the following PowerShell script, specifying the appropriate server instance.

#### Set MDOP to 1
Import-Module "sqlps" -DisableNameChecking
$sql = "EXEC sys.sp_configure N'show advanced options', N'1' RECONFIGURE WITH OVERRIDE
GO
EXEC sys.sp_configure N'max degree of parallelism', N'1'
GO
RECONFIGURE WITH OVERRIDE
GO
EXEC sys.sp_configure N'show advanced options', N'0' RECONFIGURE WITH OVERRIDE
GO"
Invoke-Sqlcmd -Query $sql [-ServerInstance "SERVER\instance"]

Open a PowerShell console with administrator credentials and execute the above script.

Note: If you are unable to execute PowerShell commands on the server, you may need to change the execution policy. See this link for reference. 

Delegate Permissions

  1. Open SQL Management Studio
  2. Create SQL Login for sp_admin service account
  3. Assign server roles:
    1. dbcreator
    2. securityadmin

 

<< Windows Server 2012 Setup SharePoint Installation & Config..>>

 Reference

Using the Set-ExecutionPolicy Cmdlet in PowerShell

 

Setup SharePoint 2013 Single Server Environment – Part 3: Windows Server 2012 Setup

Intro

This series describes the details and required steps for setting up a SharePoint 2013 Single Server Environment. This is typically used by developers in order to write custom solutions without interfering with one another. This type of environment is also is good for evaluation, training and demonstration purposes.
The series contains 6 parts:
  1. Environment Details
  2. VM setup
  3. Windows Server 2012 setup
  4. SQL Server setup
  5. SharePoint Installation and Initial Configuration
  6. Post-Installation Steps

Windows 2012 Server setup

This article contains the required steps to properly setup Windows Server 2012 with the required features to run a single server SharePoint 2013 environment, which includes setting Active Directory and Domain Controller.

Windows Server 2012 Installation

As per the previous article in this series, we should have downloaded the Windows Server 2012 ISO installation file and added it to the VM as a Virtual Optical Drive by now. When the VM is started, the Windows installation will kick in automatically.

Configure Server Roles

After the Windows installation is complete, follow this steps to properly add the required server roles and features:
  1. Setting Computer Name and Network Settings
    1. From the Server DashBoard go to Local Server
    2. Change Computer Name and Restart
    3. After restart, select Ethernet > Properties > Internet Protocol Version 4
    4. Specify network settings such as:
      1. IP address: 192.168.100.10,
      2. Subnet mask: 255.255.255.0,
      3. Subnet Gateway: 192.168.100.1
  2. Adding Server Roles
    1. From the Server Manager DashBoard click Add Roles and Features
    2. Set Installation Type to Role-Based or Featured-Based installation
    3. Under Server Roles, select Active Directory Domain Services
    4. Accept popup with required features
    5. Leave everything else as default and click through the end of the wizard
  3. Promote Server to Domain Controller
    1. Go to Server Manager > AD DS
    2. There should be a warning message on top displaying “Configuration required for Active Directory …”. Click More…
    3. On All Server Task Details click “Promote this server to a domain…”
    4. Under Deployment Configuration, select “Add a new forest” and specify the domain name
    5. Enter Administrator password
    6. Leave everything else as default and click through the end of thee wizard
    7. Computer will be restarted at the end
  4. Add users to Domain Controller
    1. After restart, open Active Directory Users and Computers
    2. Under Users, add all required accounts (tick “User cannot change password” and “Password never expires” options):
      1. sp_admin
      2. sp_instal
    3. Add sp_admin to the local “Administrators” group
  5. Install .NET 3.5 Features as prerequisite for SQL Server features installation
    1. From Server Manager > DashBoard click “Add roles and features”
    2. From Features tab select “.Net Framework 3.5 Features”
    3. Click through the end of the wizard.

 

<< VM Setup SQL Server Setup >>

Setup SharePoint 2013 Single Server Environment – Part 2: VM Setup

Intro

This series describes the details and required steps for setting up a SharePoint 2013 Single Server Environment. This is typically used by developers in order to write custom solutions without interfering with one another. This type of environment is also is good for evaluation, training and demonstration purposes.

The series contains 6 parts:

  1. Environment Details
  2. VM setup
  3. Windows Server 2012 setup
  4. SQL Server setup
  5. SharePoint Installation and Initial Configuration
  6. Post-Installation Steps

VM setup

This article describes the steps to create a virtual machine using Virtual Box. It also assumes that a MSDN subscription is available in order to download the required software installation.

  1. Get the software installations from MSDN
    • Windows Server 2012 (64-bit)
    • SQL Server 2012
    • SharePoint 2013 Server
  2. Download and Install Virtual Box
  3. Create a new VM
  4. Assign the following parameters:
    • Type: Microsoft Windows
    • Version: Windows 2012 (64-bit)
    • Memory Size: 8192 MB
    • Hard Disk: Create a virtual hard disk now
    • File Size: 100 GB
    • Hard Disk File Type: VDI (VirtualBox Disk Image)
    • Storage on Physical Hard Disk: Dynamically Allocated
  5. After the VM is created, click Settings from the top menu and set the following from the left menu:
    1. Storage: Add the all the ISO installation files, starting by Windows Server 12
    2. System: Increase the number of processors to 2
    3. Network: On the Adapter 2 tab, select Bridge Adapter and use the current adapter from the host machine

 

<< Environment Details Windows Server 2012 Setup >>

Reference

VirtualBox Site

MSDN Subscriber Downloads

Setup SharePoint 2013 Single Server Environment – Part 1: Environment Details

Intro

This series describes the details and required steps for setting up a SharePoint 2013 Single Server Environment. This is typically used by developers in order to write custom solutions without interfering with one another. This type of environment is also is good for evaluation, training and demonstration purposes.
The series contains 6 parts:
  1. Environment Details
  2. VM setup
  3. Windows Server 2012 setup
  4. SQL Server setup
  5. SharePoint Installation and Initial Configuration
  6. Post-Installation Steps

Environment Details

This article contains the environment details, including hardware requirements, minimum recommended services, minimum software, an required service accounts.

Hardware Requirements

  • Processor: 4 cores, 64-bit
  • RAM: 10GB
  • Hard-Drive Space: 100GB

Minimum Recommended Services for Development Environment

  • App Management Service Application
  • Central Administration Website
  • Claims to Windows Token Service (C2WTW)
  • Distributed Cache Service
  • Microsoft SharePoint Foundation 2013 Site and Subscription Setting Service
  • Secure Store Service
  • User Profile Service Application (SP 2013 only)

Minimum Software

Optional Extra Software

  • Microsoft SharePoint Designer 2013
  • Google Chrome
  • Firefox
  • ULSViewer

Service Accounts

Account Purpose Requirements
SQL Service Account

sp_sql

Used to run SQL Server services:

  • MSSQLSERVER
  • SQLSERVERAGENT
  • Use either a Local System account or a domain user account.
SharePoint Setup Account

sp_admin

Used to run the following:

  • Setup
  • SharePoint Products Configuration Wizard
  • Domain user account.
  • Member of the Administrators group on each server on which Setup is run.
  • SQL Server login on the computer that runs SQL Server.
  • Member of the following SQL Server roles:
    securityadmin
    dbcreator
 Server farm account or database access account

sp_farm

Used to perform the following tasks:

  • Configure and manage the server farm.
  • Act as the application pool identity for the SharePoint Central Administration Web site.
  • Run the Microsoft SharePoint Foundation Workflow Timer Service.
  • Domain user account.
  • Additional permissions are automatically granted for the server farm account on Web servers and application servers that are joined to a server farm.
  • The server farm account is automatically added as a SQL Server login on the computer that runs SQL Server.
  • The account is added to the following SQL Server security roles:
    • dbcreator
    • securityadmin
    • db_owner for all SharePoint databases in the server farm

 

VM Setup >>

Reference

Install and Configure SharePoint 2013
Install SharePoint 2013 on a single server with SQL Server