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/
Related
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.
I am updating my ASP.NET project to use some more JavaScript and AJAX. I’ve refactored parts of my HTML so that they are created with JavaScript, but now I’m not able to use the values of my local resource files anymore.
The structure of my project is that each page/usercontrol has it’s own set of local resources and it’s own set of .js files.
Is there a simple/elegant solution to use the local resources in JavaScript?
Preferably I would like to see something that takes the myfile.js file, parses it by looking at the current language, and outputs something myfile.en.js
UPDATE
How I’d like to work:
<script src="../message.js"></script>
function showMessage(){
alert(GetLocalResource("AlertMessage"));
}
Yes. Create an Controller, or ApiController that reads the resources from your folder or resx file.
To read from a resx file, use ResourceManager
There are plenty examples online for the general structure. Like this one: Display image from database in asp mvc. Of course, you could use this not only for images, but any type of file.
You can map an incoming parameter, like filename the way you want, and you can post-process it to replace things if you need to. You can also set some HTTP headers to handle caching.
In my case, I found that converting RESX files into JSON files and then loading them in the client-side JavaScript works good.
Since RESX is XML, using LINQ-to-XML you'll convert each node into a key and each value into the key value:
{ "myLabel": "hello world!" }
Now the problem will be loading the right resources for user's culture. If you use a convention like RESX and files are called like MyResources.en-US.json, if you write a cookie with current user's culture, it's just about concatenating it as follows: "MyResources." + cultureCookieValue + ".json"
Finally, you might use jQuery to load the whole resources:
$.getJSON("/JsonResources/MyResources." + cultureCookieValue + .json").done(function(resources) {
var myLabel = resources.myLabel;
});
This is just the idea. Now, if you develop it, you may create some abstractions so your client-side code can access such resources using this approach.
Suggestion: You can convert RESX on build using MSBuild!
Here is an example on how to write your own Http Handler to create minified JavaScript on the fly. Perhaps you can extend this with translation options and output not only minified, but also translated files.
http://weboptimizer.codeplex.com/
I want to provide an autocomplete option for a text in my web applciation . I have the master data in the SQL server database table. I beowsed in google and found how to use autocomplte. all the examples use web service to do this. I cannot create a web service to impltement this. Is it possible to implement autocomplete by looking up values from database in code behind ? If so any one can provide any sample links for reference ?
Thanks in advance,
Jebli
It depends on the volume of data. There are 2 options:
send it to the client pre-emptively (perhaps as json or html) in the page source
let the client query it based on their input
The second is common if the data-volume is non-trivial, as you can query when (for example) they've entered 3 characters; very useful for names and other long lists.
Re the web-service; this doesn't have to be a full/complex web-service; just a simple route or ashx (for example) that returns the filtered data.
The jquery autocomplete plugin supports both scenarios, although this is now partly obsoleted by jquery ui plugin.
Is it possible to implement autocomplete by looking up values from database in code behind
Well, that is at the server - so you're essentially talking about the same "web service" that you say you can't do... I also think you should separate out the 2 functions (create page vs provide auto-complete results) into separate files (/pages/whatever).
A simple way would be to make a new aspx page that takes the autocomplete query as querystring parameters, looks up the result in a database and returns the response as XML og JSON.
Excuse my limited knoweldge here.
In the past I have used Steve Sanderson's method to HTML encode by default at runtime: http://blog.stevensanderson.com/2007/12/19/aspnet-mvc-prevent-xss-with-automatic-html-encoding/
I have a need to alter img src and a href attributes before they are spat out in the user's browser. There is a solution using JavaScript but this is not ideal for several reasons. Intercepting the compiler is not an option because of unnecessarily using Response.Write for trivial HTML.
Is there something I can do with HTTP modules or the view engine?
Any thoughts?
UPDATE: I do not need to HTML encode the attributes but I do have a need to change them.
Cheers.
Use a response filter. Works with any ASP.NET project, including MVC. Should work even if you're using a different view engine, as it intercepts at a lower level.
Here's an actual example that strips whitespace:
https://web.archive.org/web/20211029043851/https://www.4guysfromrolla.com/articles/120308-1.aspx
I've used this before to rewrite links before sending to the client, but I can't find the code at the moment.
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!