Three Not-So-Obvious Ways to Use Visual Studio’s Debugger

#1: How do you create a breakpoint in Visual Studio when generating JavaScript as a string? Just include a debugger; statement in the string and Visual Studio will step in when the statement is executed.

#2: How do you write to Visual Studio’s debug window from JavaScript? Call the Sys.Debug.trace() method and it’s parameter will show up in Visual Studio’s debug window.

#3: How do you set a breakpoint in code? Call the System.Diagnostics.Debugger.Break() method and Visual Studio will step in when the statement is executed–after asking you four times if it really should. This can come in handy when it’s cumbersome to attach to the process executing your code–for example when debugging a SharePoint feature receiver.

Here’s an example for ways #1 and #2:

protected override void CreateChildControls() {
 CreateJavaScript();
 // Table 
 Table t = new Table();
 Controls.Add(t);
 TableRow tr = new TableRow();
 t.Rows.Add(tr);
 TableCell tc = new TableCell();
 tr.Cells.Add(tc);
 // CallJavaScriptButton
 Button CallJavaScriptButton = new Button();
 tc.Controls.Add(CallJavaScriptButton);
 CallJavaScriptButton.Attributes.Add("onclick", "testMethod(); false;");
 CallJavaScriptButton.ID = "CallJavaScriptButton";
 CallJavaScriptButton.Text = "Call JavaScript";
} // CreateChildControls()

void CreateJavaScript() {
 if (Page.ClientScript.IsClientScriptBlockRegistered(
  this.GetType(), "MyJavaScript") == false) {
  StringBuilder sb = new StringBuilder();
  sb.Append("<script type='text/javascript'>");
  sb.Append("\r\nfunction testMethod() {");
  sb.Append("\r\n debugger;");
  sb.Append("\r\n alert('Hello from JavaScript!');");
  sb.Append("\r\n Sys.Debug.trace('testMethod() called at: ' + new Date().toLocaleString());");
  sb.Append("\r\n}");
  sb.Append("\r\n</script>");
  Page.ClientScript.RegisterClientScriptBlock(
   this.GetType(), "MyJavaScript", sb.ToString());
 }
} // CreateJavaScript
Advertisements
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s