Url.RouteUrl in js - javascript

I have a situation that I need to jump urls in javascript of a ASP.NET MVC site.
As we know, we can generate url with #Url.RouteUrl("RouteName", new { params}) in xx.cshtml. Now I want to generate url in the same way in javascript, is it possible?
I have tried:
window.location.href ='#Url.RouteUrl("RouteName", new {param1="' + param+ '"}) %>'.
However, it doesn't work.
My Route:
routes.MapRoute(
"ListOfTicketAB",
"piao/{citystart}-{cityend}",
new { controller = "Tickets", action = "ListS2S", traintype = 0, sorttype = 0, page = 1 },
new { citystart = "[a-zA-Z0-9]+", cityend = "[a-zA-Z0-9]+" });
My js:
var selectS;var selectE;function SearchClick(obj) {
location.href = '#Url.RouteUrl("ListOfTicketAB",new {citystart="' + selectS+ '",cityend="' + selectE+ '"})';
}
selectS and selectE will be set in some other functions.
With Above, I got error:
Server Error in '/' Application.
Illegal characters in path.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Illegal characters in path.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Now I want to generate url in the same way in javascript, is it possible?
No, javascript files cannot execute server side Razor language.
What you could do is generate this url as a global javascript variable in your view or as HTML5 data-* attribute to some existing DOM element that you could access later in your javascript file:
<script type="text/javascript">
var myUrl = '#Url.RouteUrl("ListOfTicketAB", new { citystart = "_start_", cityend = "_end_" })';
</script>
and then in your javascript replace the 2 placeholders with the corresponding values of your existing javascript variables selectS and selectE:
var selectS;
var selectE;
function SearchClick(obj) {
var url = myUrl.replace('_start_', selectS).replace('_end_', selectE);
window.location.href = url;
}

Related

html2canvas on shopify error: Uncaught ReferenceError: onLoadStylesheet is not defined at HTMLLinkElement.onload

I am trying to use html2canvas on a Shopify product page to convert a div to an imgURL to set as a form value. Whenever I use html2canvas, I get the error:
Uncaught ReferenceError: onLoadStylesheet is not defined at HTMLLinkElement.onload
When I try to pinpoint the error, it just directs me to <!doctype html> highlighted with the message
Each dictionary in the list "icons" should contain a non-empty UTF8 string field "type".
This also prevents the form from posting for some reason.
html2canvas(document.querySelector("#container"), {useCORS: true, logging: false}).then(canvas => {
document.getElementById("imgURL").value = canvas.toDataURL();
});
How do I fix this?
I found the solution, if you are using ScriptTags and loading JavaScript from your own domain then you will get the error, solution is to use the cache=true when creating the ScriptTag and this will load JavaScript from Shopify's CDN and html2canvas works
Here is the code snippet in C# to create a script tag with caching:
dynamic scriptTagBody = new ExpandoObject();
scriptTagBody.script_tag = new ShopifyScriptTag()
{
Event = "onload",
Src = "https://example.com/script.js",
DisplayScope = "all",
Cache = true
};
HttpContent content = new JsonContent(scriptTagBody);
content.Headers.Add("X-Shopify-Access-Token", "MyAccessToken");
string url = "https://yourshop.myshopify.com/admin/api/2021-04/script_tags.json";
await _httpClient.PostAsync(url, content);
ShopifyScriptTag in the above snippet is a simple POJO with those properties

Add attachment by url to Outlook mail

The context
There is a button on the homepage of each document set in a document library on a SharePoint Online environment. When the button is clicked, an Outlook window opens with the title and body set and all the files in the document set should be added as the attachments.
The code
Here's the code I have so far:
var olApp = new ActiveXObject("Outlook.Application");
var olNs = olApp.GetNameSpace("MAPI");
var olItem = olApp.CreateItem(0);
var signature = olItem.HTMLBody;
signature.Importance = 2;
olItem.To = "";
olItem.Cc = "";
olItem.Bcc = "";
olItem.Subject = "Pre filled title";
olItem.HTMLBody =
"<span style='font-size:11pt;'>" +
"<p>Pre filled body</p>" +
"</span>";
olItem.HTMLBody += signature;
olItem.Display();
olItem.GetInspector.WindowState = 2;
var docUrl = "https://path_to_site/Dossiers/13245_kort titel/New Microsoft Word Document.docx";
olItem.Attachments.Add(docUrl);
The Problem
When I run this code, an Outlook window opens with everything set correctly. But on the line where the attachment is added I get following very vague error message:
SCRIPT8: The operation failed.
I thought it could be the spaces in the url so I replaced them:
docUrl = docUrl.replace(/ /g, "%20");
Also didn't work (same error) and providing all parameters like this also didn't work:
olItem.Attachments.Add(docUrl, 1, 1, "NewDocument");
Passing a path to a local file (e.g. C:/folder/file.txt) or a publicly available url to an image does work. So my guess is it has something to do with permissions or security. Does anybody know how to solve this?
PS: I know using an ActiveX control is not the ideal way of working (browser limitations, security considerations, ...) but the situation is what it is and not in my power to change.
You cannot pass a url to MailItem.Attachments.Add in OOM (it does work in Redemption - I am its author - for RDOMail.Attachments.Add). Outlook Object Model only allows a fully qualified path to a local file or a pointer to another item (such as MailItem).

MarkLogic JavaScript scheduled task

I try to schedule a script using the 'Scheduled Tasks' in ML8. The documentation explains this a bit but only for xQuery.
Now I have a JavaScript file I'd like to schedule.
The error in the log file:
2015-06-23 19:11:00.416 Notice: TaskServer: XDMP-NOEXECUTE: Document is not of executable mimetype. URI: /scheduled/cleanData.js
2015-06-23 19:11:00.416 Notice: TaskServer: in /scheduled/cleanData.js [1.0-ml]
My script:
/* Scheduled script to delete old data */
var now = new Date();
var yearBack = now.setDate(now.getDate() - 65);
var date = new Date(yearBack);
var b = cts.jsonPropertyRangeQuery("Dtm", "<", date);
var c = fn.subsequence(cts.uris("", [], b), 1, 10);
while (true) {
var uri = c.next();
if (uri.done == true){
break;
}
xdmp.log(uri.value, "info"); // log for testing
}
Try the *.sjs extension (Server-side JavaScript).
The *.js extension can be used for static JavaScript resources to return to the client instead of executed on the server.
Hoping that helps,
I believe that ehennum found the issue for you (the extension - which is what the mime-type error is complaining about.
However, on the same subject, not all items in ML work quite as you would expect for Serverside Javascript. For example, using sjs as a target of a trigger is (or recently) did not work. So for things like that, it is also possible to wrap the sjs call inside of xqy using xdmp-invoke.

Deleting Parse files

If I have a Parse object with a file attribute on it and then I delete the original object.
Does it delete the orphaned file?
If not, how do I delete the file?
I'm doing everything in cloud code using Javascript trying to put an "After delete" function together and cascading the delete down.
EDIT
OK, a quick test later. The files are not deleted. They are orphaned. So, how to delete the file in cloud code?
Another option is pressing the clean up button located in the settings page of your app (I saw that somebody else had mentioned deleting via the REST API).
You can delete files that are referenced by objects using the REST API. You will need to provide the master key in order to be allowed to delete a file.
If your files are not referenced by any object in your app, it is not possible to delete them through the REST API. You may request a cleanup of unused files in your app's Settings page. Keep in mind that doing so may break functionality which depended on accessing unreferenced files through their URL property. Files that are currently associated with an object will not be affected.
There is a REST API for that, see here
Other answers already pointed out the proper links... The following shows how I did it from within the browser...
// 1. in a browser console, go to their domain do avoid cross-domain failure later
// (paste this by itself)
document.location.href='https://api.parse.com';
// 2. load up jquery
// (paste this and the rest of the script into the console only after the page url above loads)
(function(){
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.async = true;
newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(newscript);
})();
// the goods
function deleteParseFile(appId, masterKey, filename)
{
var serverUrl = 'https://api.parse.com/1/files/' + filename;
$.ajax({
type: "DELETE",
beforeSend: function(request) {
request.setRequestHeader("X-Parse-Application-Id", appId);
request.setRequestHeader("X-Parse-Master-Key", masterKey);
},
url: serverUrl,
success: function(results) {
console.log('success:', results)
}, error: function(error) {
console.log('error:', error);
}
});
}
// 3. set the file you want deleted... and delete it
var appId = "<YOUR_APPLICATION_ID>";
var masterKey = "<YOUR_MASTER_KEY>";
// this filename can be found in the file object or the parse image URL
var filename = "tfss-abcd1234-dcba-4321-1a2b-112233aabbcc-my-file.gif";
deleteParseFile(appId, masterKey, filename);

Change html page content

I am creating Firefox addon using the Add-on SDK. I want to get data from remote url and inject it in current html. As of now i m able to fetch data using request module of Firefox addon sdk but m not able to inject it in current page.
for example : i am fetching response from website "abc.com".after fetching response i will augment current page with response
// main.js
var widgets = require("sdk/widget");
var tabs = require("sdk/tabs");
var Request = require("sdk/request").Request;
//create addon widget
var widget = widgets.Widget({
id: "div-show",
label: "Show divs",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function() {
//initializing request module to fetch content
quijote.get();
}
});
//fetch content of requested page
var quijote = Request({
url: "http://localhost/abc/",
overrideMimeType: "text/plain; charset=latin1",
onComplete: function (response) {
//check if content is fetched successfully
addContent(response);
}
});
//try and modify current page
function addContent(response){
//initialize page modification module
var pageMod = require("sdk/page-mod");
tabs.activeTab.attach({
contentScript: 'document.body.innerHTML = ' + ' "<h1>'+response.text+'</h1>";'
});
}
Is their any way in which i can augment my current page???
Your code will bitterly fail e.g. when response.text includes a double quote.
Then your code would be (assume it is world):
document.body.innerHTML = "<h1>world</h1>";
This is obviously invalid code.
Your code basically constructs a dynamic script from unsanitized data, which is a bad idea because (other than the escaping problem above)
you'll be running an unsanitized content script if that code is even valid and
if that would succeed, the page might run unsanitized code as well.
This is the web equivalent to SQL injection attacks....
First, lets tackle 1.) with messaging (more):
var worker = tabs.activeTab.attach({
contentScript: 'self.port.on("setdom", function(data) { ' +
+ 'document.body.innerHTML = data; /* still a security issue! */'
+ '});'
});
worker.port.emit("setdom", response.text);
This guarantees that the content script will be valid (can even run) and does not run arbitrary code.
However 2.) is still a problem. Read DOM Building and HTML insertion.

Categories

Resources