Introduction
Nowadays we are using more and more JavaScript in our web applications. Usually, we insert a link to the external JavaScript library into the ASPX code or just put some JavaScript code between <script>
tags. However, every so often for some reason (accessing it dynamically or some other important case), we need the JavaScript in our code behind (VB.NET or C#). That's where the pain begins. Those who have tried to do it understand me perfectly well. You put your neat piece of JavaScript into your nice VB.NET or C# code and start surrounding it with quotation marks, doubling them and looking for symbols to escape until all this becomes a dreadful mix that you don't want to look at anymore. The worst part is that your application is no longer working because of JavaScript errors. Looks familiar, doesn�t it?
I was trying hard to find a utility that would do all this for me and relieve me from this pain. However, it looked like such thing just didn't exist in the vast space of the internet or such was just my luck. So, I decided to create one myself. All the more, it didn't look like a very hard task.
Using the Code
This utility does all the formatting of your JavaScript code depending on which language you prefer, VB.NET or C#. All you need is to create a text file with your JavaScript code, select an output language and click a button. At the output, you will get a snippet of code that you can just insert into your page load method. Your JavaScript code, surrounded by <script>
tags, is now contained in the string variable and is registered with the page by the ClientScript.RegisterStartupScript
method. For your convenience, all generated code may be copied into the clipboard.
Points of Interest
In order to do the job, the Streamreader
class is used to read the text file:
Dim objReader As StreamReader
Try
objReader = New StreamReader(txtFile.Text)
strContents = objReader.ReadToEnd()
objReader.Close()
Catch Ex As Exception
MessageBox.Show(Ex.Message)
End Try
Then the StringBuilder
class methods perform all the needed operations to save and transform the strings, such as dealing with quotation marks in the text depending on the output language, constructing valid VB or C# statements and so on.
str(i) = str(i).Replace("""", """""")
str(i) = str(i).TrimEnd(Chr(13))
If vb Then
sb.Append("sb.Append(""")
Else
sb.Append("sb.Append(@""")
End If
sb.Append(str(i))
sb.Append(""")")
If Not vb Then
sb.Append(";")
End If
To copy the generated code snippet into the clipboard, I'm using a Clipboard
class:
Clipboard.Clear()
If txtResult.Text.Trim.Length > 0 Then
Clipboard.SetText(txtResult.Text)
End If
That's basically all about it. You see, it was not very hard to create the utility which hopefully saves your precious time. Let's do something more interesting and less boring than formatting JavaScripts to use in our code!
History
- 3 December, 2007 -- Original version posted