My relative URL path to my View breaks on Deployment - javascript

I have a very standard ASP MVC app that I use a little javascript to show a Partial View. In order to make that Javascript work I needed to hard code a path to the Partial which is different between Dev and Production.
Mainly, in Dev there is no App specification where as in Production there is. See here:
Production=var URL = '/WetWashRequest/wetWashRequests/GetDetails?WONumber=' + wo;
Dev = var URL = '/wetWashRequests/GetDetails?WONumber=' + wo;
What this means is that as I work on it locally I delete the first part and when I want to deploy I have to remember to re add it.
This seems so ridiculously flawed that I can only assume I am being ignorant and doing something wrong...

You can take advantage of UrlHelper to get the URLs, as long as you do it in view:
var URL = '#Url.Action("GetDetails")';
Obviously, it doesn't make sense to put all your JavaScript in view, so what I will normal do is set just this in my view, in a namespace var, and then reference it in my external JavaScript:
View
<script>
var MyApplication = MyApplication || {};
MyApplication.GetDetailsUrl = '#Url.Action("GetDetails")';
</script>
External JS
$.get(MyApplication.GetDetailsUrl, { WONumber: wo }, function (result) {
...
});

Related

Name html blob urls for easy reference

Within our web application we load a lot of content from package files (zipped packages containing html, js, css, images and so on.) The module loader (client side JS) processes the packages and makes the content available to the DOM using blob urls.
While this works very nice, it's sometimes tedious to find the right piece of JavaScript file for debugging.
IE: in chrome in the development console->sources all blob urls are listed under (no domain) and have random names such as:
blob:https://example.com/0613efd7-6977-4872-981f-519eea0bc911
In a normal production environment there are roughly 100 lines like this, so finding the right one might take some time.
I'd pretty much like to name the blob urls, or do something to make them easier to find for debugging purposes. This seems possible since WebPack is doing something like this, however i can't seem to find how. Is there anybody that can hint me in the right direction.
Ok, the way I would do it is have some global that keeps a track of the URL's, using a simple reverse map.
One problem of course with this is that references to a blob that no longer exists will be kept in memory, but if say you was only enabling this for debugging purposes this might not be a problem.
var namedblobs = {};
function addNamedBlob(name, uri) {
namedblobs[uri] = name;
}
function getNamedBlob(uri) {
return namedblobs[uri];
}
function createSomeBlob() {
//for testing just a random number would do
return Math.random().toString();
}
var blob = createSomeBlob();
addNamedBlob("test1", blob);
addNamedBlob("test2", createSomeBlob());
console.log(getNamedBlob(blob)); //should be test1
Finally i have found a solution that works to my liking. For our application we already used a serviceworker which has caching active. So i ended up writing the module files into the serviceworker cache whenever somebody has debug mode turned on.
Since the url portion of the resource files is static this way, all the nice browser features such as breakpoints are now useable again.
Below i've posted the relevant code of the serviceworker. The rest of the code is just plain serviceworker caching.
api.serveScript = function(module, script, content){
try{
content = atob(content);
} catch(err){}
return new Promise(function(resolve, reject){
var init = {
status: 200,
statusText: "OK",
headers: {'Content-Type': 'text/javascript'}
};
caches.open("modulecache-1").then(function(cache) {
console.log('[ServiceWorker] Caching ' + module + "/" + script);
cache.put("/R/" + module + "/script/" + script, new Response(content, init));
resolve("/R/" + module + "/script/" + script);
});
});
}
Thanks for your answers and help. I hope this solution is going to help some others too.
#Keith's option is probably the best one. (create a Map of your blobURIs and easy to read file names).
You could also do a dynamic router that will point some nice url to the blobURIs, but if you are open to do this, then just don't use blobURIs.
An other hackish workaround, really less cleaner than the Map, would be to append a fragment identifier to your blobURI blob:https://example.com/0613efd7-6977-4872-981f-519eea0bc911#script_name.js.
Beware, This should work for application/javascript Blobs or some other resource types, but not for documents (html/svg/...) where this fragment identifier has a special meaning.
var hello = new Blob(["alert('hello')"], {type:'application/javascript'});
var script = document.createElement('script');
script.src = URL.createObjectURL(hello) + '#hello.js';
document.head.appendChild(script);
console.log(script.src);
var css = new Blob(["body{background:red}"], {type:'text/css'});
var style = document.createElement('link');
style.href = URL.createObjectURL(css) + '#style.css';
style.rel = 'stylesheet';
document.head.appendChild(style);
console.log(style.href);
And as a fiddle for browsers which doesn't like null origined StackSnippet's iframes.

Accessing file with JS when files are a folder deeper than domain

We have a MVC site which uses subdomains. Not in the traditional sub.domain.com but instead we are using domain.com/sub. The source files all exist in the sub folders of each sub domain because each might have some slightly different things. This causes the Dev team to have to place JS directly into the razor pages so the razor code was able to update URLs like below.
var temp = $('div').load('#Url.Content("~/Images/Excel.png")');
Unfortunately using a code like below in a separate JS file tries loading from domain.com and not domain.com/sub
var temp = $('div').load('/Content/Templates/warning.html');
Theses add on to the domains and can change with clients. Is there a way to get the domain plus sub when the files are loaded like that in the JS without needing to place the code into the razor? I'd prefer a separation of concerns because we are loading scripts sometimes which aren't even used because of it.
what I always do when in similar situations is that I create a function in the main.js or whatever name your using for your shared js file, modify the URL in the function and use the function as the initiator:
in the main.js:
var loadFile = function(selector,path){
$(selector).load('/sub'+path);
}
and then whenever and wherever you wanna load a file:
var temp = loadFile('div','/Content/Templates/warning.html');
UPDATE
you can upgrade your loadFile function to let it know if it has to load from the root of the website if needed:
var loadFile = function(selector,path,loadFromRoot){
var root=(loadFromRoot) ? '' : '/sub';
$(selector).load(root+path);
}

How to create file(.apk) from URL in Jaggery?

I have application store and applications have their url. I want to download apks from those urls to my jaggery server. Although below code(my first solution) create myApp.apk successfully, its not work properly.
First i tried to below code,
var url = "http://img.xxx.com/006/someApp.apk";
var data = get(url, {});
var file = new File("myApp.apk");
file.open("w");
file.write(data.data);
file.close();
when i print data.data value, its look like
i also tried,
var file = new File("http://img.xxx.com/006/someApp.apk");
file.saveAs("myApp.txt");
Can anyone help me?
.apk files are Android application files, and they are expected to start with PK, because they are actually zip archives!
They're not meant to be unzipped, although you can do it to see some of the application resources (but there are better ways for reverse engineering .apk files such as Apktool, if that's what you're looking for).
According to jaggery documentations, file.write is writing the String representation of the object to the file. So that's why you are getting an apk file which cannot be installed.
However you can make it work using copyURLToFile in apache commons-io java library as follows since jaggery supports java itself and all of WSO2 products have apache commons-io library in their class path.
<%
var JFileUtils = Packages.org.apache.commons.io.FileUtils;
var JUrl = Packages.java.net.URL;
var JFile = Packages.java.io.File;
var url = new JUrl("http://img.xxx.com/006/someApp.apk");
JFileUtils.copyURLToFile(url, new JFile("myApp.apk"));
print("done");
%>
Your file will be stored on $CARBON_HOME directory by default, unless you specified relative or absolute path to the file.

How should I create relative paths in javascript using MVC3?

I am having some difficulty aligning my paths without a hardcode in javascript. I am running an asp.net MVC3 web application.
If my path is of the form
var url = 'http://serverNameHardcode/websiteNameHardcode/service/service?param1=' + param;
Then things work fine when I do
$.get(url,
{},
function (data) {alert('callback success');},'json');
I would like to create a relative path. I tried
var url = 'service/service?param1=' + param;
And this works when I run locally and also in Firefox, but not in IE7. When I publish to the server without the hardcode the callback never fires. I know MVC-3 adds some complexity to routing, but I do not know if it applies to this situation; so, I marked this question as such.
How should I setup my path so I don't need hardcodes?
Just write out the app path as a global js variable from your master view, then compose links as
APPPATH + "path/whatever"
Just had to solve this for one of my jQuery plugins, where it is preferable not to modify anything global (i.e. outside the scope of the plugin use) so I had to disregard the marked answer.
I also found that because I host DEV locally in IIS I could not use a root-relative path (as localhost is not the root).
The solution I came up with extended what I had already started with: a data-controller attribute specifying which controller to use in the element I am applying my plugin to. I find it preferable to data-drive the controller names so the components can be more easily reused.
Previous:
<div data-controller="Section">
Solution:
<div data-controller="#Url.Content("~/Section")">
This injects the server root (e.g. /Test.WindowsAzure.Apr2014/ before the controller name so I wind up with /Test.WindowsAzure.Apr2014/Section which is perfect for then appending actions and other parameters as you have. It also avoids having an absolute path in the output (which takes up extra bytes for no good reason).
In your case use something like:
// Assuming $element points to the element your plugin/code is attached to...
var baseUrl = $element.data('controller');
var url = baseUrl + '/service?param1=' + param;
Update:
Another approach we now use, when we do not mind injecting a global value, is Razor-inject a single global JavaScript variable onto window in the layout file with:
<script>
window.SiteRoot = "#Url.Content("~/")";
</script>
and use it with
var url = window.SiteRoot + '/service?param1=' + param;
One option:
var editLink = '#Url.Action("_EditActivity", "Home")';
$('#activities').load(editLink + "?activityID=" + id);
another example:
var actionURL = '#Url.Action("_DeleteActivity", "Home")';
$('#activities').load(actionURL + "?goalID=" + gID + "&activityID=" + aID);
If you don't need to add to the string:
$('#activities').load('#Url.Action("_Activities", "Home", new { goalID = Model.goalID},null)');
I really need the path to get this to work, maybe its IE7. Who knows. But this worked for me.
Grab the URL and store it somewhere. I chose to implement the data attribute from HTML5.
<div id="websitePath" data-websitePath='#Request.Url.GetLeftPart(System.UriPartial.Authority)#Request.ApplicationPath'></div>
Then when you need to perform some AJAX or otherwise use a URL in javascript you simply refer to the stored value. Also, there are differences in the versions of IIS (not cool if your devbox is IIS5 and your server is IIS7). #Request.ApplicationPath may or may not come back with a '/' appended to the end. So, as a workaround I also trim the last character if it is /. Then include / as part of the url.
var urlprefix = $('#websitePath').data('websitepath');
urlprefix = urlprefix.replace(/\/$/, "");
var url = urlprefix + '/service/service?param1=' + param;
While the accepted answer is correct I would like to add a suggestion (i.e. how I do it).
I am using MVC, and any ajax request goes to a controller. My controllers have services so if a service call is required the controller will take of that.
So what's my point? So if ajax always communicates with a controller, then i would like to let the MVC routing resolve the path for me. So what I write in Javascript for url is something like this:
url: 'controller/action'
This way there is no need for the root path etc...
Also, you can put this in a separate Javascript file and it will also work whereas #Url.Content will need to be called on the view.

Javascript in Virtual Directory unaware of Virtual Directory

Say I have the site
http://localhost/virtual
where virtual is the virtual directory
I have an Ajax request that is defined in a javascript file using JQuery
$.getJSON("/Controller/Action")
When this is called, the client tries to find the url at the root level i.e.
http://localhost/Controller/Action
If I add the tilde (~) symbol in, it turns into
http://localhost/virtual/~/Controller/Action
It should (if it was to do what I wanted) resolve to
http://localhost/virtual/Controller/Action
Any ideas on how to fix this?
Aku's hint above looked right but it didn't want to work for me. Finally I figured out to use it like this
<script type="text/javascript">
var config = {
contextPath: '<%= #Url.Content("~") %>'
};
</script>
and then in my JavaScript I use it like this
config.contextPath + 'myAppPath".
So in case of no virtual directory this resolves to
"/" + "myAppPath"
and in case of a virtual directory this resolves to
"/VirtualPath/" + + "myAppPath"
and this finally worked for me.
I used this solution successfully
Place the following element in your masterpage
<%= Html.Hidden("HiddenCurrentUrl", Url.Action("Dummy"))%>
Declare a global variable in your main javascript file
var baseUrl = "";
Set baseUrl to the value of "HiddenCurrentUrl" when your javascript is loaded
baseUrl = $("#HiddenCurrentUrl").val();
baseUrl = baseUrl.substring(0, baseUrl.indexOf("Dummy"));
Use baseUrl
$.getJSON(baseUrl + "Action")
EDIT Improved solution
In your controller
ViewBag.BaseUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath + "/";
In your master page
<script type="text/javascript">
var YourNameSpace = YourNameSpace || {};
YourNameSpace.config = {
baseUrl: "#ViewBag.BaseUrl"
}
</script>
Use your baseUrl
$.getJSON(YourNameSpace.config.baseUrl + "Action")
Another way to get a base url is
<script type="text/javascript">
window.g_baseUrl = '#Url.Content("~")';
</script>
For example, if you run your app from SomeName virtual directory then
window.g_baseUrl variable will be equal to /SomeName/
Benefit of this method is an ability to call actions in the other controllers like so
$.getJSON(window.g_baseUrl + "AnotherController/Action")
Maybe,$.getJSON("Controller/Action") will do?
The tilde shortcut for your application root path is a special feature of ASP.NET, not part of URLs themselves. Consequently trying to use a URL with a tilde in from JavaScript won't resolve the site root, it'll just give you a literal ~ as you can see.
You'd need to pass the value of the application root path to JavaScript so it can construct URLs itself. I'm not that familiar with ASP.NET but I believe you could do something like:
<script type="text/javscript">
var approot= <%= JavaScriptSerializer.Serialize(Request.ApplicationPath) %>;
... $.getJSON(approot+'/Controller/Action') ...;
</script>
A simpler way to do it if you know there's a link on the page to the approot would be to read the href of that link:
var approot= $('#homepagelink').attr('href');
Relative Path to the JS file was the only solution I found
$.getJSON("../Controller/Action")
I know this question is very old but I was lately struggling with this issue and was able to resolve it using
url:'<%=VirtualPathUtility.ToAbsolute("~/Include/cntrols/Data.aspx") %>',
this works great in my ajax call...
It is too late to answer this question. But may be useful to someone as I had same problem. Instead of doing all this steps mentioned in above answers, better way is to use
Url.Action('action','controller').
It'll generate url /VIRDIR/controller/action if it is running from virtual directory or generate /controller/action in other case.

Categories

Resources