How to use the MathFlow SDK editor applets with ASP.NET

The information on this page applies to:
MathFlow SDK (all versions)ASP.NET

This document describes how to use the MathFlow SDK Simple Editor applet within an ASP.NET environment. The same lessons learned here can be applied to the other MathFlow SDK applets.

The MathFlow SDK includes three editors available as Java applets that allow a user to create math equations using a graphical user interface. Since it is built using Java technology, it is not possible to directly access various features of the control using any of the normal .NET languages (such as C#, VB, etc.). However, it is possible to use JavaScript to interact with the editor applets, so we can use this feature to pass data from the applet to an ASP.NET textbox, and from the ASP.NET textbox we can then manipulate it however we choose. In most situations, the MathML string will be stored in a database, but there may be many other possibilities. Our example will simply place the MathML we captured into an ASP.NET Label so we can see the result. For this example, we'll use the Simple Editor applet, but the same steps apply to the Style and Structure Editor applets, as well.

You will need Microsoft Visual Studio .NET with a correctly configured web server such as IIS in order to run this example. You will also need basic familiarity with C#, but the example can be refactored into any .NET language. Also, you should understand the basic use of JavaScript. You will also need copies of the JAR files that come with the MathFlow SDK (MFExtraSymFonts.jar, SampleCode.jar and MFSimpleApplet.jar). To run the example, you will need a Java browser plug-in installed (JRE 1.4.2 or later).

Open up Visual Studio .NET (2008 or 2010) , and select File > New > Project from the menu. You can use your .NET language of choice, but this example will be using C#. This is not a tutorial for C# and the example does not require any special knowledge of that language. So go ahead and select the C# project type and select ASP.NET Web Application icon and give your project a name. I used CSharpWebApp1 as the project name, but feel free to use whatever name you would like. Now click OK.

A word of caution:

We found that placing an applet or object tag into a web form would cause Visual Studio's graphical web page designer to freeze with the IDE taking 100% CPU utilization, which required the IDE to be forcibly quit. Therefore it is best to avoid using the graphical designer for this example. We will be using the HTML editor throughout this example. To ensure that the IDE does not try to open the page in Design mode upon startup, choose Tools > Options... from the menu bar. In the resulting dialog, select HTML Designer, and make sure that the "Start pages in" option is set to Source View.

Once you have a project, you can begin to edit the existing pages. First we will start with the Default.aspx file. If it is not already open, double click the file called Default.aspx in the Solution Explorer.

If you are using Visual Studio 2010 do the following: In HTML mode, remove the contents of the <asp:ContentID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> element. Leave the opening and closing tags,  but replace everything between them with the following HTML. After you've pasted the code, remove just the opening and closing form tags (not the code between them), as these are already defined in Site.Master.

If you are using Visual Studio 2008 do the following: remove the form tags, and everything between them, and replace it with the following HTML.

<%-- This form will display the Simple Editor applet as well as controls that will manipulate the applet --%>
<form id="Form1" method="post" runat="server">
<%-- This tag shows how to load the Simple Editor applet. Here is a brief description of various elements and attributes...
name and PARAM name="name": This value will be used to refer to the applet in JavaScript
PARAM name="code": This value is the fully qualified name of the Java class to load
PARAM name="archive": This value is the location(s) where the Java Jar files reside
PARAM name="codebase": This value is the prefix that is appended as a path to the code
PARAM name="type": This value is the mime type for a java applet
PARAM name="eq": This value is MathML. Note that it is not required to supply a value
PARAM name="scriptable": This value indicates if the applet can be accessed via scripting languages
--%>
<APPLET name="applet" width="800" height="200" align="baseline" VIEWASTEXT> <br />
<PARAM name="code" value="com.yourcompany.samplecode.editor.SampleSimpleEditorApplet">
<PARAM name="archive" value="./SampleCode.jar,MFSimpleApplet.jar,MFExtraSymFonts.jar">
<PARAM name="codebase" value=".">
<PARAM name="type" value="application/x-java-applet;jpi-version=1.4.2">
<PARAM name="name" value="applet">
<PARAM name="eq" value="<math><mrow></mrow></math>">
<PARAM name="scriptable" value="true">
No Java 2 SDK, Standard Edition v 1.4.2 support for APPLET!!
</APPLET>

<%-- This textbox is used for inserting valid MathML --%>
<p>''MathML:'' </p><input type="text" name="mml" id="mml" />

<%-- This button will initiate the insertion of the MathML string stored in the "mml" textbox. Note that both the text box and button are standard HTML elements and not ASP.NET controls. --%>
<input type="button" onclick="insertMML();" value="Insert" />

<%-- This ASP.NET button executes the JavaScript code and Button1_Click event that is defined in the codebehind =(i.e. Default.aspx.cs). --%>
<asp:Button id="Button1" Runat="server" Text="Send MML"></asp:Button>

<%-- The JavaScript code grabs the MathML and places it into this textbox for storage so that the ASP.NET code can access it. The field is made invisible by placing it inside a DIV and setting its style to "display: none". --%>
<div style="DISPLAY: none"><asp:TextBox id="storedMML" Runat="server" ClientIDMode="Static"></asp:TextBox></div>

<%-- This label is used simply to display the results of grabbing the MathML from the InputControl. In a real system, the MathML could be stored in a database. --%>
<asp:Label id="Label1" runat="server" Width="100%" Height="16px"></asp:Label>

</form>

At the very top of Default.aspx, add validateRequest="false" to the Page element.

Next for Visual Studio 2010 only, update the <system.web> section of your web.config file to include the following line: <httpRuntime requestValidationMode = "2.0" />

The above two changes are to prevent "dangerous Request.Form value was detected from the client" errors, and should be handled in a more robust fashion in your code.

This code creates the user interface for our example. It creates an instance of the Simple Editor applet using the applet tag and includes several HTML and ASP.NET form controls. Be sure to read the comments for each element, since they describe what each item is used for.

Next we are going to modify the "codebehind", which is the server-side code that will be called when the page loads and ASP.NET buttons are clicked. To modify this code, right click on the Default.aspx file in the Solution Explorer and select View Code, which should open a file called Default.aspx.cs. Replace this code:

public partial class _Default : System.Web.UI.Page
{
  private void Page_Load(Object sender, System.EventArgs e)
  {
  }
}

…with this code…

public partial class _Default : System.Web.UI.Page
{
  private void Page_Load(Object sender, System.EventArgs e)
  {
    // The following lines will build the javascript string that will be inserted into the page…
    string aJSFunction = "<script language=JavaScript>";
    // This javascript function will insert a MathML equation into the editor from a text field called "mml"
    aJSFunction += "function insertMML(){var eq = applet;var mymml = document.getElementById('mml').value;eq.insertMathMLAtCursor(mymml);}";
    // This javascript function will take the MathML equation stored inside the editor and place it into
    // a hidden asp:TextBox called "storedMML". Once the value is stored in the text field, we can extract
    // the value using .NET and do whatever we want with it.
    aJSFunction += "function submitMML(){var eq = applet;document.getElementById('storedMML').value = eq.getMathML();}";
    // This javascript code will be executed each time the page loads. It will take the MathML text stored within
    // the hidden asp:TextBox called "storedMML" and place it into the editor. This is necessary because
    // each time the user does a postback, the Applet reloads itself, which erases the formula.
    aJSFunction += "</script>";
    // This will insert the javascript into the page. This register version ensures that all of the
    // form elements have been rendered and are therefore accessible to the javascript code.
    Page.RegisterStartupScript("StartUp", aJSFunction);
    // This just shows how to programmatically insert an onclick attribute. This could have been done
    // directly in the HTML code.
    Button1.Attributes.Add("OnClick", "submitMML();");
  }
  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
    //%%
    //%% CODEGEN: This call is required by the ASP.NET Web Form Designer.
    //%%
    InitializeComponent();
    base.OnInit(e);
  }
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {
    this.Button1.Click += new System.EventHandler(this.Button1_Click);
    this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion
  public void Button1_Click(Object sender, EventArgs e)
  {
    // When the button is clicked, the javascript code should have placed the MathML
    // into the storedMML TextBox. Once we have the text we can do whatever we want with it.
    // For example, we could store the value in a database. However in this example we just
    // display the value in a label so we can see the result.
    Label1.Text = "The following text could have been saved to a database..." + Server.HtmlEncode(storedMML.Text);
  }
}

In order for the web browser to find the Java applet, you must place the MFExtraSymFonts.jar, SampleCode.jar, and MFSimpleApplet.jar files into the same directory as Default.aspx (these can be found in <path-to-SDK-installation>\<version>\java\samples and <path-to-SDK-installation>\<version>\java\lib). It is also possible to specify the location of the JAR using the archive parameter. In a real deployment it is best to place the JAR in a single location and then all pages that need to reference the JAR will point to this single location. There are two benefits of doing it this way. The first is that it simplifies upgrades when a new version of MathFlow becomes available, since you would only need to update the JAR in one location. The second benefit comes when the user downloads the JAR to their machine for execution. When a page references the JAR, it is downloaded and cached for current and future use. If you were to upgrade the JAR, the Java plugin will automatically determine that a newer version is available on the server and will download it automatically. So in summary, one location for the JAR results in a one time download for the user, even if you reference the JAR from many web pages.

You can run the example by pressing the start button in the toolbar, or by choosing the Debug > Start menu item. When you run the application, you should see the Simple Editor applet load. You can now either enter MathML into the textbox below the Simple Editor applet and click Insert, which should result in an equation within the Simple Editor applet (assuming that you have entered valid MathML). Or you can simply enter an equation into the input control and then hit "Send MML", which will result in the MathML for the equation being output at the bottom of the web page. Both of these examples show how to interact with the Simple Editor applet.

This example shows several different things that are important to know when combining the MathFlow SDK components with ASP.NET. First of all, it shows how to use JavaScript in combination with ASP.NET. In this example, the JavaScript is inserted into the web page using the Page.RegisterStartupScript() method when the page is loaded by building a string containing the JavaScript code. Please note that it is also possible to place the JavaScript directly into the webpage, but the example shows how to do it using server-side code. The JavaScript will be invoked when one of the two buttons is pushed as described above. There is also a bit of JavaScript that is executed every time the page is loaded. This code is necessary because whenever the user presses an ASP.NET button (as opposed to a regular HTML button) the server-side C# code is executed. This action submits information to the server, and then causes the page to reload. Whenever a web page is loaded, this causes the Java applet to initialize itself, which results in the equation being lost in the Simple Editor. So to prevent the loss of the equation, we make a JavaScript call to insertMathMLAtCursor() using the MathML that is stored in a hidden textbox on the page. The hidden textbox is filled with the MathML when the user presses the "Send MML" button, using JavaScript. The "Send MML" button also generates a server-side event which executes the Button1_Click() method, which simply takes the MathML from the hidden text field and places it into a ASP.NET label. You could do anything you want with the MathML on the server-side, such as place the information into a database.

Keep in mind that anytime you use an ASP.NET button, it will cause a round trip to the server to execute the server-side code. Sometimes this is not necessary, especially when you want to provide the the user with a way to interact with one of the MathFlow SDK components. For example, the "Insert" button simply needs to take a value from a standard HTML textbox and insert the value into the InputControl. There is no need for a round trip to the server in this instance.

Also note the <div style="DISPLAY: none"> tag around the ASP.NET textbox called "storedMML". This is how we make the textbox hidden from the user. If we were to set the visible attribute of the ASP.NET textbox to false, that would simply prevent the textbox from being rendered, which would in turn prevent the JavaScript code from saving the MathML, since the textbox would be unavailable. The div tag solves this problem by making the textbox invisible to the user, but visible to JavaScript.

As was stated earlier, the MathFlow SDK editors allow a developer to interact with them using JavaScript. This example shows just two ways to interact with the Simple Editor applet. Each of the MathFlow SDK components can be manipulated in similar ways, using the public API for each component. For a detailed list of API calls available for each control, consult the MathFlow SDK Programmer's Guide.


""

We hope this has been helpful. As always, please let us know if you have questions about this, or if you have additional techniques that work. We'd love to hear from you.