Using server side resources in JavaScript - c#

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/

Related

How to store a string in xml file and use it in _Layout in MVC

I'm new here. I've started working my own forum system recently to use as a portfolio. Decided to let the admin of the website set his own name and description for the forum. So first thought was use .ini file to put the string there but C# does not support inis but it does XML files. So I have created a simple XML file for use.
But my question is where do I read all the values from that XML file to send them to _Layout every time.
Because if I send it through the View() from each function in the controller that is not really good.
Can somebody point out where in the website to read the values and send them to the _Layout
Sourced: from this link
The web.config (or app.config) is a great place to store custom strings:
in web.config:
<appSettings>
<add key="message" value="Hello, World!" />
</appSettings>
in cs:
string str = ConfigurationSettings.AppSettings["message"].toString();
My answer will not be for XML, but for Resource files. You can use them to annotate your models or even use them in the views directly
Here is a article about resource files http://www.devcurry.com/2013/02/aspnet-mvc-using-resource-files-to.html
You can use xml, of course, but you can also use JSON, it's smaller in size and it's the general community standard nowadays.
Either way you can read a file in a .NET web app simply using this:
string viewPath = HttpContext.Current.Server.MapPath("~/Content/Templates/your-xml_file.xml");
var template = File.ReadAllText(viewPath);
and then use wherever library you want to read the xml file (or you can deserialize it to an object and use it to make things easy for you instead of navigating in the nodes fo the xml file.
If you use JSON data you can use the Newtonsoft.Json.JsonConvert class to read and deserialize.

Using C# variables in CSS

I'm working on a website using ASP.NET C# code, the website will be used for a variety of websites and only serve as a 'placeholder'. We would love to have CSS code which can have different markup depending on which website you are visiting. We're pulling information about the website someone is visiting from our database, which has some methods attached to return these values.
The problem is that we want to be able to use these values in CSS code, and currently the only way I can think of doing this is by using inline CSS code instead of .css files. Which would make our code look something like:
<style>
.navbar {
background-color: #Website.Models.WebsiteConfiguration.NavbarColor;
}
</style>
Which isn't ideal. Is there another way of using C# variables in CSS code, without using inline code? I've found a website which describes using a custom handler to modify the css files, however we couldn't get this to work because our parser was never called. We also found the .LESS library, but we would rather not use this library, and instead work on a solution that only uses a couple lines of code.
You could use some sort of templating language to render the css files. On it's own variables in css won't be populated but you could write a utility class to read the template file, populate variables, save new file to appropriate location and output the correct style element on the page, pointing to new css file.
That way you could have something like the following that would render the appropriate css:
<% CssHelper.Load("myFile.template", "websitex/style.css")%>
Would that be a viable option?

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/

Can a non-embedded resource js file access resource file (.resx)?

I have used the embedded resource js file to reference the .resx file before.
(by including something like
[assembly: ScriptResource("Applications.Webs.Scripts.HelpModule.js",
"Applications.Webs.Scripts.Resources.HelpResources", "Resource.HelpResources")]
in the code behind of the page, where HelpModule.js is a embedded resource)
I was wondering if I can access the .resx when the js is a content file? I have heard "no"s so far. Does any one know if this can be done?
Thanks for your replies in advance.
If your question is whether you can use values from the .resx in the JavaScript code, the answer is "not directly". You'll have to expose the resources from the resx as JavaScript variables that are emitted with your response and parsed by the browser in order to use them in your JS.
You could fudge this a little
Use a HttpModule to parse the JS just before its sent down to the client
looking for 'Tags'.
When you encounter your Tag then replace it with the required value from the resx file...
I used a technique similar to this for localizing JS files recently...
Alternatively, you might be able to use AJAX to muddy it up a bit. If you built a small method that was designed to dip into the resx file you could asynchronously dip. If you didn't want to use all of the Microsoft AJAX compiled stuff (for whatever reason), you could use a small AJAX engine (they're everywhere) and just wire it up to a .ashx handler. That way you could dip into the compiled .resx anytime you needed to. You'd just have to be willing to accept whatever connection latency AJAX might give you.

ASP.Net: Approaches to multilingual websites with Javascript and AJAX

We've recently completed phase 1 of a ASP.Net website in English and French. We went with using resource files to store language specific strings, but because the site used ASP.Net AJAX and javascript heavily we rigged up a solution to pass the right files through the ASP.Net pipeline where we could catch "tokens" and replace them with the appropriate text pulled from the resource files.
This is the second project I've been involved in that had these kinds of challenges, the first one stored the text strings in a database, and instead of ASP.Net AJAX, it used the AJAX tools that come with the Prototype library and put all Javascript into aspx files so that the tokens could be replaced on the way out.
What I'm wondering is, has anyone else encountered a similar scenario? What approach did you take? What lessons were learned? How did you deal with things like internationalized date formats?
In my main project (a RAD framework using PHP with gettext for translations) we're doing already alot of prepare operations on javascript files like merging and minifying them. Within this preperations we parse for gettext-markers and replace them with the language specific text.
The result get save as javascript file and normal included into the html.
<script scr="var/scripts/en_GB-76909c49e9222ec2bb2f45e0a3c8baef80deb665.js"></script>
The filename contains Locale and a hash value for caching.
Date and money values get always converted from system format to Locale format on output and visa versa for input.
To deal with il8n in our applications we dynamically create a JavaScript file (based on the locale we are interested in), that contains keys and translations, e.g.
LOCALISATIONS = {
'util.date.day.long': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
'util.date.day.short': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
...
};
and other JavaScript code will use this object to get translated text.

Categories