Wednesday, July 17, 2013

You see an HTTP 401 - Access Denied error when you try to access high trust app from SharePoint. This happens because multiple issuer Ids have been registered.

Please follow the below steps:
Check if any previously registered SPTrustedSecurityTokenIssuer is there. If mal-functioned one is there and if –IsTrustBroker switch was used, means the bad token issuer might be getting called. If this is the first time you are configuring high trust app then you can skip (a and b).
a. Run Get-SPTrustedSecurityTokenIssuer. If no Azure workflow is configured this command should return empty. If you get any issuer apart from
workflow one, run below script to delete it.
b. Remove- SPTrustedSecurityTokenIssuer (pass Id value from above output)Create new SPTrustedSecurityTokenIssuer, by running below script, passing
your SharePoint Developer SiteUrl and Cert path (.cer) that you will use to sign the token (you need to create a self signed cert).



For more info see http://msdn.microsoft.com/en-us/library/fp179901.aspx

Take a note of the $issuerId = "447f40c6-99df-4d37-9739-5370102489f7" in below, we will be using it later.
param
(
[Parameter(Mandatory=$true)]
[string] $TargetSiteUrl, [Parameter(Mandatory=$true)][string]
$CertPath = $(throw "Usage: ConfigureS2SApp.ps1 <TargetSiteUrl> <Certificate>")
)
# On error, stop
$ErrorActionPreference = "Stop"
# Add SharePoint snap in
add-PSSnapin Microsoft.SharePoint.PowerShell
function ConfigureS2SApp([string]$TargetSiteUrl, [string]$CertPath)
{
write-host "Configuring with parameters $appTitle , $TargetSiteUrl , $CertPath"
write-host "you passed"
$TargetSiteUrl $CertPath -foregroundcolor Green $issuerId = "447f40c6-99df-4d37-9739-5370102489f7"
$spweb = Get-SPWeb $TargetSiteUrl
$realm = Get-SPAuthenticationRealm -ServiceContext $spweb.Site
$fullAppIdentifier = $issuerId + '@' + $realm
$certificate = Get-PfxCertificate $CertPath
New-SPTrustedSecurityTokenIssuer -Name $issuerId -Certificate $certificate -RegisteredIssuerName $fullAppIdentifier –IsTrustBroker
# turning off https <optional> will make our SharePoint site run on http and still work with high trust app.
$serviceConfig = Get-SPSecurityTokenServiceConfig
$serviceConfig.AllowOAuthOverHttp = $true
$serviceConfig.Update()
}
# ConfigureS2SApp

$TargetSiteUrl $CertPath #Done
Write-host "S2S is now configured" -foregroundcolor Green
  • Create an App using VS2012 (provider hosted).
  • In Second screen, use same cert that you used the in step 2 (this time its .pfx file path).
  • Issuer ID in VS will be the value that we supplied in PS in Step 2 in this sample its "447f40c6-99df-4d37-9739-5370102489f7"
  • Open Web.Config of the AppWeb and generate a guid for the ClientId.

    The <appSettings> of the web.config looks like below

    <appSettings>
<add key="ClientId" value="6534b629-f722-4207-9d7b-4673646c3ab1" />
<add key="ClientSigningCertificatePath" value="C:\SP15\MasterReference\SimpleHighTrust\S2SCert.pfx" />
<add key="ClientSigningCertificatePassword" value="password" />
<add key="IssuerId" value="447f40c6-99df-4d37-9739-5370102489f7" />
</appSettings>
Open AppManifest in code mode and paste the above ClientId. it should look like below:
<AppPrincipal>
<RemoteWebApplication ClientId="6534b629-f722-4207-9d7b-4673646c3ab1" />
</AppPrincipal>
  • Give appropriate permission in the AppManifest. For VS template generated provider hosted app code, give Web Read permission.
  • Create an IIS site, make sure .Net 4.0 is the target framework.
  • Enable https on this IIS site and also enable Windows Authentication and Disable Anonymous Access.
  • You can use same cert for https, but if its on a separate IIS, make sure you copy certificates.
  • Compile and publish the app, you will be prompted like below:
Where is your website hosted? – This will be the url of the site where you want to host the appweb. In our sample it’s the IIS site that we created in the
previous steps (if this is on a separate IIS server, give that url). Also note that it has to be Https, OAuth requires https.
Client ID -6534b629-f722-4207-9d7b-4673646c3ab1
Cert location = location of cert (.pfx file)
Cert password = password of the cert
IssuerId = "447f40c6-99df-4d37-9739-5370102489f7"
9. This will generate app.publish folder in project\bin\debug. You will see .app file and AppWeb.Web.zip folder (this is what we want to run on a separate IIS site)
  • Drill down the AppWeb.Web.zip folder and copy all the content of PackageTmp in the virtual directory of the IISSite.
  • Go to SharePoint PowerShell and Register our appprincipal by using below script
$clientId = "6534b629-f722-4207-9d7b-4673646c3ab1"
$spweb = Get-SPWeb "http://mspx2013"
$realm = Get-SPAuthenticationRealm -ServiceContext $spweb.Site
$fullAppIdentifier = $clientId + '@' + $realm
$appPrincipal = Register-SPAppPrincipal -NameIdentifier $fullAppIdentifier -Site $spweb -DisplayName "SimpleHTApp"
Set-SPAppPrincipalPermission -Site $spweb -AppPrincipal $appPrincipal -Scope Site -Right FullControl
  • Go to SharePoint Developer Site, Click “new app to deploy”, Click upload, and browse to the .app file in app.publish folder.
13. Consent to the perm prompt the app requests.

14. Click the app, this will redirect to the separate IIS site where our app is configured, and you should see the Title of the HostWeb (your SharePoint Developer Site). 

SharePoint 2013 - 'Sorry, Apps are turned off' error


You configure the App Management Service in the farm but while trying to add any app you receive the following error
Sorry, apps are turned off. If you know who runs the server, tell them to enable apps.



Cause

The server was running out of memory. 

Resolution

  1. We tried to add an app using a non-system account, however we received the following error:

  2. Sorry, apps are turned off. If you know who runs the server, tell them to enable apps.

  3. We tried to browse SharePoint Central Admin - Apps - Configure App URL's and got below error: Sorry, something went wrong Settings or services required to complete this request are not currently available. Try this operation again later. If the problem persists, contact your administrator.
    Technical Details

    Troubleshoot issues with Microsoft SharePoint Foundation.
    Correlation ID: 6379209c-5068-40f4-5407-6ef37b5fe7a3
    Date and Time: [Date and Time]
    --------------------------------------------------------------------------------
    Go back to site
  4. Tried to browse to http://localhost:32843/3149c16fb70b4ced8e10c0c28e334a3d/subscriptionsettings.svc and http://localhost:32843/97d4210c929e443a9c69e8cd49012a51/AppMng.svc but got the below error: Server Error in '/3149c16fb70b4ced8e10c0c28e334a3d' Application.
    --------------------------------------------------------------------------------
    Memory gates checking failed because the free memory (144322560 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    Exception Details: System.InsufficientMemoryException: Memory gates checking failed because the free memory (144322560 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.
    Source Error:
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
    Stack Trace:
    [InsufficientMemoryException: Memory gates checking failed because the free memory (144322560 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.]
    System.ServiceModel.Activation.ServiceMemoryGates.Check(Int32 minFreeMemoryPercentage, Boolean throwOnLowMemory, UInt64& availableMemoryBytes) +121924
    System.ServiceModel.HostingManager.CheckMemoryCloseIdleServices(EventTraceActivity eventTraceActivity) +86
    System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +883
    [ServiceActivationException: The service '/3149c16fb70b4ced8e10c0c28e334a3d/subscriptionsettings.svc' cannot be activated due to an exception during compilation. The exception message is: Memory gates checking failed because the free memory (144322560 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element..]
    System.Runtime.AsyncResult.End(IAsyncResult result) +650220
    System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +210733
    System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) +166
    --------------------------------------------------------------------------------
    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18044
  5. Opened Task Manager and found the server was consuming complete memory on the box.
  6. We can follow below steps to resolve the issue:
  7. a. Perform IISRESET so that it will release the memory. This is only a short-term solution
    b. Increase memory on the SharePoint servers as a long-term solution

SharePoint 2013 - Emails triggered from Workflows fail with HTTP 500


Symptoms

Consider the following scenario:
In an environment with SharePoint 2013 and Workflow Manager 1.0, we create a simple list, and using SharePoint Designer 2013, create a workflow with one action; "Send email to a User". We trigger the workflow on a list item in SharePoint as a non-system account (we cannot trigger it using 'system account').
In this scenario, the workflow goes to 'Cancelled' state on the item. The error in the popup window and in the [WFInstanceManagementDB].[dbo].[Instances] table looks like below:
RequestorId: 13e3b6bd-c114-58ae-4436-1a2bcd6a57d8. Details: System.ApplicationException: HTTP 500 {"Transfer-Encoding":["chunked"],"X-SharePointHealthScore":["0"],"SPClientServiceRequestDuration":["10"],"SPRequestGuid":["13e3b6bd-c114-58ae-4436-1a2bcd6a57d8"],"request-id":["13e3b6bd-c114-58ae-4436-1a2bcd6a57d8"],"X-FRAME-OPTIONS":["SAMEORIGIN"],"MicrosoftSharePointTeamServices":["15.0.0.4420"],"X-Content-Type-Options":["nosniff"],"X-MS-InvokeApp":["1; RequireReadOnly"],"Cache-Control":["max-age=0, private"],"Date":["Day, Time"],"Server":["Microsoft-IIS\/7.5"],"X-AspNet-Version":["4.0.30319"],"X-Powered-By":["ASP.NET"]}
at Microsoft.Activities.Hosting.Runtime.Subroutine.SubroutineChild.Execute(CodeActivityContext context)
at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)


Cause

- We grab the SPRequestGuid from the error for the workflow : "SPRequestGuid":["13e3b6bd-c114-58ae-4436-1a2bcd6a57d8"],"
- This is the correlation ID we need to look for in SharePoint ULS logs. And we saw below entries:

[Date and Time] w3wp.exe (0x1A6C) 0x15E8 SharePoint Foundation CSOM ahjq1 High Exception occured in scope Microsoft.SharePoint.Utilities.SPUtility.SendEmail. Exception=System.Net.Mail.SmtpException: Error in processing. The server response was: 4.7.0 Temporary server error. Please try again later. PRX2 at System.Net.Mail.DataStopCommand.CheckResponse(SmtpStatusCode statusCode, String serverResponse) at System.Net.Mail.DataStopCommand.Send(SmtpConnection conn) at System.Net.Mail.SmtpClient.Send(MailMessage message) at Microsoft.SharePoint.Utilities.SPUtility.SendEmail_Client(EmailProperties properties) at Microsoft.SharePoint.ServerStub.Utilities.SPUtilityServerStub.InvokeStaticMethod(String methodName, ClientValueCollection xmlargs, ProxyContext proxyContext, Boolean& isVoid) at Microsoft.SharePoint.Client.ServerStub.InvokeStaticMethodWithMonitoredScope(String methodName, ClientValueCollection args, ProxyContext proxyContext, Boolean& isVoid) 13e3b6bd-c114-58ae-4436-1a2bcd6a57d8

[Date and Time] w3wp.exe (0x1A6C) 0x15E8 SharePoint Foundation CSOM agmjp High Original error: System.Net.Mail.SmtpException: Error in processing. The server response was: 4.7.0 Temporary server error. Please try again later. PRX2 at System.Net.Mail.DataStopCommand.CheckResponse(SmtpStatusCode statusCode, String serverResponse) at System.Net.Mail.DataStopCommand.Send(SmtpConnection conn) at System.Net.Mail.SmtpClient.Send(MailMessage message) at Microsoft.SharePoint.Utilities.SPUtility.SendEmail_Client(EmailProperties properties) at Microsoft.SharePoint.ServerStub.Utilities.SPUtilityServerStub.InvokeStaticMethod(String methodName, ClientValueCollection xmlargs, ProxyContext proxyContext, Boolean& isVoid) at Microsoft.SharePoint.Client.ServerStub.InvokeStaticMethodWithMonitoredScope(String methodName, ClientValueCollection args, ProxyContext proxyContext, Boolean& isVoid) 13e3b6bd-c114-58ae-4436-1a2bcd6a57d8
[Date and Time] w3wp.exe (0x1A6C) 0x15E8 SharePoint Portal Server Microfeeds aizmo Medium SocialRESTExceptionProcessingHandler.DoServerExceptionProcessing - SharePoint Server Exception [System.Net.Mail.SmtpException: Error in processing. The server response was: 4.7.0 Temporary server error. Please try again later. PRX2 at System.Net.Mail.DataStopCommand.CheckResponse(SmtpStatusCode statusCode, String serverResponse) at System.Net.Mail.DataStopCommand.Send(SmtpConnection conn) at System.Net.Mail.SmtpClient.Send(MailMessage message) at Microsoft.SharePoint.Utilities.SPUtility.SendEmail_Client(EmailProperties properties) at Microsoft.SharePoint.ServerStub.Utilities.SPUtilityServerStub.InvokeStaticMethod(String methodName, ClientValueCollection xmlargs, ProxyContext proxyContext, Boolean& isVoid) at Microsoft.SharePoint.Client.ServerStub.InvokeStaticMethodWithMonitoredScope(String methodName, ClientValueCollection args, ProxyContext proxyContext, Boolean& isVoid)] 13e3b6bd-c114-58ae-4436-1a2bcd6a57d8

- From the stack it looks like a communication error with the Outgoing SMTP server.


Resolution

Verify the following settings:

- We made sure the Outgoing Email settings for the farm are set correctly.
- We made sure that from the SharePoint server - we are able to telnet the Exchange server on port 25 and there is a positive response status for EHLO request.
- We disabled firewall on the Exchange/SMTP server.
- We also ensured App management service is running, UPA is set up and we have completed sync such that the user running the workflow has a profile.

How to Promote a 2013 SharePoint Task List to be Managed in PWA 2013


Summary
Project Server 2013 has the ability to import a SharePoint Task List into the Project Server database for reporting purposes. The data will reside in the Reporting schema of the ProjectWebApp 2013 database. However, the SharePoint Task List is still edited on the site's Tasks list where it was created. 

Once the SharePoint Tasks list is imported into PWA,  the site will gain some additional Project Web App (PWA) features.  The list of features available for a SharePoint Tasks List are listed below:

•The SharePoint Project Site is the master for editing the task list.  
The Tasks list can be opened from the site into Project Professional 2013 in order to use Project's scheduling engine to calculate the project, for example, duration, dates and work.  The plan is then synchronized back to the Tasks list on the SharePoint Project Site.  
If changes are made to the SharePoint Tasks List while the list is also open in Project Professional, a conflict management dialog will help to resolve differences from the stand point of the SharePoint Tasks List being the master.Some scheduling engine features are not available, such as resources not authorized by SharePoint and cross-linked projects.
•A Project Details page is added to the SharePoint Project Site.
◦This page contains basic plan info such as Name, Description, Start Date, Finish Date and Owner
◦Enterprise custom fields can be created and marked for use with SharePoint Tasks Lists which then display on the Project Details page.
•Issues, Risks and Deliverables web pages are added to the Project Site for tracking these items related to this specific Tasks list.
To add a SharePoint Tasks List to a ProjectWebApp 2013 database for reporting, it is assumed that your site collection already has the Project Server 2013 service activated and at least a Project Center web part added.  For information on how accomplish these steps to enable the Project Web App features in an existing site collection see the following article: http://technet.microsoft.com/en-us/library/jj200305.aspx . Once the PWA features are activated follow the steps below to Add SharePoint Sites to the ProjctWebApp database.

1.Navigate to the Project Center page in your site collection as the Administrator
2.Click the Projects ribbon tab
3.In the Project section click on Add SharePoint Sites.  A dialog will display with a list of the Project Sites within the site collection that are available for import.
4.Select the SharePoint Site you wish to import.  You can choose to change the Project Name. Also select the Tasks list you wish to import from the dropdown menu.  Note: A Project Site can contain multiple Tasks lists, but only one can be imported per site.
5.Click Add
A queue job is submitted for each SharePoint Site that is imported. Once the queue job is complete the plan will show up in the Project Center page.

A SharePoint Tasks List plan that has been imported into PWA, can be promoted to an Enterprise plan, see More Information for details.

To promote a SharePoint Task List plan to use the full Enterprise management features, follow these steps:

1.Log into PWA as the administrator.
2.Click the gear in the upper right and click PWA Settings
3.Under Operational Policies click on Connected SharePoint Sites
4.Click the Activate button to the right of the project name you wish to promote.
5.The following message will display "This will set the tasks list in the project site to read only and allow project edits from Project Web App. Are you sure you want to change the project mode?"  Click OK.
To demote a plan from Enterprise management style to SharePoint Tasks List style follow these steps:

1.Log into PWA as the administrator.
2.Click the gear in the upper right and click PWA Settings
3.Under Operational Policies click on Connected SharePoint Sites
4.Click the Deactivate button to the right of the project name you wish to promote
5.The following message will display " This will disable the enterprise project features for project <ProjectName> and the SharePoint Tasks List will be enabled for editing. Are you sure you want to do this?" Click OK.
More Information
There are now two project management styles available when the Project Server 2013 service is deployed in your SharePoint 2013 farm.  They are called: 

•SharePoint Tasks List management style 
•Enterprise management style 
Listed above are the characteristics of a plan managed in the SharePoint Tasks List style once the PWA features have been activated.  A plan that is of the Enterprise management style will have the full set of PWA features available for scheduling plans and tracking progress as well as reporting.  In order to enable the enterprise management style you must have a PWA site provisioned within your site collection, not just the PWA features activated as with the SharePoint Tasks List style.  To install and configure a PWA site see the following article: http://technet.microsoft.com/en-us/library/ee662109.aspx . Below are just a few basic PWA features available for enterprise managed projects, this list will help you to distinguish between the two management styles.

•The plan is editable in the PWA Scheduled web part.  The plan can also be opened in Project Professional for editing and synchronized back to the ProjectWebApp database using the full functionality of Project's scheduling engine, no limitations.
•A Project Site Tasks list connected to an Enterprise plan displays a yellow warning bar with the following message "This project can only be edited through Project Web App. Edit Project".  Edit Project is a live link that will take you back to the PWA Scheduled web part for editing.
•Timesheets can be used to update enterprise managed plans
•Any plan created from Project Professional connected to the server will be an enterprise managed project regardless of the EPT (enterprise project type) template used. The default template used with in Project Professional is set in PWA Settings, Enterprise Project Types.  
Enterprise Project Type vs. Management Style

This article has been discussing the two new project management styles that can be used in PWA 2013.  Do not confuse the management style with the template used for Enterprise Project Type (EPT). Management style has to do with feature capabilities and EPT has to do with which web pages will be displayed for the project in PWA.  For example: On the far right of the Project ribbon in PWA, the Change Project Type button is used to change the template that the plan uses.  If you want to change a project from a SharePoint Task List to a fully featured Enterprise plan you use the PWA Settings and Connected SharePoint Sites as discussed above.

SharePoint 2013 Products Configuration Wizard failure


Symptoms

While trying to set up the SharePoint 2013 on a standalone VM, you receive the following error when running the SharePoint 2013 Product Configuration Wizard
ErrorCode: ERRCAdmin024 SubStatus: ES0001 - Failed to refresh all running servers in the cluster. You may need to restart the cluster for these changes to take effect

Cause

This error is most likely related to App Fabric Cache.
Note: You do not need the App Fabric Cache on a standalone VM installation.

Resolution

Follow the steps listed below:
1. Open a command prompt as Administrator
2. Cd to "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\BIN "
3. Run the following command:

PSConfig -cmd Configdb create SkipRegisterAsDistributedCacheHost user Contoso\Administrator password password
4. Re-run the SharePoint 2013 Product Configuration Wizard. It should run right through the first 3 steps and start processing from step 4.
Note: You may have to clean up databases created from previously failed attempts by the wizard. 


SharePoint 2013: Cannot follow - (403) Forbidden


Symptoms

When trying to follow a site or a document a generic error occurs in the UI. In the ULS logs, the error is:
“The remote server returned an error: (403) Forbidden”


Cause

Customer had a publishing / consuming farm scenario where team sites were located in one farm (consuming) and the UPA and Mysite web application was in another farm (publishing). When you try to follow something, a client-side object model (CSOM) call is made to your mysite. In this scenario, this is a server to server (S2S) call and we need S2S authentication (Oauth) configured between the two farms for it to succeed.
Customer had not configured the S2S trust correctly.
In both farms, the NameIdentifier for SPSecurityTokenServiceConfig and the NameId and RegisteredIssuerName for SPTrustedSecurityTokenIssuer were still set to SharePointOAuthID@FarmID. Example:
00000003-0000-0ff1-ce00-000000000000@bf1cf54e-2890-4b45-a4c1-97005a0f757e
These should be set to SharePointOAuthID@RealmName
Example: 00000003-0000-0ff1-ce00-000000000000@SP2013S2S

Resolution

Run these commands in both farms:
Get-SPAuthenticationRealm
Get-SPTrustedSecurityTokenIssuer
Get-SPSecurityTokenServiceConfig

-- Get-SPAuthenticationRealm should return the realm name the customer has set.
-- Get-SPTrustedSecurityTokenIssuer should show a TrustedSecurityTokenIssuer that has NameId and RegisteredIssuerName set to 00000003-0000-0ff1-ce00-000000000000@<RealmName>
-- Get-SpSecurityTokenServiceConfig should show that NameIdentifier is set to 00000003-0000-0ff1-ce00-000000000000@<RealmName>

If the values are not correct for NameIdentifier, NameId, and RegisteredIssuerName, then you will need to remove the TrustedSecurityTokenIssuers from both farms, set SPSecurityTokenServiceConfig correctly, and then re-create the TrustedSecurityTokenIssuers.
1. Remove the TrustedSecurityTokenIssuers.a. Run Get-SPTrustedSecurityTokenIssuer. Note the ID of the one you want to remove
b. Run Remove-SPTrustedSecurityTokenIssuer -id <The ID of the one you want to remove>
c. Go into Central Admin | Security | Manage Trust and remove the S2S trust that was created when New-SPTrustedSecurityTokenIssuer was run. Leaving these extra trusts shouldn’t be a problem, but this is a good cleanup step.
2. Set up the S2S trust correctly by following these steps to recreate connection:

Change the farm authentication realm:
-- This needs to be done in Publishing and Consuming Farm(s)
The farms share a realm name, which must be set to the same value on all publishing and consuming farms.

Run the following on all farms, using the same realm name for both:
Set-SPAuthenticationRealm -realm <Realm Name>

Update the Security Token Service Config
This step updates the STS with the realm named shared between the publishing / consuming farms
-- This needs to be done in Publishing and Consuming Farm(s)
$sts=Get-SPSecurityTokenServiceConfig
$Realm=Get-SpAuthenticationRealm
$nameId = "00000003-0000-0ff1-ce00-000000000000@$Realm"
Write-Host "Setting STS NameId to $nameId"
$sts.NameIdentifier = $nameId
$sts.Update()
iisreset

Create new Trusted Security Token Issuer
This step creates a new Trusted Security Token Issuer on each farm
-- Run on Publishing and Consuming farms
Run this step last to create the final TrustedSecurityTokenIssuer’s, and note that the names specified for <SomeName> need not match between publishing and consuming farms.

On the consuming farm run:
New-SPTrustedSecurityTokenIssuer -name <SomeName> -MetadataEndPoint https://<PublishingFarmWebApp>/_layouts/15/metadata/json/1

On the publishing farm run:
New-SPTrustedSecurityTokenIssuer -name <SomeName> -MetadataEndPoint https://<ConsumingFarmWebApp>/_layouts/15/metadata/json/1

Note:
<PublishingFarmWebApp> and <ConsumingFarmWebApp> can be any SSL-enabled web application of the farm that will be sending server-to-server requests.

More Information


Here are the details of what you would find in the ULS logs when you run into this problem. Please note that you need to look at the logs on both the consuming and publishing sides:

-- From the Consuming farm (where you are trying to follow something):
w3wp.exe (0x156C) 0x17F4 SharePoint Portal Server User Profiles agb0e Medium SPS2SAppContext: Executing remote query to https://mysite.contoso.com/personal/userName/ with SourceID fda11a2b-5292-4181-8d51-cf0946acb5c1
w3wp.exe (0x156C) 0x17F4 SharePoint Foundation Application Authentication aiv3e High Self-issued token request for '00000003-0000-0ff1-ce00-000000000000/mysite.contoso.com@<RealmName>' succeeded.
w3wp.exe (0x156C) 0x17F4 SharePoint Portal Server Content Following afilq Unexpected FollowedContent.FollowItem:Exception:System.Net.WebException: The remote server returned an error: (403) Forbidden. at System.Net.HttpWebRequest.GetResponse() at Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute() at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb) at Microsoft.Office.Server.UserProfiles.FollowedContentProxy.Execute(String methodName) at Microsoft.Office.Server.UserProfiles.FollowedContent.FollowItem(FollowedItem item, Boolean isInternal)

-- Meanwhile on the UPA / MySite (publishing) farm, I see this:
w3wp.exe (0x0868) 0x25EC SharePoint Foundation Application Authentication ahkpt Medium SPApplicationAuthenticationModule Authentication finished successfully for user:0#.w|contoso\userName and actor:0i.t|ms.sp.ext|00000003-0000-0ff1-ce00-000000000000@cbc091f7-bec4-44f2-a4e7-13d66c447d22
w3wp.exe (0x0868) 0x25EC SharePoint Foundation Authentication Authorization ag6al Medium OAuth app principal Name=i:0i.t|ms.sp.ext|00000003-0000-0ff1-ce00-000000000000@cbc091f7-bec4-44f2-a4e7-13d66c447d22, IsAppOnlyRequest=False, UserIdentityName=0#.w|contoso\userName, ClaimsCount=166
w3wp.exe (0x0868) 0x23A0 SharePoint Foundation Authentication Authorization adhp1 High The app principal I:0I.T|MS.SP.EXT|00000003-0000-0FF1-CE00-000000000000@CBC091F7-BEC4-44F2-A4E7-13D66C447D22 does not exists.
w3wp.exe (0x0868) 0x23A0 SharePoint Foundation Authentication Authorization adhqj High Unable to get tenant permission for app I:0I.T|MS.SP.EXT|00000003-0000-0FF1-CE00-000000000000@CBC091F7-BEC4-44F2-A4E7-13D66C447D22. hr=-2130575150
w3wp.exe (0x0868) 0x23A0 SharePoint Foundation Authentication Authorization adhqm High Failed to initilize the m_pSiteAppPrincipal -2130575150
w3wp.exe (0x0868) 0x23A0 SharePoint Foundation General 8kh7 High The app principal does not exist.
w3wp.exe (0x0868) 0x23A0 SharePoint Foundation General aix9j High SPRequest.OpenWebInternal: UserPrincipalName=i:0).w|s-1-5-21-527237240-1682526488-1417001333-670443, AppPrincipalName=I:0I.T|MS.SP.EXT|00000003-0000-0FF1-CE00-000000000000@CBC091F7-BEC4-44F2-A4E7-13D66C447D22 ,bstrUrl=https://mysite.contoso.com/personal/userName/_vti_bin/client.svc/ProcessQuery
w3wp.exe (0x0868) 0x23A0 SharePoint Foundation General ai1wu Medium System.Runtime.InteropServices.COMException: The app principal does not exist., StackTrace: at Microsoft.SharePoint.SPWeb.InitWebPublic() at Microsoft.SharePoint.SPContext.DefaultKey(HttpContext context, SPWeb web) at Microsoft.SharePoint.SPContext.get_Current() at Microsoft.SharePoint.Client.SPClientServiceHost.OnBeginRequest() at Microsoft.SharePoint.Client.ClientRequestServiceImpl.ProcessQuery(Stream inputStream, IList`1 pendingDisposableContainer) at Microsoft.SharePoint.Client.ClientRequestService.ProcessQuery(Stream inputStream) at SyncInvokeProcessQuery(Object , Object[] , Object[] ) at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
w3wp.exe (0x0868) 0x23A0 SharePoint Foundation CSOM ajeo1 High The app principal i:0i.t|ms.sp.ext|00000003-0000-0ff1-ce00-000000000000@cbc091f7-bec4-44f2-a4e7-13d66c447d22 does not exist, sending 403 

500 Internal server error" while browsing to SharePoint 2013 sites

Symptoms

  • Users get the error "500 Internal server error" while browsing to the any new sites on the SharePoint server.
  • Open Task manager and we will notice Memory consumption at its peak.
  • If we browse to securitytoken.svc on the IIS console we get the below error:
Server Error in '/SecurityTokenServiceApplication' Application.
--------------------------------------------------------------------------------
Memory gates checking failed because the free memory (914993152 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InsufficientMemoryException: Memory gates checking failed because the free memory (914993152 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InsufficientMemoryException: Memory gates checking failed because the free memory (914993152 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.]
System.ServiceModel.Activation.ServiceMemoryGates.Check(Int32 minFreeMemoryPercentage, Boolean throwOnLowMemory, UInt64& availableMemoryBytes) +121924
System.ServiceModel.HostingManager.CheckMemoryCloseIdleServices(EventTraceActivity eventTraceActivity) +86
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +883
[ServiceActivationException: The service '/SecurityTokenServiceApplication/securitytoken.svc' cannot be activated due to an exception during compilation. The exception message is: Memory gates checking failed because the free memory (914993152 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element..]
System.Runtime.AsyncResult.End(IAsyncResult result) +650220
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +210733
System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) +166
Looked in to the ULS Logs and we see the below error
[Date and Time] w3wp.exe (0x072C) 0x0ECC SharePoint Foundation General 8nca Medium Application error when access /_layouts/15/settings.aspx, Error=The requested service, 'http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc' could not be activated. See the server's diagnostic trace logs for more information. Server stack trace: at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding) at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at Microsoft.IdentityModel.Protocols.WSTrust.IWSTrustContract.Issue(Message message) at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.Issue(RequestSecurityToken rst, RequestSecurityTokenResponse& rstr) at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.Issue(RequestSecurityToken rst) at Microsoft.SharePoint.SPSecurityContext.SecurityTokenForContext(Uri context, Boolean bearerToken, SecurityToken onBehalfOf, SecurityToken actAs, SecurityToken delegateTo, SPRequestSecurityTokenProperties properties) at Microsoft.SharePoint.SPSecurityContext.SecurityTokenForLegacyLoginContext(Uri context) at Microsoft.SharePoint.IdentityModel.SPWindowsClaimsAuthenticationHttpModule.PerformClaimsAuthenticationForUser(HttpContext context, SPFederationAuthenticationModule fam, SessionAuthenticationModule sam, WindowsIdentity windowsIdentity, SessionSecurityToken sessionSecurityToken, Boolean writeCookie) at Microsoft.SharePoint.IdentityModel.SPWindowsClaimsAuthenticationHttpModule.AuthenticateRequest(Object sender, EventArgs e) at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) 8ecdfd9b-9a3f-3054-c5fd-1d27ddcf178d

Cause

High Memory utilization preventing the Security Token service to be activated because SharePoint server was assigned Dynamic Memory instead of Static which is not supported (http://support.microsoft.com/kb/2764086/en-us)


Resolution

  • Turn off the SharePoint VM
  • Change the type of memory assigned from Dynamic to Static
  • Boot the machine and we should be able to browse to sites and securitytoken.svc without any errors.

SharePoint 2013: Workflow suspends on e-mail enabled library


Symptoms

SharePoint 2013 Designer Workflow goes to Suspended state when Item is added to on e-mail enabled document library https://sp.contoso.com/abc/Forms/AllItems.aspx
Name of Workflow: ABC Workflow.
When we manually add the item to library, everything works fine. New documents from incoming emails are starting the workflow but the workflow immediately goes to an Internal "Suspended" status and shows the below error in ULS. These workflows are initiated by the System Account. We have already set the declarativeworkflowautostartonemailenabled property to true, so we should be able to start the workflow upon creation. However, the workflow goes into a Suspended state.

We found below details in ULS logs.
RequestorId: 7d6b5f5d-e49d-3502-0000-000000000000. Details: RequestorId: 7d6b5f5d-e49d-3502-0000-000000000000.
Details: An unhandled exception occurred during the execution of the workflow instance. Exception details:
System.ApplicationException: HTTP 401 {"Transfer-Encoding":["chunked"],"X-SharePointHealthScore":
["0"],"SPRequestGuid":["7d6b5f5d-e49d-3502-b080-0ae9537b7c6b"],"request-id":["7d6b5f5d-e49d-3502-b080-0ae9537b7c6b"],"X-FRAME-OPTIONS":["SAMEORIGIN"], "MicrosoftSharePointTeamServices":["15.0.0.4481"],"X-Content-Type-Options":["nosniff"],"X-MS-InvokeApp":["1; RequireReadOnly"],"Cache-Control":["max-age=0, private"],"Date":["Thu, 02 May 2013 11:11:46 GMT"],"Server":["Microsoft-IIS\/8.0"],"WWW-Authenticate":["NTLM"],"X-AspNet-Version":["4.0.30319"],"X-Powered-By":["ASP.NET"]} {"error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Access denied. You do not have permission to perform this action or access this resource."}}} at Microsoft.Activities.Hosting.Runtime.Subroutine.SubroutineChild.Execute(CodeActivityContext context) at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)

Cause

'Workflows can use app permissions' was not activated. 

Resolution

  1. Added the System account to Full control Permission on bin folder and GAC.
  2. Confirmed that this account do have full control on the Web application.
  3. Checked Site actions > Site Settings > Site features > Workflows can use app permissions > Activate.
  4. Performed an IISReset.
  5. We tested this on library, This worked.
  6. Account was showing as SharePointApp now in place of System account.
  7. SPD 2013 workflow are working as expected.


SharePoint 2013 - Unable to resolve users from another trusted domain


Consider the following scenario:
You have two domains ABC.net and XYZ.net
SharePoint 2013 is installed on domain ABC.net and you have a two-way trust between both the domains
Adding a user from XYZ.net domain to a network share in ABC.net domain is working fine and we are able to see users from XYZ.net domain (vice-versa).

However, we are unable to resolve the user accounts from XYZ.net domain when trying to add them via people picker to a SharePoint 2010 site.


Cause

Unlike MOSS 2007 or SharePoint Server 2010, we need to register all two-way trusted domains with the people picker in SharePoint 2013

Resolution

Logon using the farm account credentials and open an elevated command prompt
Change to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\BIN folder
Execute the following command

Stsadm -o setproperty -pn peoplepicker-searchadforests -pv "domain:ABC.net,Login name,Password;domain:XYZ.net,Login name,Password" -url http://contoso.com
For more information, see Peoplepicker-searchadforests: Stsadm property
Note: There are no Windows PowerShell commands to configure People Picker.

SharePoint 2010 / 2013: Access Denied to claims web apps

All users, even admins with full control policy for web application get Access Denied when browsing to claims auth site collections.
In SharePoint 2013, they get the standard SharePoint access denied page that says:
“Sorry, you don’t have access to this page”

In SharePoint 2010, users get the standard SharePoint access denied page that says:
“Error: Access Denied”

If you take a Process Monitor trace, you will that “NT Authority\IUSR” is getting access denied to the root folder for the web application. For example: C:\inetpub\wwwroot\wss\VirtualDirectories\80.
You look at the Permissions for C:\inetpub\wwwroot\wss\VirtualDirectories\80, and you see that “Everyone” has been given Read permissions there along with all files and sub-folders. This group should contain the IUSR account, yet you still see the access denied in Procmon.
Note: If the "Everyone" group does not have Read permission at the root of each web app folder structure, that would cause this problem too.

In this situation, there are some things that users can successfully browse to. They include:
Central Admin
Pages in _layouts
Web apps that use Windows Classic authentication.

Cause

In the Local Security Policy | Local Policies | User Rights Assignment, “Bypass traverse checking” -- did not have the “Everyone” or “Users” group listed here, or anything that would contain the IUSR account. Because IUSR did not have this permission, it could not traverse C:\inetpub\, or C:\inetpub\wwwroot\, etc to get to C:\inetpub\wwwroot\wss\VirtualDirectories\80, and therefore was showing access denied for that directory even though it had permission at that level.

Resolution

1. Add a group that contains IUSR to “Bypass traverse checking” in the Local Security Policy. This could be “Everyone”, or “NT Authority\Authenticated Users”, or “Users”.
2. Gpudate /force
3. IISReset

Note: These policies may be pushed down to the machines via GPO, so you may have to change it at that level.

More Information

If you turn ULS logging up to verbose, you should see errors like the following just before it does the GET for _layouts/AccessDenied.aspx.
Notes: These entries may not have a correlation ID associated with them.
The errors are the same in both 2010 and 2013.

w3wp.exe (0x129C) 0x1DC0 SharePoint Foundation Claims Authentication ftc8 Verbose Access Denied: Authentication is required.
w3wp.exe (0x129C) 0x1DC0 SharePoint Foundation General 8gs1 Verbose Access Denied for /. StackTrace: at Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(HttpContext context) at Microsoft.SharePoint.IdentityModel.SPFederationAuthenticationModule.OnEndRequest(Object sender, EventArgs args) at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) at System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error) at System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb) at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr managedHttpContext, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags) at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr managedHttpContext, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags) at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr managedHttpContext, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags) at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr managedHttpContext, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)

Developer Dashboard in SharePoint 2013


The way to enable the Developer Dashboard in SharePoint 2013 remains the same. The following PowerShell script enables Developer Dashboard: $DevDashboardSettings = [Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashboardSettings; $DevDashboardSettings.DisplayLevel = 'OnDemand';
$DevDashboardSettings.RequiredPermissions = 'EmptyMask';
$DevDashboardSettings.TraceEnabled = $true;
$DevDashboardSettings.Update()
This turns on Developer Dashboard for the entire farm meaning all sites are enabled.
The Developer Dashboard opens in a new separate window and gives more information than before.

The tabs Scopes, SQL, SPRequests, Asserts and Service Calls are not new and show similar information like before. However, the ULS tab can be very handy since it lists all the events related to the current HTTP Request:

The tab Cache Calls is also interesting and lists all the interactions happening behind the scenes with AppFabric.

On the top, next to the Requests tab, you can find Animation/Scenarios and MDS (Minimal Download Strategy) which gives information about client scripting (css/javascript) similar to browser toolbars.
Minimal Download Strategy http://www.wictorwilen.se/sharepoint-2013---introduction-to-the-minimal-download-strategy-mds

SharePoint 2013 - Disable WebDAV use on SharePoint


In the event there is a cross site scripting attack using WebDAV by contributors to a site, a SharePoint administrator can protect their site by disabling all client integration.
This is an extreme measure, since it will effectively block SharePoint from being a useful collaboration tool, and block all Office client interaction with SharePoint. As such it's meant only as a data protection mechanism until a more targeted remedy is available.

More Information

To resolve this problem, disable the client integration. To do this, follow any of the following methods
Method 1
  1. Start SharePoint 2010 Central Administration | click Application Management | Manage Web applications
  2. Select the web application for which you want to disable "Client Integration" and click on "Authentication providers" from the ribbon
  3. Under Zone, Click Default to open the 'Edit Authentication' page.
  4. Under Enable Client Integration, click No, and then click Save.
Method 2
Create a permission policy for the web application to set 'UseRemoteAPIs' permission to 'false'
A permission policy level for a Web application contains permissions that enable a subset of users or groups to work with site collections in a specific way. For example, you might want to create a permission policy level for users of a site collection who will be allowed to add, edit, or delete items from a list, open a list, and view items, lists, and pages. However, you might want to prevent the same users from creating or deleting lists, which would require the Manage Lists permission.
The permissions list contains a Grant All column and a Deny All column. You can either grant or deny all permissions as part of a permission policy level. You can also grant or deny individual permissions. No permissions are enabled by default.
  1. Start SharePoint 2010 Central Administration | click Application Management | Manage Web applications
  2. Select the web application for which you want to create the permission policy click on "Permission Policy" from the ribbon
  3. Click on 'Add permission policy level'
  4. To disable client integration, ensure that 'Use Remote Interfaces - Use SOAP, Web DAV, or SharePoint Designer 2010 interfaces to access the Web site.' is set to 'DENY'. Other permissions can be set at the discretion of the site collection administrator or site administrator.
For more information, please the following articles

Tuesday, July 2, 2013

Let's Trobleshoot SharePoint

Some major issues in SharePoint 2013

Issue : UPA stuck on starting
Symptom
User profile service application-Feed cache repopulation job fails every 5 minutes and triggers following event id  :
Log Name:      Application
Source:        Microsoft-SharePoint Products-SharePoint Foundation
Date:          5/24/2013 4:20:02 AM
Event ID:      6398
Task Category: Timer
Level:         Critical
Keywords:     
User:          HONBLUE\SVC-SPFARMADMIN
Computer:      DYN-SPFE.honblue.local
Description:
The Execute method of job definition Microsoft.Office.Server.UserProfiles.LMTRepopulationJob (ID d5725fa3-1d31-434c-a80b-bd894dd37384) threw an exception. More information is included below.
Unexpected exception in FeedCacheService.IsRepopulationNeeded: Cache cluster is down, restart the cache cluster and Retry.
Cause
NA
Resolution
Remove-SPDistributedCacheServiceInstance
Add-SPDistributedCacheServiceInstance
Restart-CacheCluster




2)Distributed Cache in SharePoint 2013 -"Unexpected exception in FeedCacheService.IsRepopulationNeeded: Cache cluster is down, restart the cache cluster and Retry."
In ULS and event we were getting lots of errors related to Distributed cache

Event ID: 6398
Task Category: Timer
Level: Critical
Keywords:
User: xxxxxxxxxxx
Computer: xxxxxxxxx
Description:
The Execute method of job definition Microsoft.Office.Server.UserProfiles.LMTRepopulationJob (ID ba320718-0e80-4295-a3f8-a4badea59f0d) threw an exception. More information is included below.
Unexpected exception in FeedCacheService.IsRepopulationNeeded: Cache cluster is down, restart the cache cluster and Retry.

Cause
Issue with cache cluster.

Resolution
  • Run the following command:
Remove-SPDistributedCacheServiceInstance
$SPFarm = Get-SPFarm
$cacheClusterName = "SPDistributedCacheCluster_" + $SPFarm.Id.ToString()
$cacheClusterManager = [Microsoft.SharePoint.DistributedCaching.Utilities.SPDistributedCacheClusterInfoManager]::Local
$cacheClusterInfo = $cacheClusterManager.GetSPDistributedCacheClusterInfo($cacheClusterName);
$instanceName ="SPDistributedCacheService Name=AppFabricCachingService"
$serviceInstance = Get-SPServiceInstance | ? {($_.Service.Tostring()) -eq $instanceName -and ($_.Server.Name) -eq $env:computername}
if([System.String]::IsNullOrEmpty($cacheClusterInfo.CacheHostsInfoCollection))
{
$serviceInstance.Delete()
}
  • After this we ran following command
$SPFarm = Get-SPFarm
$cacheClusterName = "SPDistributedCacheCluster_" + $SPFarm.Id.ToString()
$cacheClusterManager = [Microsoft.SharePoint.DistributedCaching.Utilities.SPDistributedCacheClusterInfoManager]::Local
$cacheClusterInfo = $cacheClusterManager.GetSPDistributedCacheClusterInfo($cacheClusterName);
$instanceName ="SPDistributedCacheService Name=AppFabricCachingService"
$serviceInstance = Get-SPServiceInstance | ? {($_.Service.Tostring()) -eq $instanceName -and ($_.Server.Name) -eq $env:computername}
if([System.String]::IsNullOrEmpty($cacheClusterInfo.CacheHostsInfoCollection))
{
Add-SPDistributedCacheServiceInstance
$cacheClusterInfo.CacheHostsInfoCollection
}

ran Get-CacheHost and it shows the service is up