Set SharePoint CorrelationID programmatically for Troubleshooting

This post has been republished via RSS; it originally appeared at: New blog articles in Microsoft Tech Community.

This post is a contribution from Jing Wang, an engineer with the SharePoint Developer Support team.

 

There are multiple ways to access SharePoint data with custom code, for example, CSOM, JSOM, SharePoint Rest API and Sharepoint Web Service call.

Troubleshooting problems with these accesses likely need correlation IDs of the failed requests. With the correlation IDs we can locate relevant errors in SharePoint ULS logs efficiently.

However, not all failed requests expose the correlation ID to UI, code or through network traces. In those scenarios, being able to set distinctive correlation IDs when send the requests to SharePoint become very useful.

 

  1. For CSOM (client object model code), it is straight forward to set it:


ClientContext context = new ClientContext("https://{site_url}");
Web web = context.Web;

context.TraceCorrelationId = "88888888111111112222222233333333";

context.Load(web);

context.ExecuteQuery();

  1. For JSOM (JavaScript library code):

<script type="text/javascript">

var clientContext;

var website;

SP.SOD.registerSod('sp.js', '/_layouts/16/sp.js');

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);

function sharePointReady() {

    clientContext = SP.ClientContext.get_current();

    website = clientContext.get_web();   

    clientContext.set_traceCorrelationId(88888888111111112222222233333333');

    clientContext.load(website);

    clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);

}

function onRequestSucceeded() {alert(website.get_url());  }

function onRequestFailed(sender, args){alert('Error: ' + args.get_message());}     

</script>

 

  1. For SharePoint Rest API call

 

<input id="Button" type="button" value="Empty Site Recycle Bin" onclick="runCode()" />

<script type="text/javascript">   

function runCode(){

    SP.SOD.registerSod('sp.js', '/_layouts/16/sp.js');

    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', emptySiteRecycleBin);

    function emptySiteRecycleBin(){

        var restUrl = _spPageContextInfo.webAbsoluteUrl+"/_api/site/RecycleBin/deleteAll()";             

        $.ajax({

            url: restUrl,

            type: "POST",                                                        

            //withCredentials: true,

            headers: {    

               "X-RequestDigest": $("#__REQUESTDIGEST").val(),

               'SPResponseGuid': '88888888111111112222222233333333'               

                                },                                                       

              success: function(response) {alert("Emptied Site RecycleBin!");},

              error: function(response){ alert("Error empting RecycleBin..." );}                 

            });
      } 
}
</script>

Fiddler Trace shows the correlation ID was set successfully:

SPDev_Support_0-1583533551789.png

 

 

 

  1. For the calls to SharePoint Web Services, for example, listdata.svc or lists.asmx, we can hardcode the correlation IDs as well.

 

To make a web service call from C# code, you need to create web service reference to the service .svc file first, Visual Studio will generate the reference class for the web service automatically, for example, reference.cs:

The below is the code change needed to add into that class file:


namespace callwebservice.sp2016ws {

    using System;​

    using System.Web.Services;​

    using System.Diagnostics;​

    using System.Web.Services.Protocols;​

    using System.Xml.Serialization;​

    using System.ComponentModel;​

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.7.2053.0")]​

    [System.Diagnostics.DebuggerStepThroughAttribute()]​

    [System.ComponentModel.DesignerCategoryAttribute("code")]​

    [System.Web.Services.WebServiceBindingAttribute(Name="ListsSoap", Namespace="http://schemas.microsoft.com/sharepoint/soap/")]​

    public partial class Lists : System.Web.Services.Protocols.SoapHttpClientProtocol {​

        ​

        private System.Threading.SendOrPostCallback GetListOperationCompleted;​

        protected override System.Net.WebRequest GetWebRequest(Uri uri)​

           {​
       var request = base.GetWebRequest(uri);​
       request.Headers.Add("SPResponseGuid","88888888111111112222222233333333"); ​

       return request;​

        }​

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.