JavaScript GetLocalResourceObject from .resx file - javascript

I'm trying to get the local ressources key from .rsex file in javascript, but it doesn't work, I got error "not available".
Thanks for your help.
var key = "errMesgLength"
var val = eval('<%= GetLocalResourceObject("' + key + '") %>');
lblMessage.innerHTML = val;

Thank you Michael for help.
I have found a solution.
In C# code I have used a web method
[WebMethod()]
public static string GetLocalRessources(string key)
{
var currentLanguage = (Language)HttpContext.Current.Session["CurrentLanguage"];
if (currentLanguage == Language.French)
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-FR");
}
else
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
return HttpContext.GetLocalResourceObject("~/SelfRegistration.aspx", key, Thread.CurrentThread.CurrentCulture).ToString();
}
and in JS code, I have used PageMethos call
function IsIMEI() {
var imei = document.querySelector(".txt-imei");
var lblMessage = document.querySelector(".lblMsgError");
var key;
if (imei) {
if (imei.value !== "IMEI / Serial Number") {
if (imei.value.toString().length > 7) {
imei.style.border = "";
lblMessage.innerHTML = "";
return true;
}
else {
key = "errMesgLength"
PageMethods.GetLocalRessources(key, onSucess, onError);
return false;
}
}
else {
imei.style.border = "1px solid red";
key = "errMesgIMEI"
PageMethods.GetLocalRessources(key, onSucess, onError);
return false;
}
}
}
function onSucess(result) {
var lblMessage = document.querySelector(".lblMsgError");
lblMessage.innerHTML = result;
}
function onError(error) {
alert(error._message);
}

Related

How to access object array using javascript with variable

var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
var parametersForTranslation = {};
function __tr(src, params) {
parametersForTranslation[src] = params;
return buildMessage(src);
}
function buildMessage(src){
var message=dict[src] ? dict[src].message : src
console.log(message);
var messageArray = message.split("$");
var output = "";
messageArray.forEach(function(elem, index){
if(index === 0){
output += elem;
}else{
// get variable and index
var paramIndex = configMigratedTo.substring(0, 1);
var paramValue = parametersForTranslation[src][paramIndex-1];
output += paramValue;
output += configMigratedTo.substring(1);
}
});
return output;
}
__tr("configMigratedTo", [2]);
console.log(buildMessage("configMigratedTo"));
i want get result like __tr("configMigratedTo", [2]);
then it will give me
Migrated configuration to configurator: 2
i do not know where is wrong in my code
Try this one. Hope it helps!
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
function __tr(src, params)
{
for (var key in dict)
{
if (key === src)
{
var message = dict[key].message;
return message.substring(0, message.length - 2) + params[0];
}
}
return;
}
console.log(__tr("configMigratedTo", [2]))
https://jsfiddle.net/eLd9u2pq/
Would that be enought?
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: "
}
}
function buildMessage(src,param){
var output = dict[src].message + param;
return output;
}
console.log(buildMessage("configMigratedTo",2));
You are overcomplicating this, it's much easier using a regex and passing a function as replacer
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
function __tr(src, params) {
if (! dict[src]) return src;
if (! /\$0/.test(dict[src].message)) params.unshift('');
return dict[src].message.replace(/\$(\d)+/g, (orig, match) => params[match] || orig);
}
console.log(__tr("configMigratedTo", [2]));

toString method on Linked List implementation not working in js

I'm working through Cracking the Coding Interview and I thought I'd implement all the data structures in JS 5. Can anyone explain to me why my toString method isn't working?
Thanks!
function Node(data) {
this.next = null;
this.data = data;
}
Node.prototype.appendToTail = function(data) {
var end = new Node(data);
var n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
}
Node.prototype.toString = function(head) {
console.log(head)
if (head == null) {
return ""
} else {
return head.data.toString() + "-> " + head.next.toString();
}
}
var ll = new Node(1);
ll.appendToTail(3);
ll.appendToTail(4);
console.log(ll.toString())
function Node(data) {
this.next = null;
this.data = data;
}
Node.prototype.appendToTail = function(data) {
var end = new Node(data);
var n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
};
Node.prototype.toString = function() {
var returnValue = String(this.data);
if (this.next) {
returnValue = returnValue + "-> " + String(this.next);
}
return returnValue;
};
var ll = new Node(1);
ll.appendToTail(3);
ll.appendToTail(4);
console.log(String(ll))
or avoid this kind of problems completly and do not use prototype, class, this, call, etc
Your toString function takes an argument, but you're not passing it when you call toString.
If you want to access the node, you should use this, instead of passing in a value
Node.prototype.toString = function() {
var result = this.data.toString();
if (this.next) {
result += "-> " + this.next.toString();
}
return result;
}

How to take the result of one script and feed it into another?

I'm in way over my head here and need some help to understand what I'm looking at please! (Very new to Javascript!) Here is the situation as I understand it...
I have a script that is selecting a single line from a paragraph of text, and currently produces this alert, where '1' is the selected line:
alert(getLine("sourcePara", 1));
...Instead of triggering an alert I need this selected text to feed into this separate script which is sending data to another browser window. Presently it's taking a text field from a form with the id 'STOCK1', but that can be replaced:
function sendLog() {
var msg = document.getElementById('STOCK1').value;
t.send('STK1', msg);
}
I'm totally confused as to what form this text data is taking on the way out of the first script and have no idea how to call it in as the source for the second... HELP!
All the thanks!
EDIT:
Here is the source code for the Local Connection element;
function LocalConnection(options) {
this.name = 'localconnection';
this.id = new Date().getTime();
this.useLocalStorage = false;
this.debug = false;
this._actions= [];
this.init = function(options) {
try {
localStorage.setItem(this.id, this.id);
localStorage.removeItem(this.id);
this.useLocalStorage = true;
} catch(e) {
this.useLocalStorage = false;
}
for (var o in options) {
this[o] = options[o];
}
this.clear();
}
this.listen = function() {
if (this.useLocalStorage) {
if (window.addEventListener) {
window.addEventListener('storage', this.bind(this, this._check), false);
} else {
window.attachEvent('onstorage', this.bind(this, this._check));
}
} else {
setInterval(this.bind(this, this._check), 100);
}
}
this.send = function(event) {
var args = Array.prototype.slice.call(arguments, 1);
return this._write(event, args);
}
this.addCallback = function(event, func, scope) {
if (scope == undefined) {
scope = this;
}
if (this._actions[event] == undefined) {
this._actions[event] = [];
}
this._actions[event].push({f: func, s: scope});
}
this.removeCallback = function(event) {
for (var e in this._actions) {
if (e == event) {
delete this._actions[e];
break;
}
}
}
this._check = function() {
var data = this._read();
if (data.length > 0) {
for (var e in data) {
this._receive(data[e].event, data[e].args);
}
}
}
this._receive = function(event, args) {
if (this._actions[event] != undefined) {
for (var func in this._actions[event]) {
if (this._actions[event].hasOwnProperty(func)) {
this.log('Triggering callback "'+event+'"', this._actions[event]);
var callback = this._actions[event][func];
callback.f.apply(callback.s, args);
}
}
}
};
this._write = function(event, args) {
var events = this._getEvents();
var evt = {
id: this.id,
event: event,
args: args
};
events.push(evt);
this.log('Sending event', evt);
if (this.useLocalStorage) {
localStorage.setItem(this.name, JSON.stringify(events));
} else {
document.cookie = this.name + '=' + JSON.stringify(events) + "; path=/";
}
return true;
}
this._read = function() {
var events = this._getEvents();
if (events == '') {
return false;
}
var ret = [];
for (var e in events) {
if (events[e].id != this.id) {
ret.push({
event: events[e].event,
args: events[e].args
});
events.splice(e, 1);
}
}
if (this.useLocalStorage) {
localStorage.setItem(this.name, JSON.stringify(events));
} else {
document.cookie = this.name + '=' + JSON.stringify(events) + "; path=/";
}
return ret;
}
this._getEvents = function() {
return this.useLocalStorage ? this._getLocalStorage() : this._getCookie();
}
this._getLocalStorage = function() {
var events = localStorage.getItem(this.name);
if (events == null) {
return [];
}
return JSON.parse(events);
}
this._getCookie = function() {
var ca = document.cookie.split(';');
var data;
for (var i=0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(this.name+'=') == 0) {
data = c.substring(this.name.length+1, c.length);
break;
}
}
data = data || '[]';
return JSON.parse(data);
}
this.clear = function() {
if (this.useLocalStorage) {
localStorage.removeItem(this.name);
} else {
document.cookie = this.name + "=; path=/";
}
}
this.bind = function(scope, fn) {
return function () {
fn.apply(scope, arguments);
};
}
this.log = function() {
if (!this.debug) {
return;
}
if (console) {
console.log(Array.prototype.slice.call(arguments));
}
}
this.init(options);
}
If I understand what you are asking for correctly, then I think its a matter of changing your log function to the following:
function sendLog() {
t.send('STK1', getLine("sourcePara", 1));
}
This assumes that getLine is globally accessible.
Alternatively Another approach would be to allow for the sendLog function to take the message as a parameter. In which case, you would change your first script to be:
sendLog(getLine("sourcePara", 1));
And the modified sendLog function would look like this:
function sendLog(msg) {
t.send('STK1', msg);
}
LocalConnection.js should handle transferring the data between windows/tabs. Looks like an an iteresting project:
https://github.com/jeremyharris/LocalConnection.js

How can we determine the group which initiated SignalR extended method?

I have created a Javascript function to make SignalR even more magical:
//Initializable
function Initializable(params) {
this.initialize = function (key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
/*SignalR Updater*/
function SignalRUpdater(params) {
Initializable.call(this, params);
var self = this;
this.initialize("RawHubs", [], true);
this.initialize("RawGroups", {}, true);
this.initialize("Connection", $.connection, true);
this.initialize("Extend", {});
this.Hubs = {};
this.addHub = function (name, extend) {
if (self.Hubs[name]) {
return false;
}
self.Hubs[name] = params.Connection[name];
self.Hubs[name].Groups = {};
params.RawHubs.push(name);
if (!params.RawGroups[name]) {
params.RawGroups[name] = [];
}
if (extend) {
if ((!self.Extend) || (!extend.append)) {
self.Extend = extend;
} else {
if (!self.Extend) {
self.Extend = {};
}
if (extend.append) {
for (var extendIndex in extend) {
if (extendIndex !== "append") {
self.Extend = extend[extendIndex];
}
}
} else {
self.Extend = extend;
}
}
$.extend(params.Connection[name].client, self.Extend);
} else if (self.Extend) {
$.extend(params.Connection[name].client, self.Extend);
}
return true;
};
this.removeHub = function (name) {
if (!self.Hubs[name]) {
return false;
}
for (var groupIndex in self.Hubs[name].Groups) {
self.Hubs[name].Groups[groupIndex].unsubscribe();
}
delete self.Hubs[name];
delete params.RawGroups[name];
params.RawHubs.splice(params.RawHubs.indexOf(name), 1);
return true;
};
this.addGroupToHub = function (hubName, groupName) {
if ((self.Hubs[hubName]) && (self.Hubs[hubName].Groups[groupName])) {
return false;
}
self.Hubs[hubName].server.subscribe(groupName);
self.Hubs[hubName].Groups[groupName] = {}; //Here we can hold group-related data
if (params.RawGroups[hubName].indexOf(groupName) < 0) {
params.RawGroups[hubName].push(groupName);
}
return true;
};
this.removeGroupFromHub = function (hubName, groupName) {
if ((!self.Hubs[hubName]) || (!self.Hubs[hubName].Groups[groupName])) {
return false;
}
self.Hubs[hubName].server.unsubscribe(groupName);
delete self.Hubs[hubName].Groups[groupName];
if (params.RawGroups[hubName].indexOf(groupName) >= 0) {
params.RawGroups[hubName].splice(params.RawGroups[hubName].indexOf(groupName), 1);
}
return true;
};
for (var hubIndex in params.RawHubs) {
self.addHub(params.RawHubs[hubIndex]);
}
params.Connection.hub.start().done(function () {
for (var hubIndex in params.RawGroups) {
for (var groupIndex in params.RawGroups[hubIndex]) {
self.addGroupToHub(hubIndex, params.RawGroups[hubIndex][groupIndex]);
}
}
});
}
I am using it like this, for example:
function statusUpdate(status) {
alert(status);
}
var signalRUpdater = new SignalRUpdater({
RawHubs: ["statusUpdates"],
Extend: {
statusUpdate: statusUpdate
}
});
So far, so good. However, I may have several groups in the same hub and at the point of statusUpdate I do not seem to know about the group. I can send it from server-side as a parameter to statusUpdate, but I wonder whether this is an overkill and whether it is possible out of the box with SignalR.
When sending a group message to clients the server does not send the name of the group the message was sent to. The server selects clients that are members of the group and just sends them the message. If you want to understand the protocol SignalR is using you can find a description I wrote some time ago here.

Creating cookies in javascript and use it into mvc 4 action result

I have make cookies in java script page but when used in the Controller page it shows null and i Check in the browser cookies is also created so please help me for this ......
<script>
#Html.Raw(ViewBag.CallJSFuncOnPageLoad)
function IPDetction()
{
$.getJSON("http://ip-api.com/json/?callback=?", function (data) {
var items = [];
$.each(data, function (key, val)
{
if (key == 'city') {
document.cookie = "DetectedCityName=" + val;
}
if (key == 'region') {
document.cookie = "DetectedRegionName=" + val;
}
});
});
}
</script>
#{
string DetectedCityName = "Toronto";
try
{
RateMadnessfinal.DataModel.RateMadnessdbEntities db = new RateMadnessfinal.DataModel.RateMadnessdbEntities();
DetectedCityName = HttpContext.Current.Request.Cookies["DetectedCityName"].Value;
var getCityID = db.Macities.Where(c => c.CityName.Contains(DetectedCityName)).ToList();
if ((getCityID != null) && (getCityID.Count > 0))
{
DetectedCityName = getCityID.FirstOrDefault().CityName;
}
else
{
DetectedCityName = "Toronto";
}
}
catch (Exception e)
{
DetectedCityName = "Toronto";
}
}

Categories