Generating JavaScript in C# and subsequent testing - c#

We are currently developing an ASP.NET MVC application which makes heavy use of attribute-based metadata to drive the generation of JavaScript.
Below is a sample of the type of methods we are writing:
function string GetJavascript<T>(string javascriptPresentationFunctionName,
string inputId,
T model)
{
return #"function updateFormInputs(value){
$('#" + inputId + #"_SelectedItemState').val(value);
$('#" + inputId + #"_Presentation').val(value);
}
function clearInputs(){
" + helper.ClearHiddenInputs<T>(model) + #"
updateFormInputs('');
}
function handleJson(json){
clearInputs();
" + helper.UpdateHiddenInputsWithJson<T>("json", model) + #"
updateFormInputs(" + javascriptPresentationFunctionName + #"());
" + model.GetCallBackFunctionForJavascript("json") + #"
}";
}
This method generates some boilerplace and hands off to various other methods which return strings. The whole lot is then returned as a string and written to the output.
The question(s) I have are:
1) Is there a nicer way to do this other than using large string blocks?
We've considered using a StringBuilder or the Response Stream but it seems quite 'noisy'. Using string.format starts to become difficult to comprehend.
2) How would you go about unit testing this code? It seems a little amateur just doing a string comparison looking for particular output in the string.
3) What about actually testing the eventual JavaScript output?
Thanks for your input!

We created a library specifically for the purpose of embedding JavaScript in a fluent-like syntax into our C# code, and then made it open source.
Have a look at Adam.JSGenerator.

I typically try to create a separate .js file for most/all of my javascript code. Usually I will need to have common bahvior applied to many elements that are dynamically created by ASP controls or server-side code, so I may not be able to code everything into a .js file.
I've found that the main reason that you want to generate javascript on the server is because you won't know the IDs of elements until the page renders. Therefore, I try to condense that dependency down as much as possibly so that I'm generating as little javascript as possible. For example, in traditional ASP.Net (not MVC) if I were rendering a set of forms such as in the example, each with multiple fields, then I would probably have something in the code behind such as this:
protected void FormRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Control form = e.Item.FindControl("MyForm");
ClientScript.RegisterStartupScript(this.GetType(), "prepareForm_" + form.ClientID, #"prepareForm('" + form.ClientID + "');", true);
}
A separate .js file would include the definition of the prepareForm function, which would be something like this:
// define a formPresenter "class" that encapsulates the behavior for a given form
function formPresenter(formId) {
this.setFirstName = function(value) {
$("#" + formId + "_FirstName").val(value);
}
this.setLastName = function(value) {
$("#" + formId + "_LastName").val(value);
}
// create other functions to handle more complicated logic
// clear fields
this.clearInputs = function() {
this.setFirstName("");
this.setLastName("");
//...
}
// receive Json object
this.handleJson = function(json) {
this.clearInputs();
// populate fields with json object
this.setFirstName(json.FirstName);
this.setLastName(json.LastName);
//...
}
// "constructor" logic
}
function prepareForm(formId) {
// create a new formPresenter object and shove it onto the specified element as the "presenter"
document.getElementById(formId).presenter = new formPresenter(formId);
}
Now almost all of your actual logic is in its own .js file, which should be much easier to maintain. If you need to access the formPresenter object for a given form, then you just need to get a reference to whatever element is referenced by the formId parameter and access the presenter variable:
"document.getElementById(" + form.ClientID + ").presenter.handleJson(json);"
Note: Since I've been using JQuery, I've found less of a need to even include any javascript generated by the server. Typically I can find the elements that I need by looking for a specific CSS class name (or something to that effect) and perform whatever setup/initialization I need.

We're doing a lot of JS generation in our project as well, and we're using StringBuilder to do it.
StringBuilder sb = new StringBuilder();
sb.Append("some javascript stuff")
.Append("some more")
.AppendFormat("formatted stuff {0}", "here");
return sb.ToString();
It's not pretty, but no solution is going to be.
And concerning testing, we don't actually do any unit tests on the generated code. Before release people go and test all the features to make sure they work as expected.

If you don't care about super duper performance you could use a templating language to generate the javascript.
Then for unit testing you would just fill the templates with their appropriate bindings/variables and then run it through a Javascript evaluator like Rhino or whatever the .NET equivalent is to at least test the syntax if not the actual JS code.
Other than that I would seriously question the design of software that is generating Javascript like this. It also looks like you are using JQuery but are referencing the $ directly which may lead to some problems down the line.
If compilers generating Javascript is one thing (ala GWT) but I would separate your client side JS code as much as possible from your .NET code (not to mention your .NET code looks like server side JS talk about confusing).
This in vogue kind of design of separating the client crap from the server is known as SOFEA. I let you google that.

Related

Sending message to user using selenium

I have over 100 tests to do .
For every test i need to show the title of testcase,
I cannot use MessageBox because it stops the tests, i need just to show a popup that contains the title and after 2 sec disappears.
I am using Selenium test drive for a web application and c#
You can enable logging . This will give clear picture about this.
https://www.seleniumeasy.com/testng-tutorials/logging-with-testng-using-listeners
Workaround at best without changing page DOM. How about writing to a html file with the test case name when each test starts in the title tag. Setup a refresh meta-tag with a time of 1-2 secs. Open up the html as a separate window and it keeps on refreshing on its own.
What about injecting html via javascript to your page at the beginning of every test?
I dont know the C# syntax, here's an idea how it may look in java:
((JavascriptExecutor) driver).executeScript( "document.body.appendChild( document.createTextNode( \"" + testName + "\") );" );
Depending on if you reuse your browser across tests, you might need an element something you can clean up after the test.
Or, just change the page title
((JavascriptExecutor) driver).executeScript( "document.title = \"" + testName + "\";" );
Just make sure you choose a way that doesn't interfere with the tests themselves.
But, what I'd really like to suggest is to look into ways of getting more confidence in your automation. If there are reasons for you to manually need to look at what your automation is doing.. that just doesn't sound optimal..

How to fix Veracode error for InnerHtml

When running Veracode, it generated a bunch of errors pointing to the lines with InnerHtml.
For example, one of those lines is:
objUL.InnerHtml += "<tr><td></td><td class=\"libraryEdit\">" + HttpUtility.HtmlEncode(dtitems.Rows[currentitem]["content"].ToString()) + "</td>";
What do alternatives exist to fix it without using html server controls?
What exactly are you trying to do, and what exactly does Veracode say?
Most likely, it is complaining that you could end up with an arbitrary code injection vulnerability if the data passed into your InnerHtml is untrusted and could contain malicious JavaScript.
The tool may not complain if you manually construct the DOM elements using the JavaScript createElement function to build each DOM element manually.
I have faced this issue in my ASP.NET Webforms application. The fix to this is relatively simple.
Install HtmlSanitizationLibrary from NuGet Package Manager and refer this in your application.
At the code behind, please use the sanitizer class in the following way.
For example if the current code looks something like this,
YourHtmlElement.InnerHtml = "Your HTML content" ;
Then, replace this with the following:
string unsafeHtml = "Your HTML content";
YourHtmlElement.InnerHtml = Sanitizer.GetSafeHtml(unsafeHtml);
This fix will remove the Veracode vulnerability and make sure that the string gets rendered as HTML. Encoding the string at code behind will render it as 'un-encoded string' rather than RAW HTML as it is encoded before the render begins.

Using Javascript for Google Maps API from WPF

I am creating an application that interfaces with Google's Maps API v3. My current approach is using a WebBrowser control by WebBrowser.Navigate("Map.html"). This is working correctly at the moment; however, I am also aware of WebBrowser.InvokeScript(). I have seen this used to execute a javascript function, but I would like to have something like the following structure:
APICalls.js - Contains different functions that can be called, or even separated out into a file for each function if necessary.
MapInterface.cs
WebBrowser.InvokeScript("APICalls.js", args) - Or control the javascript variables directly.
I have seen the InvokeScript method used, but none of the examples gave any detail to the source of the function, so I'm not sure if it was calling it from an html file or js file. Is it possible to have a structure like this, or a similarly organized structure, rather than creating an html file with javascript in each one and using Navigate()?
Additionally, are there any easier ways to use Google Maps with WPF. I checked around, but all of the resources I found were at least 2-3 years old, which I believe is older than the newest version of the maps API.
I can't suggest a better way of using Google Maps API with WPF (although I'm sure it exists), but I can try to answer the rest of the question.
First, make sure to enable FEATURE_BROWSER_EMULATION for your WebBrowser app, so Google Maps API recognizes is it as modern HTML5-capable browser.
Then, navigate to your "Map.html" page and let it finish loading. Here's how it can be done using async/await (the code is for the WinForms version of WebBrowser control, but the concept remains the same).
You can have your APICalls.js as a separate local file, but you'd need to create and populate a <script> element for it from C#. You do it once for the session.
Example:
var scriptText = File.ReadAllText("APICalls.js");
dynamic htmlDocument = webBrowser.Document;
var script = htmlDocument.createElement("script");
script.type = "text/javascript";
script.appendChild(htmlDocument.createTextNode(scriptText));
htmlDocument.body.appendChild(script);
Then you can call functions from this script in a few different ways.
For example, your JavaScript entry point function in APICalls.js may look like this:
(function() {
window.callMeFromCsharp = function(arg1, arg2) {
window.alert(arg1 + ", " +arg2);
}
})();
Which you could call from C# like this:
webBrowser.InvokeScript("callMeFromCsharp", "Hello", "World!");
[UPDATE] If you're looking for a bit more modular or object-oriented approach, you can utilize the dynamic feature of C#. Example:
JavaScript:
(function() {
window.apiObject = function() {
return {
property: "I'm a property",
Method1: function(arg) { alert("I'm method 1, " + arg); },
Method2: function() { return "I'm method 2"; }
};
}
})();
C#:
dynamic apiObject = webBrowser.InvokeScript("apiObject");
string property = apiObject.property;
MessageBox.Show(property);
apiObject.Method1("Hello!");
MessageBox.Show(apiObject.Method2());

Calling javascript from codebehind c# & Asp.Net

Am unable to understand why Cannot the below javascript code is not called from code behind
I have a simple javascript block like this
function callsCox(res) {
alert(res);
}
From my code behind :
....
string res="COX23";
string script = String.Format("callsCox({0})", res);
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Cox",script,true);
Am I missing anything? There aren't any exceptions or errors.
Page.ClientScript.RegisterStartupScript looks OK to me (might have missed something). Things to try
Add apostrophes to the call - it's coming through as an object. Try as a string
string script = String.Format("callsCox('{0}')", res);
Is the string script Page.ClientScript.RegisterStartupScript being called after an update panel partial postback. That could effect it
I have know functions not been found if they are in the same page. Try moving to an external js file. Don't asked me why this has resolved issues but it has a couple of times in the past for me.
Just for debug purposes take the function out of the equation all together, Try to get the alert working like this. It will at least isolate the problem if it does work
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Cox","alert('Does this work?')",true);
View the source of the page. Is the function even written into the page (or alert from point 4). It should be. If you put a breakpoint on the this.Page.ClientScript.RegisterStartupScript method is it being hit? Seems like it might not be.
Apologies for not giving you a 'hey this is the solution' type of answer. I've had stuff like this in the past and I've found it a matter of stripping things down until the problem has been isolated. Someone else may be able to spot an immediate problem of course. Good luck.
This works for me:
public static void ShowAlert(Page page, String message)
{
String Output;
Output = String.Format("alert('{0}');",message);
page.ClientScript.RegisterStartupScript(page.GetType(), "Key", Output, true);
}

ASP.NET MVC Html Helper Extensions and Rendering Their Required "include"s

I have build a custom Html Helper extension as follows:
public static string DatePicker(this HtmlHelper helper, string name, string value)
{
return string.Format(#"<script type='text/javascript'>
$(document).ready(function(){{
$('#{0}').datepicker({{
changeMonth: true,
changeYear:true,
dateFormat: 'd-M-yy',
firstDay: 1, showButtonPanel:
true,
showWeek: true
}});
}});
</script>
<input type='text' name='{0}' id='{0}' value='{1}'>", name, value);
}
The problem is that this now requires the page to "include" the following:
<script src="/Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.ui.datepicker.min.js" type="text/javascript"></script>
And a few other items. The questions are as follows:
Is there a serious processing
overhead if I were to include these
items in EVERY page (like in the
Site.Master for example) thus
negating the need for the HtmlHelper
to organise the "includes" -
considering there would end up being
about 20 includes for all the
different types of jQuery UI widgets
used throughout the site.
If the HtmlHelper sorts out the
"includes", it will add one every
time this DatePicker is used (often
there are two on a page) Does anyone
have a way of determining whether or
not the user has already rendered
the same type of control on the
page, thus not re-including the same
jquery libraries when multiple
instances of the DatePicker (for
example) are used?
Direct Answer
1) Yes 20 requests for scripts on each page will reduce performance for clients considerably - see Yahoo / Google's docs on web optimisation for more info
Browser Caching helps, but its so easy to do better.
2) Why roll your own solution to dependencies?
There are numerous excellent libraries out there that do this very well already - with advantages?
In depth :
Similar to the suggestion from #Mare , but with I think some decent advantages - I would recommend changing your approach slightly. Refactor !
Consider these core questions :
1) Why write HTML in .cs files?
=> much better to keep your HTML in aspx / ascx (or other view engine) files
check out editor and display templates e.g.
Brad Wilson's Intro to templates
i.e. comment from #admsteck above
2) why write Javascript in .cs files?
=> much better to keep your Javascript in .js files
3) Also note - Why use HtmlHelper extension methods when you are not using any of the state information from the HtmlHelper class?
=> For a simple solution why not instead just use a static helper class (not an extension of HtmlHelper) see this answer here
But mainly :
4) If you a concerned about performance, why not minify and combine all your scripts (and CSS while you're at it).
=>Then you can have a single little CSS file and a single JS file for your whole app.
However, 4) then leads to some further questions :
a) How do you debug combined + minified JS
b) How do you work effectively with combined + "minified" CSS?
c) To focus back in on your original request for a clean way to handle dependencies, how do you ensure its clear what code depends on what code, and how do you ensure code is requested only once when its needed?
I have found that this open source library Client Dependency Framework an excellent addition to my toolbox for MVC, when you debug you get individual files, when you run you get combined files (for massive performance gains in production).
It also provides an excellent way for your UI components to "register" their dependencies, so its clear to developers what is needed where, and so the correct js + the correct css gets down to the client (and only gets requested once) !
Maybe something of these code pieces will help you to get an idea or two about it:
private static readonly SortedList<int, string> _registeredScriptIncludes = new SortedList<int, string>();
public static void RegisterScriptInclude(this HtmlHelper htmlhelper, string script)
{
if (!_registeredScriptIncludes.ContainsValue(script))
{
_registeredScriptIncludes.Add(_registeredScriptIncludes.Count, script);
}
}
public static string RenderScript(this HtmlHelper htmlhelper, string script)
{
var scripts = new StringBuilder();
scripts.AppendLine("<script src='" + script + "' type='text/javascript'></script>");
return scripts.ToString();
}
public static string RenderScripts(this HtmlHelper htmlhelper)
{
var scripts = new StringBuilder();
scripts.AppendLine("<!-- Rendering registered script includes -->");
foreach (string script in _registeredScriptIncludes.Values)
{
scripts.AppendLine("<script src='" + script + "' type='text/javascript'></script>");
}
return scripts.ToString();
}
To answer number 2, you could do something like the following
<script type='text/javascript'>
if (typeof jQuery == 'undefined') // test to see if the jQuery function is defined
document.write("<script type='text/javascript' src='jquery.js'></script>");
</script>
Regarding:
1: no processing overhead at all, and no significant size overhead (as in: the files are normally loaded only first time by the browser). I normally would go this approach.
2: no idea, sorry ;) Someone else will pick that up, i think.

Categories

Resources