ASP.net Rejuicer combine js dynamically - javascript

Im looking at using Rejuicer http://rejuice.me/ to combine all the JS files of my ASP.net MVC site into one JS file. This works ok but it doesnt allow me to add or remove JS files without having to also reset/recycle the application, as all the configuration is set in the Application_Start() event handler.
Does anyone have any ideas on how I can get around this. Or if there is a better alternative to Rejuicer?

Loading configuration in Application_Start is a trade off. Other option is to hook into FileSystemWatcher and wait for folder changes. Given the nature of a web application, this isn't ideal. Some alternative use web.config which also forces a reset.
There are tools like Workbench which does its thing during development (in VS.NET). This removes dependency on the application start cycle and files are there when the app starts up.

In the _layout.cshtml file I have code similar to this. The list of js files for the site can be defined here without having to reset or recompile the site.
#{
//combine all JS files into one file using Rejuicer.
List<string> JsFiles = new List<string>();
//define list of JS files here
JsFiles.Add("~/Scripts/One.js");
JsFiles.Add("~/Scripts/Two.js");
if (System.Web.HttpContext.Current.Application["JsFileListing"] != null)
{
var JsFileRejuiced = (List<string>)System.Web.HttpContext.Current.Application["JsFileListing"];
//check if we have any new/removed/renamed files
if (JsFiles.Except(JsFileRejuiced).Count()> 0 || JsFileRejuiced.Except(JsFiles).Count() > 0)
{
//force application reset
HttpRuntime.UnloadAppDomain();
}
}
if (System.Web.HttpContext.Current.Application["JsFileListing"] == null)
{
var Combiner = Rejuicer.OnRequest.ForJs("~/Combined.js").Combine;
foreach (var file in JsFiles)
{
Combiner.File(file);
}
Combiner.Configure();
System.Web.HttpContext.Current.Application["JsFileListing"] = JsFiles;
}
}
#Rejuicer.Rejuiced.JsFor("~/Combined.js")

Related

WordPress - ERR_BAD_RESPONSE admin-ajax-php file upload

I'm trying to upload files in WordPress using admin-ajax.php
I have this code in my functions.php file
function upload_docs(){
var_dump($_FILES);
}
add_action('wp_ajax_nopriv_upload_docs', 'upload_docs');
add_action('wp_ajax_upload_docs', 'upload_docs');
The function at the moment is a test that I want to use to debug what information is passed from the front-end which is a Vue app hosted in a page template.
I've correctly loaded and localized the Vue CSS and js files and after the build, in my localhost, I'm able to pass the other forms I have configured on my functions file
On the front-end side, the Vue app has this method that will add the needed information to the WordPress backend
sendUploadForm(){
let documents = this.$refs.uploadedFiles.files
let userData = new FormData()
for(let i = 0; i < documents.length; i++ ){
userData.append('file[]', documents[i])
}
userData.append('action', 'upload_docs')
axios.post(wp_param.ajaxurl, userData).then( res => {
console.log(res)
}).catch( e => console.log(e) )
}
What is going wrong with the code? I will always get a 500 error status code ERR_BAD_RESPONSE and I don't know if the function is called because I'm unable to see any var_dump or var_export from PHP. I've tried to enable the debug in wp-config file but nothing changed.
Any suggestion?
Add these additional two lines under your WP_DEBUG one, make the error happen again, and check in the folder wp-content/ if you see a new file debug.log.
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
Consider:
Implementing nonces and permission checks to protect your endpoints
If only logged in users are supposed to be able to upload files, ensure the no_priv method is properly locked down
Using a custom REST API endpoint instead of admin-ajax https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/
Terminate your function with wp_die(); when using AJAX in WordPress
I was stuck with this problem because of WordPress plugin conflicts.
You can disable unused plugins and check.

How do I load antlr/index into ace worker js file?

I am following the instruction given here to integrate antlr4 with ace editor and I have trouble at the step var antlr4 = require('antlr4/index');. The author mentions that here we should use require for nodejs. However, ACE has another require that may cause problems. Thus he loaded another script for nodejs require and load antlr4/index with require in that script.
I tried that one, too. But it always cannot find the script. From the console of my browser, I can see the path it loads the script is:
localhost:4200/./antlr4/index.js and it fails to load it.
I am using Angular 7, and the structure of my project is as follows:
Also, when loading some local javascript file using importScripts, I always fails by giving the local path, however, giving URL from CDN will always work. But importScripts should support local file importing.
Where should I make changes and what else methods should I try?
Here are some of my code:
var ace_require = require;
window.require = undefined;
var Honey = { 'requirePath': ['..'] };
//importScript{"require.js"}
//the script can't be imported through importSctipt so I pasted the
//whole script file under...(not shown here)
var antlr4_require = window.require; // antlr4_require:antlr using nodejs require;
window.require = require = ace_require; // require:ace using its own require
var antlr4, LPMLNLexer, LPMLNParser;
try {
window.require = antlr4_require;
antlr4 = antlr4_require('antlr4/index');
//the browser stuck here reporting error...
} finally {
window.require = ace_require;
}

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);
}

Unity WebGL External Assets

I'm developing some webGL project in Unity that has to load some external images from a directory, it runs all fine in the editor, however when I build it, it throws a Directory Not Found exception in web console. I am putting the images in Assets/StreamingAssets folder, that will become StreamingAssets folder in the built project (at root, same as index.html). Images are located there, yet browser still complains about not being able to find that directory. (I'm opening it on my own computer, no running web server)
I guess I'm missing something very obvious, but it seems like I could use some help, I've just started learning unity a week ago, and I'm not that great with C# or JavaScript (I'm trying to get better...) Is this somehow related to some javascript security issues?
Could someone please point me in the right direction, how I should be reading images(no writing need to be done) in Unity WebGL?
string appPath = Application.dataPath;
string[] filePaths = Directory.GetFiles(appPath, "*.jpg");
According to unity3d.com in webGL builds everything except threading and reflection is supported, so IO should be working - or so I thought:S
I was working around a bit and now I'm trying to load a text file containing the paths of the images (separated by ';'):
TextAsset ta = Resources.Load<TextAsset>("texManifest");
string[] lines = ta.text.Split(';');
Then I convert all lines to proper path, and add them to a list:
string temp = Application.streamingAssetsPath + "/textures/" + s;
filePaths.Add(temp);
Debug.Log tells me it looks like this:
file://////Downloads/FurnitureDresser/build/StreamingAssets/textures/79.jpg
So that seems to be allright except for all those slashes (That looks a bit odd to me)
And finally create the texture:
WWW www = new WWW("file://" + filePaths[i]);
yield return www;
Texture2D new_texture = new Texture2D(120, 80);
www.LoadImageIntoTexture(new_texture);
And around this last part (unsure: webgl projects does not seem easily debuggable) it tells me: NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
Can someone please enlighten me what is happening? And most of all, what would be proper to solution to create a directory from where I can load images during runtime?
I realise this question is now a couple of years old, but, since this still appears to be commonly asked question, here is one solution (sorry, the code is C# but I am guessing the javascript implementation is similar). Basically you need to use UnityWebRequest and Coroutines to access a file from the StreamingAssets folder.
1) Create a new Loading scene (which does nothing but query the files; you could have it display some status text or a progress bar to let the user knows what is happening).
2) Add a script called Loader to the Main Camera in the Loading scene.
3) In the Loader script, add a variable to indicate whether the asset has been read successfully:
private bool isAssetRead;
4) In the Start() method of the Loading script:
void Start ()
{
// if webGL, this will be something like "http://..."
string assetPath = Application.streamingAssetsPath;
bool isWebGl = assetPath.Contains("://") ||
assetPath.Contains(":///");
try
{
if (isWebGl)
{
StartCoroutine(
SendRequest(
Path.Combine(
assetPath, "myAsset")));
}
else // desktop app
{
// do whatever you need is app is not WebGL
}
}
catch
{
// handle failure
}
}
5) In the Update() method of the Loading script:
void Update ()
{
// check to see if asset has been successfully read yet
if (isAssetRead)
{
// once asset is successfully read,
// load the next screen (e.g. main menu or gameplay)
SceneManager.LoadScene("NextScene");
}
// need to consider what happens if
// asset fails to be read for some reason
}
6) In the SendRequest() method of the Loading script:
private IEnumerator SendRequest(string url)
{
using (UnityWebRequest request = UnityWebRequest.Get(url))
{
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
// handle failure
}
else
{
try
{
// entire file is returned via downloadHandler
//string fileContents = request.downloadHandler.text;
// or
//byte[] fileContents = request.downloadHandler.data;
// do whatever you need to do with the file contents
if (loadAsset(fileContents))
isAssetRead = true;
}
catch (Exception x)
{
// handle failure
}
}
}
}
Put your image in the Resources folder and use Resources.Load to open the file and use it.
For example:
Texture2D texture = Resources.Load("images/Texture") as Texture2D;
if (texture != null)
{
GetComponent<Renderer>().material.mainTexture = texture;
}
The directory listing and file APIs are not available in webgl builds.
Basically no low level IO operations are supported.

Loading local files in a WebBrowser Control

Im trying to load local files in a WebBrowser on Windows Phone 7.1 but Im always getting exceptions or a blank page.
I tried with
Stream stream = Application.GetResourceStream(
new Uri("./Html/par/index.html",
UriKind.Relative)).Stream;
using (StreamReader reader = new StreamReader(stream))
{
// Navigate to HTML document string
this.webBrowser.NavigateToString(reader.ReadToEnd());
}
this is firing a blank page.
I set index.html and all files needed (css/js) as Content and IsScriptEnable to "true".
Do you have an idea how to solve this problem?
i think the path is incorrect.
do you have /Html/par directories in your project ? secondly is index.html set to content ?
try
var rs = Application.GetResourceStream(new Uri("myFile.html", UriKind.Relative));
using(StreamReader sr = new StreamReader(rs.Stream))
{
this.webBrowser.NavigateToString(sr.ReadToEnd());
}
this might help
http://phone7.wordpress.com/2010/08/08/loading-a-local-html-file-in-the-webbrowser-control/
this might help undertand differences between resource and content
http://invokeit.wordpress.com/2011/09/30/images-and-build-actio-settings-in-wp7/
this link details how to load the file and other linked files
http://transoceanic.blogspot.co.uk/2011/07/wp7-load-local-html-files-and-all.html

Categories

Resources