Amazon Ad

Monday 24 March 2014

Create In Browser Compiler For C#,Java,C,C++,Python, Ruby and many more using CodeMirror and IDEOne

Hi Folks!

I was given a task to create a website which can compile the code, the code can be c#,java,c,c++,ruby,python and other languages. I found a very good API(IDEONE), really simple to implement and gives fast result. I also used codemirror, which is a great code editor for different languages and provides real time environment like keyword recognition.

I built the same in asp.net, Please follow the steps.



Step 1. Create a dropdownlist, TextBox(TextArea) and a button to submit the result. Here is the code for the asp.net form :


<form id="form1" runat="server">
        Select Your Language:
        <asp:DropDownList ID="ddlLanguage" runat="server" AutoPostBack="true" Width="250px" OnSelectedIndexChanged="ddlLanguage_SelectedIndexChanged">
            <asp:ListItem Value="7">Ada (gnat-4.3.2)</asp:ListItem>
            <asp:ListItem Value="13">Assembler (nasm-2.07)</asp:ListItem>
            <asp:ListItem Value="45">Assembler (gcc-4.3.4)</asp:ListItem>
            <asp:ListItem Value="104">AWK (gawk) (gawk-3.1.6)</asp:ListItem>
            <asp:ListItem Value="105">AWK (mawk) (mawk-1.3.3)</asp:ListItem>
            <asp:ListItem Value="28">Bash (bash 4.0.35)</asp:ListItem>
            <asp:ListItem Value="110">bc (bc-1.06.95)</asp:ListItem>
            <asp:ListItem Value="12">Brainf**k (bff-1.0.3.1)</asp:ListItem>
            <asp:ListItem Value="11">C (gcc-4.3.4)</asp:ListItem>
            <asp:ListItem Value="27" Selected="True">C# (mono-2.8)</asp:ListItem>
            <asp:ListItem Value="1">C++ (gcc-4.3.4)</asp:ListItem>
            <asp:ListItem Value="44">C++0x (gcc-4.5.1)</asp:ListItem>
            <asp:ListItem Value="34">C99 strict (gcc-4.3.4)</asp:ListItem>
            <asp:ListItem Value="14">CLIPS (clips 6.24)</asp:ListItem>
            <asp:ListItem Value="111">Clojure (clojure 1.1.0)</asp:ListItem>
            <asp:ListItem Value="118">COBOL (open-cobol-1.0)</asp:ListItem>
            <asp:ListItem Value="106">COBOL 85 (tinycobol-0.65.9)</asp:ListItem>
            <asp:ListItem Value="32">Common Lisp (clisp) (clisp 2.47)</asp:ListItem>
            <asp:ListItem Value="102">D (dmd) (dmd-2.042)</asp:ListItem>
            <asp:ListItem Value="36">Erlang (erl-5.7.3)</asp:ListItem>
            <asp:ListItem Value="124">F# (fsharp-2.0.0)</asp:ListItem>
            <asp:ListItem Value="123">Factor (factor-0.93)</asp:ListItem>
            <asp:ListItem Value="125">Falcon (falcon-0.9.6.6)</asp:ListItem>
            <asp:ListItem Value="107">Forth (gforth-0.7.0)</asp:ListItem>
            <asp:ListItem Value="5">Fortran (gfortran-4.3.4)</asp:ListItem>
            <asp:ListItem Value="114">Go (gc-2010-07-14)</asp:ListItem>
            <asp:ListItem Value="121">Groovy (groovy-1.7)</asp:ListItem>
            <asp:ListItem Value="21">Haskell (ghc-6.8.2)</asp:ListItem>
            <asp:ListItem Value="16">Icon (iconc 9.4.3)</asp:ListItem>
            <asp:ListItem Value="9">Intercal (c-intercal 28.0-r1)</asp:ListItem>
            <asp:ListItem Value="10">Java (sun-jdk-1.6.0.17)</asp:ListItem>
            <asp:ListItem Value="35">JavaScript (rhino) (rhino-1.6.5)</asp:ListItem>
            <asp:ListItem Value="112">JavaScript (spidermonkey) (spidermonkey-1.7)</asp:ListItem>


            <asp:ListItem Value="26">Lua (luac 5.1.4)</asp:ListItem>
            <asp:ListItem Value="30">Nemerle (ncc 0.9.3)</asp:ListItem>
            <asp:ListItem Value="25">Nice (nicec 0.9.6)</asp:ListItem>
            <asp:ListItem Value="122">Nimrod (nimrod-0.8.8)</asp:ListItem>
            <asp:ListItem Value="43">Objective-C (gcc-4.5.1)</asp:ListItem>
            <asp:ListItem Value="8">Ocaml (ocamlopt 3.10.2)</asp:ListItem>
            <asp:ListItem Value="119">Oz (mozart-1.4.0)</asp:ListItem>
            <asp:ListItem Value="22">Pascal (fpc) (fpc 2.2.0)</asp:ListItem>
            <asp:ListItem Value="2">Pascal (gpc) (gpc 20070904)</asp:ListItem>
            <asp:ListItem Value="3">Perl (perl 5.12.1)</asp:ListItem>
            <asp:ListItem Value="54">Perl 6 (rakudo-2010.08)</asp:ListItem>
            <asp:ListItem Value="29">PHP (php 5.2.11)</asp:ListItem>
            <asp:ListItem Value="19">Pike (pike 7.6.86)</asp:ListItem>
            <asp:ListItem Value="108">Prolog (gnu) (gprolog-1.3.1)</asp:ListItem>
            <asp:ListItem Value="15">Prolog (swi) (swipl 5.6.64)</asp:ListItem>
            <asp:ListItem Value="4">Python (python 2.6.4)</asp:ListItem>
            <asp:ListItem Value="116">Python 3 (python-3.1.2)</asp:ListItem>
            <asp:ListItem Value="117">R (R-2.11.1)</asp:ListItem>
            <asp:ListItem Value="17">Ruby (ruby-1.9.2)</asp:ListItem>
            <asp:ListItem Value="39">Scala (scala-2.8.0.final)</asp:ListItem>
            <asp:ListItem Value="33">Scheme (guile) (guile 1.8.5)</asp:ListItem>
            <asp:ListItem Value="23">Smalltalk (gst 3.1)</asp:ListItem>
            <asp:ListItem Value="40">SQL (sqlite3-3.7.3)</asp:ListItem>
            <asp:ListItem Value="38">Tcl (tclsh 8.5.7)</asp:ListItem>
            <asp:ListItem Value="62">Text (text 6.10)</asp:ListItem>
            <asp:ListItem Value="115">Unlambda (unlambda-2.0.0)</asp:ListItem>
            <asp:ListItem Value="101">Visual Basic .NET (mono-2.4.2.3)</asp:ListItem>
            <asp:ListItem Value="6">Whitespace (wspace 0.3)</asp:ListItem>
        </asp:DropDownList>
        <br /><br />
        Enter your code:
        <br />
        <br />
        <asp:TextBox ID="TextBox1" BorderColor="Black" runat="server" Height="131px" style="border:solid 1px" TextMode="MultiLine" Width="468px">using System;
            
  class Program
  {
      public static void Main(String[] args)
      {
        System.Console.WriteLine(&quot;Hello&quot;);
      }
  }
        </asp:TextBox>
        <br />
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Submit Code" OnClick="Button1_Click" />
        <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Show Result" Visible="False" />
        <br /><br />Code Output : <br />
        <asp:Label ID="Label1" Visible="false" runat="server" Text=""></asp:Label>
        <div style="background-color:#f3f0f0;font-size:13px">
            <asp:Label ID="outputLabel" runat="server" Text=""></asp:Label>
        </div>
        <div style="background-color:#f3f0f0;font-size:13px">
            <asp:Label ID="errorLabel" runat="server" Text=""></asp:Label>
        </div>
        <!-- Create a simple CodeMirror instance -->
        <link rel="stylesheet" href="lib/codemirror.css">
        <script src="lib/codemirror.js"></script>
        <script src="mode/clike/clike.js"></script>
        <script>
            var myTextArea = '<%=TextBox1.ClientID%>';
            var editor = CodeMirror.fromTextArea(document.getElementById(myTextArea), {
                //mode: { name: "xml", htmlMode: true },
                value: myTextArea.value,
                mode: { name: "text/x-csrc", htmlMode: true },
                lineNumbers: true,
                tabMode: "indent",
                matchBrackets: true,
                path: 'js/',
                searchMode: 'inline',
                onCursorActivity: function () {
                    editor.setLineClass(hlLine, null);
                    hlLine = editor.setLineClass(editor.getCursor().line, "activeline");
                },
               
            });
        </script>

    </form>



Step 2 : Create a web reference to the wsdl of IDEONE, i.e create a reference of http://ideone.com/api/1/service.wsdl in your project.




Step 3 : In the .cs code create an object that instantiate with this reference i.e

com.ideone.Ideone_Service_v1Service client = new com.ideone.Ideone_Service_v1Service();

Create a async task function which calls two functions

private async Task<bool> TestFunction()
        {
            var x = await initialize();
            var y = await showresult();
            return true;
        }

Create two functions, 1st one handles the code submission and checks the link returned by the service and second one actually process the data after sending the link to the service.

public async Task<string> initialize()
        {
            //Thanks to https://www.facebook.com/note.php?note_id=292105957920
            //Creating same page like http://labs.wedevs.com/compiler/

            Dictionary<string, string> result = new Dictionary<string, string>();
            Object[] ret = client.createSubmission("IDEONEUSERNAME", "IDEONEPASSWORD", TextBox1.Text, int.Parse(ddlLanguage.SelectedValue.ToString()), "", true, true);

            // filling result with data returned by testFunction
            foreach (object o in ret)
            {
                if (o is XmlElement)
                {
                    XmlNodeList x = ((XmlElement)o).ChildNodes;
                    result.Add(x.Item(0).InnerText, x.Item(1).InnerText);
                }
            }

            string link = "";

            // checking if everything went ok
            if ("OK" == result["error"])
            {
                string data = "";
                // printing result
                foreach (KeyValuePair<string, string> kvp in result)
                {
                    data = kvp.Key + " : " + kvp.Value;
                    if (kvp.Key == "link")
                        link = kvp.Value;
                }
                Label1.Text = link;
            }
            else
            {
                Label1.Text = "Error occured: " + result["error"];
            }
            return Label1.Text;
        }

        public async Task<string> showresult()
        {
            //Get the result of submission
            Dictionary<string, string> oresult = new Dictionary<string, string>();
            Object[] sresult = client.getSubmissionDetails("IDEONEUSER", "IDEONEPASSWORD", Label1.Text, true, true, true, true, true);
            foreach (object o in sresult)
            {
                if (o is XmlElement)
                {
                    XmlNodeList x = ((XmlElement)o).ChildNodes;
                    oresult.Add(x.Item(0).InnerText, x.Item(1).InnerText);
                }
            }

            outputLabel.Text = oresult["status"].ToString();

            if (int.Parse(oresult["status"]) == 0)
            {
                outputLabel.Text = oresult["output"].ToString();
                errorLabel.Text = oresult["stderr"].ToString() + " <br/>" + oresult["cmpinfo"].ToString();
            }
            else
            {
                GC.Collect();
                showresult();
            }
            return outputLabel.Text;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            outputLabel.Text = "";
            errorLabel.Text = "";
            TestFunction();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            //Get the result of submission
            Dictionary<string, string> oresult = new Dictionary<string, string>();
            Object[] sresult = client.getSubmissionDetails("IDEONE_User", "IDEONE_Password", Label1.Text, true, true, true, true, true);
            foreach (object o in sresult)
            {
                if (o is XmlElement)
                {
                    XmlNodeList x = ((XmlElement)o).ChildNodes;
                    oresult.Add(x.Item(0).InnerText, x.Item(1).InnerText);
                }
            }

            outputLabel.Text = oresult["status"].ToString();

            if (int.Parse(oresult["status"]) == 0)
            {
                outputLabel.Text = oresult["output"].ToString();
                errorLabel.Text = oresult["stderr"].ToString() + " <br/>" + oresult["cmpinfo"].ToString();
            }
            else
            {

            }
        }

Dropdown Selected Index Changed Event Creates a default code for the programming language selected.

protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            TextBox1.Text = "";
            Label1.Text = "";
            errorLabel.Text = "";
            outputLabel.Text = "";

            StringBuilder sb = new StringBuilder();
            if (int.Parse(ddlLanguage.SelectedValue.ToString()) == 27)
            {
                sb.Append("using System;");
                sb.Append("\n\nclass Program");
                sb.Append("\n{");
                sb.Append("\n\tpublic static void Main(String[] args)");
                sb.Append("\n\t{");
                sb.Append("\n\t\tSystem.Console.WriteLine(\"Hello\");");
                sb.Append("\n\t}");
                sb.Append("\n}");
                TextBox1.Text = sb.ToString();
            }
            else if (int.Parse(ddlLanguage.SelectedValue.ToString()) == 10)
            {
                sb.Append("\n\nclass Program");
                sb.Append("\n{");
                sb.Append("\n\tpublic static void main(String args[])");
                sb.Append("\n\t{");
                sb.Append("\n\t\tSystem.out.println(\"Hello\");");
                sb.Append("\n\t}");
                sb.Append("\n}");
                TextBox1.Text = sb.ToString();
            }
            else if (int.Parse(ddlLanguage.SelectedValue.ToString()) == 1)
            {
                sb.Append("\n\tint main()");
                sb.Append("\n\t{");
                sb.Append("\n\t\tcout<<\"Hello\";");
                sb.Append("\n\t\treturn 1;");
                sb.Append("\n\t}");
                TextBox1.Text = sb.ToString();
            }
            else if (int.Parse(ddlLanguage.SelectedValue.ToString()) == 11 || int.Parse(ddlLanguage.SelectedValue.ToString()) == 44)
            {
                sb.Append("\n\tint main()");
                sb.Append("\n\t{");
                sb.Append("\n\t\tprintf(\"%s\",\"Hello\");");
                sb.Append("\n\t\treturn 1;");
                sb.Append("\n\t}");
                TextBox1.Text = sb.ToString();
            }
        }

Hope this helps to all.

Thanks
Ritesh Tandon


9 comments:

Unknown said...
This comment has been removed by the author.
Unknown said...
This comment has been removed by the author.
Unknown said...

Where is this Button2_Click function ? Can you please help me find it out?

Ritesh said...

Hi Vibhanshu,

I have added the code of Button2_Click, Sorry for not adding it before.

Unknown said...

Thank you very much for the tutorial. I have used it as a part of my Asp.net project in 6th semester and has been successful in doing an important task.Thanks a lot.
I would request you to please provide any other details regarding it if you have. For example how to let the user add std input file while submitting.

Unknown said...

i need your help please let me know when u are available

Unknown said...

please, how i can get ideone API password ?

Ritesh said...

You can register with IDEOne and get the password.

Ritesh said...

Sorry for replying too too late, Let me know if its solved.

Post a Comment

Comments are welcome, Please join me on my Linked In account

http://in.linkedin.com/pub/ritesh-tandon/21/644/33b

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...