Chris Carter's Web Log

I'm playing around with some different techniques of generating javascript with C#.  No, I'm not creating my own Script#; which, by the way, i think it should be a rule that no one should be allowed to host software on codeplex without providing the sourcecode-see here for the script # source code - ya, there's nothing there, soooo lame.  Here's some code I need to generate for various reasons from C#:

function save(){
  if ($F('Name').replace(/ /,'').length == 0){
    alert('Please enter the name.');
    $('Name').activate();
    return;
  }
}

StringBuilder

Anywho.how do you generate javascript through code? StringBuilder? OK.  But that usually means alot of typing and is error prone.  Also it can be hard to read. Here's one way of using the StringBuilder:  The problem with this is that your have to remember to include the tab characters and the end of line characters, which is annoying, i don't want to have to remember that crap.

StringBuilder js = new StringBuilder();
js.Append("function save(){\r\n");
js.Append("\tif ($F('Name').replace(/ /,'').length == 0){\r\n");
js.Append("\t\talert('Please enter the name of the project.');\r\n");
js.Append("\t\t$('Name').activate();\r\n");
js.Append("\t\treturn;\r\n");
js.Append("\t}\r\n");
js.Append("}\r\n");

StringWriter

Here's a StringWriter example.  We've excluded end of line characters but still have the stupid tab characters, lame.

using (StringWriter js = new StringWriter())
{
  js.WriteLine("function save(){");
  js.WriteLine("\tif ($F('Name').replace(/ /,'').length == 0){");
  js.WriteLine("\t\talert('Please enter the name of the project.');");
  js.WriteLine("\t\t$('Name').activate();");
  js.WriteLine("\t\treturn;");
  js.WriteLine("\t}");
  js.WriteLine("}");
}

ScriptWriter

Ya, stoopid name, but this is my attempt at eliminating the need handle formatting myself and end of line characters, as well as semi colons at the end of javascript lines(yes, not required but I prefer them), and curly braces in their appropriate places.

using (ScriptWriter script = new ScriptWriter())
{
  script.CreateBlock("function save()");
  script.CreateBlock("if ($F('Name').replace(/ /,'').length == 0)");
  script.WriteLine("alert('Please enter the name of the project.')");
  script.WriteLine("$('Name').activate()");
  script.WriteLine("return");
}

CreateBlock notifies the code that we're going to basically indent and create a new block of code that's surrounded by a statement and open and close braces.  I started going down the path of creating code nodes, similar to the CodeDom, like here's a block, and it contains lines, some of the lines are other blocks, etc.  But that didn't feel right, actually it felt like I was trying to recreate the javascript dom.  ScriptWriter doesn't feel super comfortable right now either, but this is a first stab.

Click here to view the source.

 
Author: , 0000-00-00