C# Tutorial: Calling Javascript from the Code Behind (.cs) File

In this short tutorial, I will show you how you can call Javascript from your code behind (.cs) file when programming in C#.  It came about because I was trying to find a way to display content in a new window after clicking a button.  So here it is.  (Please note that I am using Visual Studio 2012 and the ASP.NET 4.5 Framework in my examples.)

First, open a new project in Visual Studio by navigating to File -> New -> Project… (or hit Ctrl+Shift+N).

Visual Studio New Project

Next, I will select Templates -> Visual C# -> Web -> ASP.NET Empty Web Application and name the project SampleCode.  I will also check the option to Create a directory for solution and hit the OK button to continue.

SampleCode Project

Now, I am going to add the App_Code folder to my project because I want to create a helper class for organization reasons.  To add this folder, right click on the project name (SampleCode) in the Solution Explorer window and navigate to Add -> Add ASP.NET Folder -> App_Code.

App_Code Folder

To add the class, right click on the App_Code folder you’ve just created and navigate to Add -> Class…  I’ll go ahead and name this class BrowserUtility.cs and click on the Add button.

BrowserUtility Class

To make sure this class gets compiled into an assembly that I can use later, I’ll highlight the BrowserUtility.cs file under the App_Code folder, and in the Properties window, I will change the Build Action from Content to Compile.

Compile Option

In the class itself, I will import the System.Text namespace so that I can use the Stringbuilder class to create my Javascript string.  My class will just contain one public static method called OpenInNewBrowserWindow which takes one string as a parameter and returns a string as a result.  Here’s what the code looks like:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace SampleCode.App_Code
{
  public class BrowserUtility
  {
    #region Methods
    public static String OpenInNewBrowserWindow(String url)
    {
      StringBuilder sb = new StringBuilder();
      sb.Append("<script type = 'text/javascript'>");
      sb.Append("window.open('");
      sb.Append(url);
      sb.Append("','','width=1024,height=768')");
      sb.Append("</script>");

      return sb.ToString();
    }
    #endregion
  }
}

Now, I will add an ASP.NET Web Form page to my project by right clicking the project name and selecting Add -> Web Form.  In the Specify Name of Item window, I will type in Default and then click on the OK button.

Specify Name of Item Window

This will create a Default.aspx page.  Double click it to load it in your Visual Studio IDE and then switch to Design View.  Drag a button control onto the page, set the text to something like “Open Page“, and set the ID of the button to something like “openPageButton” if you’d like.  Following the same steps above, create another Web Form page called “HelloWorld” and type in “Hello World!” on the page.  Switch back to the Default.aspx page and double click on the openPageButton button to create a button Click event.  This will open the Default.aspx.cs (code behind) file and create a method called protected void openPageButton_Click(object sender, EventArgs e).  On top, place a using statement to load your custom assembly (i.e. using SampleCode.App_Code) and place the following code within this method:

String newWindow = BrowserUtility.OpenInNewBrowserWindow("HelloWorld.aspx");
ClientScript.RegisterStartupScript(this.GetType(), "script", newWindow);

The ClientScript.RegisterStartupScript method will allow you to execute your Javascript code and can be used for other types of scripts as well.  You entire code behind file should look something like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using SampleCode.App_Code;

namespace SampleCode
{
  public partial class Default : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void openPageButton_Click(object sender, EventArgs e)
    {
      String newWindow = BrowserUtility.OpenInNewBrowserWindow("HelloWorld.aspx");
      ClientScript.RegisterStartupScript(this.GetType(), "script", newWindow);
    }
  }
}

Finish building your application by navigating to Build -> Build Solution or hit Ctrl+Shift+B.  Redirect focus to the Default.aspx window and then hit F5 to launch and test your application.  Make sure you disable any pop-up blockers when you click on the “Open Page” button, and you can see your Javascript working in action.

Blast from the Past

This is actually a republish of an article I wrote last year.  I can’t believe I found this rummaging through my archive of computer files I kept over the years. It’s a Microsoft Word document I created on June 19, 1995 while working at a UCLA computer lab. Here is what I wrote in verbatim:

Frequently Asked Questions and Some Common Troubleshooting Tips

How do I change printers?

To change printers on the Macintosh (while using any program):

First, on the upper left hand corner of the screen and on the menu bar, there is an apple icon. Move the cursor to this icon. Click on it and keep the mouse button depressed. This will bring up a new menu of choices. (This menu of choices is commonly referred to as the Apple Menu.) Now drag the mouse so that the word Chooser is highlighted and release the button. This will bring up a new window. To select an image writer printer, click on the Appletalk Imagewriter icon. To select the laser printer, click on the Laser Printer icon.

To change printers on the IBM (any Microsoft product)

Go to the File Menu and select Printer Setup. This will bring up a window with a list of printers. Select appropriate type and select OK.

To change printers on the IBM (WordPerfect)

If there is a menu bar, go to the file menu and select print, or press Shift+F7. Press S to bring up a selection of printers. Highlight the appropriate printer and press 1 to select it.

My paper is printing on the printer, but it is not aligned correctly. How do I fix this?

First, check to see if the margins are set properly on your document. You can do this by going to the Format Menu and selecting Document. If this does not correct the problem, then check to see if the perforations of the paper are aligned properly on the printer (dot matrix only).

I saved my file, but every time I check my disk, it’s not there! What happened to my file?

Most probably, you saved your file somewhere on the hard drive. To correct this, make sure that you change the current directory to the directory that you would like to save your files in.

I just bought a new disk. How do I format it so that I can use it on the IBM?

To format a disk (Windows):

Open up File Manager. Next, go to the Disk Menu and select Format Disk. Select the drive you wish to format the disk in and the capacity of the disk. Then, select OK.

To format a disk (DOS):

At the DOS prompt, type format d:/f:size where d is the drive letter and size is the capacity of the disk.

I am a newbie to the Internet, and I would like to download GIFs from a site. How do I do this?

There are two ways in which you can do this at an HCF lab. First, you can either use a net browser like Mosaic or Netscape. Locate the file and click on it. Then, Mosaic or Netscape will ask you if wish to download it. The other way is through anonymous ftp. Load either FTP (IBM) or Fetch (Macintosh). Next enter either the domain name or the IP Address of the site you wish to connect to. Use either anonymous, ftp, or your e-mail address as your password. Once connected, you can select the file(s) you wish to download.

The just goes to show you how some things have changed (e.g. computing) while other things remained the same (e.g me creating troubleshooting articles).

A Microsoft SQL Server Database Administrator’s Daily Bread: Killing Processes

A few years ago, I started on a path to become a database administrator and read many articles on the Internet on how to break into that field.  There were a lot of articles out there, but I don’t remember finding many that offered practical knowledge (i.e. advice on what problems database administrators might encounter on a day-to-day basis).  Please note that at the time I am writing this article, I am not officially a database administrator within my organization, but I do perform database related duties and wanted to share my experience with you.

Working for a hosting company, our customers do not have complete access/control over their databases which is understandable since you are offloading management duties to the hosting company.  Learning how to correctly kill a process can be essential to getting a database back in working order, and here’s a list of the occasions where I’ve had to do it:

1) The database had open transactions causing a database lock.
2) The database somehow got set to SINGLE_USER mode, the customer was still logged in, and it needed to be set back to MULTI_USER mode (This works 9 times out of 10.  Sometimes, the person is logged in with SQL Server Management Studio, and you won’t be able to kill the process.  In that case, you just ask the customer politely to log off.)
3) Trying to bring a database online/offline, and it gets stuck.
4) The database Auto-Close setting got set to true or on.
5) Database Attach/Backup/Restore jobs which get stuck.

There are probably many ways to do this, but I found this to be the simplest to understand:

1) Make sure you’re logged in with an account that has SQL Server Administrator privileges using SQL Server Management Studio.
2) Open a New Query window and type in the following replacing DatabaseName with the name of the database.

USE MASTER
GO

SELECT DB_ID(N'DatabaseName') AS [Database ID]

3) It should return a number in the Results windows.

DatabaseID Results Window

4) Enter the next set of T-SQL commands in the same or new window replacing # with the Database ID number from the Results window.  If you are doing this in the same window, remember to highlight only the following code and then hit F5 or the Execute button so that you will not be executing other T-SQL statements.

USE MASTER
GO

SELECT * FROM SYSPROCESSES WHERE DBID = #

5) You should get a set of results like the one below.

SPIDs

6. To kill the process, look at the spid number and type in the following in the Query window replacing SPID# with the actual number.

KILL SPID#

For open transactions, if the number is greater than 0, then that most likely is the process that is causing the problem, and you can just kill that one.  Familiarize yourself with the column names and their meanings as they will help you identify which processes you should be removing.  Sometimes, I’ve had to clear all the processes associated with the database so that I could execute other commands to perform maintenance on it.  As with anything, use the kill command with great caution and care as you don’t want to be killing system related processes that could crash the SQL Server engine or cause corruption to your databases.