Sharepoint学习笔记—Debug&TroubleShooting--使用代码获取当前Request的CorrelationID
在Sharepoint2010中,每个Request都有自己的Correlation ID,我们在跟踪或调试时会结合ULS来查找特定的信息(如:Error信息等),Correlation ID的使用请参见此文(Sharepoint学习笔记—Debug--Correlation ID的使用),这里我们要通过代码来获取当前Request的Correlation ID。
先在我们的项目中新建一个类:MYSPCorrelationId .cs,此类有一个方法GetCurrentCorrelationToken(), MYSPCorrelationId .cs 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace CopyListContent
{
public class MYSPCorrelationId
{
[DllImport("advapi32.dll")]
public static extern uint EventActivityIdControl(uint controlCode, ref Guid activityId);
public const uint EVENT_ACTIVITY_CTRL_GET_ID = 1;
public static Guid GetCurrentCorrelationToken()
{
Guid g = Guid.Empty;
EventActivityIdControl(EVENT_ACTIVITY_CTRL_GET_ID, ref g);
return g;
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace CopyListContent
{
public class MYSPCorrelationId
{
[DllImport("advapi32.dll")]
public static extern uint EventActivityIdControl(uint controlCode, ref Guid activityId);
public const uint EVENT_ACTIVITY_CTRL_GET_ID = 1;
public static Guid GetCurrentCorrelationToken()
{
Guid g = Guid.Empty;
EventActivityIdControl(EVENT_ACTIVITY_CTRL_GET_ID, ref g);
return g;
}
}
}
创建一个Viusal WebPart,放入一个Button和一个Label标签
在Button的Click事件中写入
protected void BtnGetCorrelation_Click(object sender, EventArgs e)
{
lblCurCorrelation.Text = MYSPCorrelationId.GetCurrentCorrelationToken().ToString();
}
{
lblCurCorrelation.Text = MYSPCorrelationId.GetCurrentCorrelationToken().ToString();
}
部署此WebPart,当点击Button后就可以得到当前Request的Correlation ID。如下图:
当然在实际操作中,你通常是把这一段代码写入你想要获取Correlation ID的任何地方(eg: try/catch, event, receiver),然后把Correlation ID写入或输出到用户容易获取到的地方(eg: Label, alert....等等),如果你能培训你的用户让他能把你在这段代码中获取的Correlation ID 连同他们的操作记录传给你,你就能更加方便快速地定位和解决问题了。