Accessing C# function in Javascript - c#

I think there is something that I don't understand as I proceed forward in my project of importing D3 visuals into Spotfire.
I currently have implemented a D3 visualization into Spotfire by using Awesomium's embedded browser and these lines:
string myString = System.IO.File.ReadAllText(#"C:\Users\leear\Desktop\SDK\SDK\Examples\Extensions\D3Visualizations\Gauge.html");
webView.LoadHTML(myString);
The HTML of Gauge.html contains javascript code that runs all the necessary things to create the visualization.
However, I want to be able to access/run C# functions and variables inside the Gauge.html file. I am envisioning something like this:
for (var value in <%=Spotfire.getCurrentColumn()%>) {gauge.redraw(value)}
My project is currently structured just for the C# code to read and write all the HTML from a file into Awesomium's embedded browser.
How would I do this? Where does aspx.NET fit into this, if at all?
Thanks

You can't; javascript is client-side, and ASP.NET is server side. ASP.NET basically generates HTML and javascript, and once that rendering is done the page is processed the client-side takes over, which it knows nothing of ASP.NET. It's perfectly fine for ASP.NET to spit out JS becuase it's RENDERING it, but the client-side PROCESSING of JS, which is where you are trying to call a server-side method knows nothing of ASP.NET. You'd have to move the logic to the client, or have the client talk to the server using javascript.
I can't advise further as I don't know what that method does.

"You can't; javascript is client-side, and ASP.NET is server side. ASP.NET basically generates HTML and javascript"....
This is absolutely correct. Client and server are two different worlds...
You have a couple of options if you need to get code-reuse.
Look into a C# to javascript compiler..and make sure your C# functions don't depend on anything related to the server or its runtime.
Otherwise, consider exposing your server functionality as a web service that takes input of some form and returns output as JSON for use on the client side.

Related

How does Microsoft Razor Syntax run server side code without exposing it to the client?

I am having trouble wrapping my head around how Razor syntax works.
It is my understanding that it will allow you to embed server-side code directly into the page, but it keeps all of that from the client even though the client can interact with it.
I'm used to ASP.net web views and things of that nature - does the Razor syntax essentially do postbacks and all of the code is contained within the page, or is the way that the client interacts with the server-side code fundamentally different?
If this is too open-ended, please leave me comments as to how to focus the question more. I fear I don't yet understand enough to make finely-focused questions.
Thanks!
From my understanding:
1. How Razor syntax works:
You can see the Razor is similar to the scriplet in Web Form. For example, you want to get the Name of the Human class, in .cshtml file, you write:
<div>Name is #Model.Name</div>
And in aspx, you write:
<div>Name is <%= Human.Name %></div>
Both Razor and scriplet will be processed before returning the HTML files to client. Follow the above example, if you view the source of your HTML web page, you will see (Forte is just an example):
<div>Name is Forte</div>
Because the code was processed, so, what the client see is the HTML result only.
2.How do clients interact with server?
In Web Form, when you want to go to server (like handle click button event), you can generate the function to call by set OnClickListener for the button, and everything is done automatically for you.
However, in MVC.NET, you have to do it through Ajax call, or put your button in a <form>.
If you have any question, feel free to let me know :)
mvc runs all that stuff server side and provides the client with the resulting html/javascript generation.
Lets say you have this in a view
#{ var var1 = "Hello World"; }
<p>The value of var1 is: #var1</p>
Everything happens on the server
When a user is requesting this page the server gets the text above and sends it to the view engine.
Then the server runs the text line by line and "compiles" it.
Then the server snds the result back to the user:
The value of var1 is: Hello World
If the user makes a view source he will see only:
<p>The value of myMessage is: Hello World</p>
So the user on the client writes a simple URL , and the result he is getting is ONLY the line above.
Essentially it compiles the view like any other csharp/vb.net file. However, it does it on-the-fly (the first time you hit it, and the underlying file hasn't changed).
If you want to see what the generated code looks like, take a look at https://github.com/RazorGenerator/RazorGenerator This allows you to actually generate the same code as part of MSbuild and deploy it.

Localizing JavaScript strings in an ASP.NET Web Forms application

One of the apps I work on is a large ASP.NET 3.5 Web Forms app that is used in the U.S., Central and South Americas, and Europe. We're also starting to do more work with AJAX, and thus we need to settle on a strategy for localizing strings in our JavaScript controls.
For example, we have a control written as a jQuery plugin that formats data into a sortable table. The buttons and table columns need to be localizable.
We're currently using two different approaches to handle this scenario, but I'm not completely satisfied with either.
Write the bulk of the code in a jQuery plugin style, then place a script block on the .aspx page where we'll pull in values from a .resx file and feed them into the plugin code. Here's an example in pseudo code:
<script>
var view;
$(function() {
view = {
columnHeaders: {
productNumber = <%$ Resources:WidgetProductNumber_HeaderText %>,
productDescription = <%$ Resources:WidgetProductDescription_HeaderText %>
}
};
});
</script>
Place the JavaScript in plain .js files with custom tokens in place of strings. We have a handrolled HttpModule that will parse JavaScript files and replace the tokens with values from any existing .resx file whose file name matches the name of the JavaScript file being processed.
Both approaches have problems. I'd prefer to keep our JavaScript code separate from our .aspx pages to make it more unobtrusive and reusable.
The HttpModule approach is clever but a little opaque to developers. I'm also looking to implement a JavaScript bundler called Rejuicer, which is also written as an HttpModule, and getting these to work together seems like it would require customizing the open source code. I'd prefer to use the code as it's written so that we can upgrade it as the project progresses.
Are there any other tried-and-true strategies for approaching this problem in ASP.NET?
It seems that both approaches are a little more complex/cumbersome than necessary. Keep it simple.
1) Using an .ashx, custom http handler, or web service, create a .net object (anonymous, custom -- doesn't matter) that matches the client side JSON object.
2) Populate server side object's properties with the localized values
3) Set the response content type to text/json or text/javascript.
4) Using the JavaScriptSerializer class, serialize the object into the response stream.
From the client side, you have two options:
1) Use an AJAX call to the .ashx/handler/service to set your client side "view" object to the response JSON.
2) Create a script tag with the src="the/path/to/the/serviceOrHandler". In this case you would need to include the js variable declaration in your response output.
Let me know if you need a code sample.
I just stumbled onto this question, and I have another answer to throw into the ring. It isn't my work or anything, but it looks like a fairly elegant solution. It involves writing a localization handler to serve up ASP.NET resources to Javascript. Here are a couple of links:
http://weblog.west-wind.com/posts/2009/Apr/02/A-Localization-Handler-to-serve-ASPNET-Resources-to-JavaScript
http://www.tikalk.com/use-aspnet-resource-strings-within-javascript-files/

Update a field from server without reloading the existing page using simple javascript

I want to change a value of a field say document.getElementById('reloader').innerHTML = updated value from Server
I do not want to use Ajax, PHP, ASP, JSP .. or anything like these.
Is it possible by using simple javascript?
Server is C# 's application made by using HttpListener.
Please question if needed more info.
You can't do it without using something like AJAX, unless you're willing to update the entire page. Somehow, the browser has to contact the server, trigger an action there, and receive and process the response.
Thus, you can use XMLHttpRequest, or you could use JSONP or something similar. In any case something has to be written on the server to respond to the request and supply the data, and that's not going to be "simple Javascript" unless you've got a server-side Javascript solution (which is not impossible of course, but probably unlikely).
I am not sure why you dont want to use Ajax. But i believe the only other workaround then can be use an iframe on your page point to the server script and write javascript to read it. I havent tried it recently but i believe it should work

How to inspect an element in c# like firebug does?

Is there a way to inspect/spy elements in a web browser like firebug does when we move the mouse over the webpage? How to to it in c#??
EDIT:
Actually I just want to get the HTML source code from the tagged element.
Best regards.
Asp.Net framework uses "HTMLTextWriter" class to generate the HTMl markup for server controls.If say for example , you want the HTML markup for gridview control , then you can make use of this class and its associated member functions to get the markup.But again its all a part of server side logic and achieving the same through client side code is not that easy.If you can provide more information on whats the exact requirement then it will be quiet nice.
You cannot interrogate dynamically the client side rendering of a server side control via the browser. There is a disconnect between the server and client side that it maintained through the .Net viewstate model. You can generally tell which DOM elements have been generated via server side code through the ID having an extended value but this is not any guarantee etc. In .Net 4.0 the client side IDs will be able to be set via the server side so even this is tenuous.
As James has said, you should use firebug to determine the output on the client side and then tailor your server side rendering accordingly.
Can you provide a more detailed example of what you are trying to achieve and perhaps there is a further solution / explanation that can be offered?

Parsing HTML generated from Legacy ASP Application to create ASP.NET 2.0 Pages

One of my friends is working on having a good solution to generate aspx pages, out of html pages generated from a legacy asp application.
The idea is to run the legacy app, capture html output, clean the html using some tool (say HtmlTidy) and parse it/transform it to aspx, (using Xslt or a custom tool) so that existing html elements, divs, images, styles etc gets converted neatly to an aspx page (too much ;) ).
Any existing tools/scripts/utilities to do the same?
Here's what you do.
Define what the legacy app is supposed to do. Write down the scenarios of getting pages, posting forms, navigating, etc.
Write unit test-like scripts for the various scenarios.
Use the Python HTTP client library to exercise the legacy app in your various scripts.
If your scripts work, you (a) actually understand the legacy app, (b) can make it do the various things it's supposed to do, and (c) you can reliably capture the HTML response pages.
Update your scripts to capture the HTML responses.
You have the pages. Now you can think about what you need for your ASPX pages.
Edit the HTML by hand to make it into ASPX.
Write something that uses Beautiful Soup to massage the HTML into a form suitable for ASPX. This might be some replacement of text or tags with <asp:... tags.
Create some other, more useful data structure out of the HTML -- one that reflects the structure and meaning of the pages, not just the HTML tags. Generate the ASPX pages from that more useful structure.
Just found HTML agility pack to be useful enough, as they understand C# better than python.
I know this is an old question, but in a similar situation (50k+ legacy ASP pages that need to display in a .NET framework), I did the following.
Created a rewrite engine (HttpModule) which catches all incoming requests and looks for anything that is from the old site.
(in a separate class - keep things organized!) use WebClient or HttpRequest, etc to open a connection to the old server and download the rendered HTML.
Use the HTML agility toolkit (very slick) to extract the content that I'm interested in - in our case, this is always inside if a div with the class "bdy".
Throw this into a cache - a SQL table in this example.
Each hit checks the cache and either a)retrieves the page and builds the cache entry, or b) just gets the page from the cache.
An aspx page built specifically for displaying legacy content receives the rewrite request and displays the relevant content from the legacy page inside of an asp literal control.
The cache is there for performance - since the first request for a given page has a minimum of two hits - one from the browser to the new server, one from the new server to the old server - I store cachable data on the new server so that subsequent requests don't have to go back to the old server. We also cache images, css, scripts, etc.
It gets messy when you have to handle forms, cookies, etc, but these can all be stored in your cache and passed through to the old server with each request if necessary. I also store content expiration dates and other headers that I get back from the legacy server and am sure to pass those back to the browser when rendering the cached page. Just remember to take as content-agnostic an approach as possible. You're effectively building an in-page web proxy that lets IIS render old ASP the way it wants, and manipulating the output.
Works very well - I have all of the old pages working seamlessly within our ASP.NET app. This saved us a solid year of development time that would have been required if we had to touch every legacy asp page.
Good luck!

Categories