Call a Javascript function from a vb.net class - javascript

My web application which has 2 tiers. UI tier where the pages and javascript files reside. Business Layer tier with all the .net classes to save the data. In my Javascript file, i have a long function which takes an Object as a parameter and converts it onto a xml string. something like this:
function objToXML(obj) {
var strXML = '<Data>';
strXML = strXML + '<Name>' + obj.Name + '</Name>'
strXML = strXML + '</Data>'
return strXML;
}
In my business layer class, i need the same feature of converting the .net class to xml. But i do not want to write the long method in vb.net again as it has 100+ properties (above was just a sample).
is there any way by which i can use the same Jaavscript function on the server side business layer, where i do not have any acccess to the page.
Thanks.

Related

Access RESX file from external javascript file [duplicate]

How would one get resx resource strings into javascript code stored in a .js file?
If your javascript is in a script block in the markup, you can use this syntax:
<%$Resources:Resource, FieldName %>
and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed.
I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active.
One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser?
Or does anyone have any other suggestions?
Here is my solution for now. I am sure I will need to make it more versatile in the future... but so far this is good.
using System.Collections;
using System.Linq;
using System.Resources;
using System.Web.Mvc;
using System.Web.Script.Serialization;
public class ResourcesController : Controller
{
private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
public ActionResult GetResourcesJavaScript(string resxFileName)
{
var resourceDictionary = new ResXResourceReader(Server.MapPath("~/App_GlobalResources/" + resxFileName + ".resx"))
.Cast<DictionaryEntry>()
.ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
var json = Serializer.Serialize(resourceDictionary);
var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.{0} = {1};", resxFileName, json);
return JavaScript(javaScript);
}
}
// In the RegisterRoutes method in Global.asax:
routes.MapRoute("Resources", "resources/{resxFileName}.js", new { controller = "Resources", action = "GetResourcesJavaScript" });
So I can do
<script src="/resources/Foo.js"></script>
and then my scripts can reference e.g. window.Resources.Foo.Bar and get a string.
There's no native support for this.
I built a JavaScriptResourceHandler a while ago that can serve Serverside resources into the client page via objects where each property on the object represents a localization resource id and its value. You can check this out and download it from this blog post:
http://www.west-wind.com/Weblog/posts/698097.aspx
I've been using this extensively in a number of apps and it works well. The main win on this is that you can localize your resources in one place (Resx or in my case a custom ResourceProvider using a database) rather than having to have multiple localization schemes.
whereas "Common" is the name of the resource file and Msg1 is the fieldname. This also works for culture changes.
Partial Javascript...:
messages:
{
<%=txtRequiredField.UniqueID %>:{
required: "<%=Resources.Common.Msg1 %>",
maxlength: "Only 50 character allowed in required field."
}
}
In a nutshell, make ASP.NET serve javascript rather than HTML for a specific page. Cleanest if done as a custom IHttpHandler, but in a pinch a page will do, just remember to:
1) Clear out all the ASP.NET stuff and make it look like a JS file.
2) Set the content-type to "text/javascript" in the codebehind.
Once you have a script like this setup, you can then create a client-side copy of your resources that other client-side scripts can reference from your app.
If you have your resources in a separate assembly you can use the ResourceSet instead of the filename. Building on #Domenics great answer:
public class ResourcesController : Controller
{
private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
public ActionResult GetResourcesJavaScript()
{
// This avoids the file path dependency.
ResourceSet resourceSet = MyResource.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
// Create dictionary.
var resourceDictionary = resourceSet
.Cast<DictionaryEntry>()
.ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
var json = Serializer.Serialize(resourceDictionary);
var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.resources = {1};", json);
return JavaScript(javaScript);
}
}
The downside is that this will not enable more than one resource-file per action. In that way #Domenics answer is more generic and reusable.
You may also consider using OutputCache, since the resource won't change a lot between requests.
[OutputCache(Duration = 3600, Location = OutputCacheLocation.ServerAndClient)]
public ActionResult GetResourcesJavaScript()
{
// Logic here...
}
http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs
I usually pass the resource string as a parameter to whatever javascript function I'm calling, that way I can continue to use the expression syntax in the HTML.
I the brown field application I'm working on we have an xslt that transforms the resx file into a javascript file as part of the build process. This works well since this is a web application. I'm not sure if the original question is a web application.
use a hidden field to hold the resource string value and then access the field value in javascript
for example :
" />
var todayString= $("input[name=TodayString][type=hidden]").val();
Add the function in the BasePage class:
protected string GetLanguageText(string _key)
{
System.Resources.ResourceManager _resourceTemp = new System.Resources.ResourceManager("Resources.Language", System.Reflection.Assembly.Load("App_GlobalResources"));
return _resourceTemp.GetString(_key);
}
Javascript:
var _resurceValue = "<%=GetLanguageText("UserName")%>";
or direct use:
var _resurceValue = "<%= Resources.Language.UserName %>";
Note:
The Language is my resouce name. Exam: Language.resx and Language.en-US.resx

Razor page javascript execute c# only once

I'm trying to use a javascript loop to update data from my c# code. But it only execute the c# method once.
I made a test class :
public class testClass
{
public static int result;
public static int nb1;
public static int add()
{
result = result + 1;
return result;
}
}
And in my javascript I made this :
<script>
setInterval(Testing,3000);
nb1 = 0;
function Testing() {
nb1 = nb1 + 1; //this is to test that the function really restart after 3 seconds
document.getElementById('label').innerHTML = nb1 + " | " + #testClass.add(); ; // calling my c# method and print into a html label
}
And it display this on the page :
this is what is displayed on my html page
As you can see the number that show if the javascript function is restarting after 3 seconds works, but the c# method is not updating.
Do you have any solutions ?
It seems like you don't really have an understanding how HTML, JS and C# work in unison.
When a request is made to your server, It will perform calculations to return a document. This document is presented in HTML, with added logic in the form of JS to compliment it.
When using Razor, you can effectively use C# to help building the document, but not at runtime. If you want your front end document to be able to interact with the backend C# code, you are bound to using sockets(for example SignalR), or AJAX(which would be the most prominent way of asynchronous communication between a web page and a back end).
I will help you understand by stepping through the code with you..
Your razor page will start building. at one point it will detect the following line:
document.getElementById('label').innerHTML = nb1 + " | " + #testClass.add(); ; // calling my c# method and print into a html label
this is where it will call on the C# method, convert it to a value, and put the value in the JS code, so when the document gets sent to the client (your webbrowser) the code will look as follows:
document.getElementById('label').innerHTML = nb1 + " | " + {THE CALCULATED VALUE} ; // calling my c# method and print into a html label
I will refer you to this answer. Where it is explained how to do what you are trying to do.

Accessing MVC server side variable in Javascript

I'm moving one of our web applications from Drupal to an ASP.net MVC Web Application.
One of the Drupal functions gets some data from a web service and converts it to a JS Array, as follows:
foreach ($xml_result->JobList->JobDetail as $job_detail) {
// dsm((array)$job_detail);
$open_job_details[] = array("east"=>(string)$job_detail->Easting,"north"=>(string)$job_detail->Northing, "duedate"=>(string)$job_detail->openDate);
}
//dsm($open_job_details);
$open_jobs_data = json_encode($open_job_details);
drupal_add_js(array('open_jobs' => array('open_newjobs' => $open_jobs_data)), 'setting');
In the Javascript file, it is accessed using;
var openJobsData = JSON.parse(Drupal.settings.open_jobs.open_newjobs);
Is there a simple way to access a server side variable in the JS file in .NET? I can call the web service and get the relevant data from the XML file but not sure how to access it in the JS file.
Thanks
You can use Strongly Typed view to create cshtml page
if you want to access JSON object
View1.cshtml
#model mvcApplication1.Models.model1
#{
var serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = int.MaxValue;
var jsonModel = serializer.Serialize(Model);
}
var JsonData = #Html.Raw(jsonModel); // declare a javascript variable and use it
if you want to access server variable at cshtml page
just use # to access server-side variables
after getting the value you can use javascript variable in another js file
Declare your javascript variable outside
$(document).ready(function()
{}
or before using the variable
you can use that variable in Javascript file.

Access javascript data from Java (maven application)

I hope this is the right subforum to post this.
I'm very new to maven, vaadin and java applications in general, so I hoped you could help me with this as I'm not sure what's the best way to go about it.
Basically I have a maven project (java 7) which, using javascript, creates a popup window with a form inside, allows you to upload a file, display its content in a textarea and send it (the content of the file as a string) to the server via an ajax request. That was the easy part.
What I want to do now is to access that data sent through ajax (the string containing the data of the uploaded file) in Java because I need to run it through some validation.
I had a good look around, including the book of vaadin, and the net in general and considering that I have never done this before, it seems that one way could be to have a connector, but it looks a little too complicated and also it appears - from what I understand from the book of vaadin https://vaadin.com/docs/-/part/framework/gwt/gwt-overview.html - that I won't be able to implement that in my project given the structure I have - which is different from what's in there.
So, my question to you guys is, given the project I have (just a normal maven project) what would be the easiest way for me to access this data from Java?
Here is some code from the project, to put things into context:
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.annotations.Widgetset;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.JavaScript;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.client.ui.*;
#Theme("mytheme")
#Widgetset("my.vaadin.apptest.MyAppWidgetset")
#com.vaadin.annotations.JavaScript({"https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"
})
public class MyUI extends UI {
#Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
layout.addStyleName("myLayout");//add class to main div
Label label = new Label("Hello Vaadin user. Use this application to upload files.");
...
//HERE IS THE JAVASCRIPT CREATING AND INSTANTIATING THE POPUP AND THE AJAX CALL
//CREATING POPUP
JavaScript.getCurrent().execute(""
+"var $HTMLpopup = $('<div class=\"popupContainer\">"
+"<span class=\"cancelBtn big\"></span>"
+"<div class=\"wrapper\">"
+"<form action=\"\" id=\"fileForm\">"
+"<div class=\"mask\">"
+"<input type=\"file\" title=\" \"name=\"uploadFile\" class=\"uploadFile\" accept=\".mol,.sdf\">/*filters files to upload*/"
+"<span class=\"pseudoBtn\">Browse</span>"
+"<input type=\"text\" name=\"displayFile\" class=\"displayFile\" placeholder=\"no file loaded\">"
+"<span class=\"cancelBtn small\"></span>"
+"</div>"
+"<textarea class=\"fileResult\"></textarea>"
+"<button type=\"submit\" class=\"submitBtn\">Upload</button>"
+"<div class=\"clear\"></div>"
+"</form>"
+"</div>"
+"</div>');"
//INSTANTIATING THE POPUP
+"$('.popupTriggerBtn').click(function(){"
+"/*console.log('button clicked!');*/"
+"var $body = $('body');"
+"$HTMLpopup.appendTo($body);"
+"});"
//HERE IS THE AJAX BIT
+"var $submitBtn = $HTMLpopup.find('.submitBtn');"
+"$submitBtn.click(function(e){"
+"e.preventDefault();/*prevent submission*/"
+"if(isFileUploadEmpty()){/*IF EMPTY*/"
+"/*alert('submit clicked');*/"
+"removeError();"
+"showError('empty');"
+ "}"
+"else{/*IF NOT EMPTY*/"
+"/*AJAX OPS*/"
+"if (window.XMLHttpRequest){/*XMLHttpRequest SUPPORT?*/"
+"console.log('XMLHttpRequest supported!');"
+"var postData = returnFileAsString();/*returns the file as a string*/;"
+"/*console.log('here is the file as a string ' + postData);*/"
+"$.ajax({"
+"type:'post',"
+"url:'http://localhost:8080/apptest/',"
+"data:postData,"
+"contentType: 'application/x-www-form-urlencoded',"
+"success: function(responseData, textStatus, jqXHR){"
+"/*alert('data saved');*/"
+"console.log('responseData is ' + responseData);"
+"console.log('text status is ' + textStatus);"
+"console.log('the data submitted is ' + postData );"
+"},"
+"error: function(jqXHR, textStatus, errorThrown){"
+"console.log(errorThrown);"
+"alert('an error has occurred!');"
+"}"
+"});"
+"}"
+"}"
+"});"
+"");
//ADDING COMPONENTS
layout.addComponents( label, button );
layout.setMargin(true);
layout.setSpacing(true);
setContent(layout);
}
Link to pastebin here http://pastebin.com/mSEJq0HT
So, postData contains the string that I passed to the server and that I'd like to access in Java.
I came across this earlier on, which may or may not be another way to deal with it vaadin with ajax. What do you guys think?
Any help would be much appreciated, thanks
Well, firstly I need to express my deep concern that you are using wrong tools in a really strange way to achieve your desired effect. I won't go deeply into that topic but lets just indicate the main purpose of Vaadin framework is to allow developer to write components in Java (similarly to Swing components) to avoid JavaScript mess. Yes, you can run JavaScript using Vaadin Framework but you should avoid it as long as possible.
Ok now lets get into hacking. You have two options to catch your file data (which is a String as you said) by your server:
a) Get rid ofconstructing your XMLHttpRequest by hand. Let Vaadin handle it for you. Instead of
+"$.ajax({"
+"type:'post',"
+"url:'http://localhost:8080/apptest/',"
...
just call JavaScript function, lets say
sendFileContentToTheServer(postData)
Now next thing you need to do is to register JavaScript callback on the Server side (read: Vaadin). Somewhere in your code (doesn't really matter where, just make sure the code is called at least once - ideally exactly once) put:
JavaScript.getCurrent().addFunction("sendFileContentToTheServer", new JavaScriptFunction() {
public void call(JSONArray arguments) throws JSONException {
System.out.println(arguments.getString(0));
//do whatever you want with your data - its under arguments.getString(0)
}
});
That's it. Vaadin will manage the RPC call for you. Your page won't be reloaded and you will get your data on the server side.
b) The second approach it's a way more tricky. It is technically possible to construct XMLHttpRequest by hand and receive data on the server using Vaadin. What you need to do is to register JavaServlet (not VaadinServlet). Send the data to the JavaServlet. Then through some proxy or reference call the existed VaadinUI. It's a compilcated way of doing things that you've already made very tricky so I won't go deeper into that.

Can user's custom JavaScript on MediaWiki call a Lua module?

On MediaWiki wikis each user has a user JavaScript page they can put code in, much like GreaseMonkey but without extensions. Such as at User:YourUsername/vector.js
MediaWiki has also had an embedded Lua, called Scribunto, for a little while now.
I know Lua modules can be called from MediaWiki templates, and I suppose that's their main use. But Googling and hunting around the MediWiki docs I can't find whether there's a way to call a Lua module from your user JavaScript.
(I need to map names of languages to language codes in my JS and there's a Lua module to do just that without me duplicating the code (mainly data) in a second language.)
You can't do this directly, because JS runs on the client and Lua on the server. What you can do is to use the MediaWiki API from JS to invoke the module. Specifically using the expandtemplates API module.
For example, if you wanted to call the function h2d from Module:Hex with the parameter FF ({{#invoke:hex|h2d|FF}} in wikitext) and alert the result, then the JS would look like this:
var api = new mw.Api();
api.get( {
action: 'expandtemplates',
text: '{{#invoke:hex|h2d|FF}}'
} ).done ( function ( data ) {
alert(data.expandtemplates['*']);
} );
And for the OP's specific case, running on the English Wiktionary:
var langName = 'Esperanto';
(new mw.Api()).get({
action: 'expandtemplates',
format: 'json',
prop: 'wikitext',
text: '{{#invoke:languages/templates|getByCanonicalName|' + langName + '|getCode}}'
}).done(function(data) {
alert('Language name: ' + langName + '\nLanguage code: ' + data.expandtemplates.wikitext);
});
(prop: 'wikitext' avoids a warning from the API and lets you access the result as data.expandtemplates.wikitext rather than the slightly mystifying data.expandtemplates['*']. Otherwise there's no difference.)

Categories

Resources