Using Javascript for Google Maps API from WPF - c#

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());

Related

Opening a Silverlight Window From Javascript and passing an object

I am looking for a way to open my silverlight application from my web application using javascript. I will also need to pass a string to the silverlight application during this process. The code below will currently open the silverlight application for me. I need to know how to do this while passing in the string value to silverlight.
$(function () {
$('.cell').on('focus', 'textarea', function () {
var inputValue = $(this).val();
window.open('/TestPage.aspx');
});
});
Note: I have searched everywhere for the answer to this and cant seem to find a decent solution. All of the demos I've found are incomplete or do not function as expected.
You could pass it in the query string:
window.open('/TestPage.aspx?input=' + inputValue);
Retrieve it in Silverlight using HtmlDocument.QueryString:
string inputValue = null;
if (HtmlDocument.QueryString.ContainsKey("input"))
inputValue = HtmlDocument.QueryString["input"];

dynamically evaluating javascript expressions in winrt/xaml/c# applications

Is there a way of evaluating javascript expressions, which are loaded from an external source at runtime, in a winrt application written in XAML and c#?
Consider the following pseudo-code:
String expression = File.ReadAll(somefile);
String result = AnyJavascriptEngineAvailableUnderWinRT.Evaluate(expression);
before winrt, we have been using Microsoft.JScript engine.
Now, with winrt, we have been trying Jint, which led to runtime exception "The API 'System.Type.ReflectionOnlyGetType(System.String, Boolean, Boolean)' cannot be used on the current platform. See http://go.microsoft.com/fwlink/?LinkId=248273 for more information."
To be honest, I would prefer addressing the built-in javascript engine coming with winrt, but I would also accept "AnyJavascriptEngineAvailableUnderWinRT", if it allows expressions to be evaluated dynamically.
You can do this easily by tapping into IE directly through the WebView.
Like this:
var js = "whatever you want";
var webView = new WebView();
var result = webView.InvokeScript("eval", new[] { js });
Best of luck!

emulating a browser programmatically in C# / .Net

We would like to automate certain tasks in a website, like having a user 'login', perform some functionality, read their account history etc.
We have tried emulating this with normal POST/GETs, however the problem is that for example for 'login', the website uses javascript code to execute an AJAX call, and also generate some random tokens.
Is it possible to literally emulate a web-browser? For example:
Visit 'www.[test-website].com'
Fill in these DOM items
DOM item 'username' fill in with 'testuser'
DOM item 'password' fill in with 'testpass'
Click' button DOM item 'btnSubmit'
Visit account history
Read HTML (So we can parse information about each distinct history item)
...
The above could be translated into say the below sample code:
var browser = new Browser();
var pageHomepage = browser.Load("www.test-domain.com");
pageHomepage.DOM.GetField("username").SetValue("testUser");
pageHomepage.DOM.GetField("password").SetValue("testPass");
pageHomepage.DOM.GetField("btnSubmit").Click();
var pageAccountHistory = browser.Load("www.test-domain.com/account-history/");
var html = pageAccountHistory.GetHtml();
var historyItems = parseHistoryItems(html);
You could use for example Selenium in C#. There is a good tutorial: Data Driven Testing Using Selenium (webdriver) in C#.
I would suggest to instantiate a WebBrowser control in code and do all your work with this instance but never show it on any form. I've done this several times and it works pretty good. The only flaw is that it makes use of the Internet Explorer ;-)
Try JMeter, it is a nice too for automating web requests, also quite popularly used for performance testing of web sites
Or just try System.Windows.Forms.WebBrowser, for example:
this.webBrowser1.Navigate("http://games.powernet.com.ru/login");
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
HtmlDocument doc = webBrowser1.Document;
HtmlElement elem1 = doc.GetElementById("login");
elem1.Focus();
elem1.InnerText = "login";
HtmlElement elem2 = doc.GetElementById("pass");
elem2.Focus();
elem2.InnerText = "pass";

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.

Generating JavaScript in C# and subsequent testing

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.

Categories

Resources