Thursday, January 26, 2012

Toggle Debugging on/off for a Custom Code Web Part in SharePoint

C#
When I render my custom coded SharePoint Web Part, it helps to display extra information to assist me in troubleshooting. I can do this by constructing my web part like this...

...
using System.Web.UI.WebControls.WebParts;
...
public class MyCustomWebPart : WebPart
{
  protected override void CreateChildControls()
  {
    string paramOne = "One";
    this.Controls.Add(new LiteralControl("paramOne=" + paramOne + <br/>));
  }
}

So that my custom Web Part displays "paramOne=One"  Useful for debugging when I want know the value of internal parameters in code.

However, I don't want my user's to see my debugging information. I only want to turn it on in my local browser instance. I do this by adding to the Query String "?debug=true"  So on the end of my URL I append the Query String and update my Controls.Add statement with the following code.

bool.TryParse(Page.Request.QueryString["debug"], out debugOn);
if (debugOn) this.Controls.Add(new LiteralControl("paramOne=" + paramOne));

No comments:

Post a Comment