ASP.NET Core's wwwroot is included in path by wiredep and gulp-inject..how can I exclude it? - asp.net-core

We have a *.sln that includes an ASP.NET Core RC2 *.csproj for client html only (ASP.NET Controllers are in another *.csproj).
This gives the following folder/file structure:
SolutionRoot/
ClientProjectRoot/ <- project root, npm root folder
wwwroot_dev/ <- location of src dev files,
wwwroot/ <- where gulp concats, minimifies, optimises, and root of static pages
bower_packages/
node_modules/
package.json
bower.json
.bowerrc <- where 'directory' is set to 'wwwroot/bower_packages/'
gulpfile.js
Requirements I'd like to meet are:
The csproj is only client artifacts, with no asp.net C# code, so that we can give the whole project to external devs with UI expertise, and slot it back into the solution when done.
The wwwroot/index.html file should be accessible as http://example.com/index.html -- not http//example.com/wwwroot.html
CSS and JS should be minified, and in wwwroot, and html picked up from there (ie wwwroot_dev is there just for editing purposes but never served from directly).
No idea where bower packages should be -- part of this question.
The gulpfile has tasks defined, which correctly minify the css and scripts found in wwwroot_dev into app.min.js and app.min.css within wwwroot.
It's the html files, passed through gulp-inject and wiredep that get their relative pathing wrong. They both include wwwroot in the output.
My files so far are:
.bowerrc:
{
"directory":"wwwroot/bower_components"
}
And in gulpfile.js, the html task looks as follows:
gulp.task('dist:html',['dist:scripts'],function(){
//get the dest js and css that previous tasks have already minifieded:
var sources = gulp.src(
['wwwroot/scripts/**/*.js', 'wwwroot/scripts/**/*.css'],
{read:false}
);
return gulp
.src("wwwroot/scripts/**/*.html", {})
.pipe(plugins.inject(sources, {relative:true}))
.pipe(plugins.wiredep(sources,{relative:true}))
.pipe(gulp.dest("wwwroot/");
});
The output is (wrong) as it mentions wwwroot/, when it simply be ../js/ etc:
<!-- bower:js -->
<script src="../wwwroot/bower_components/jquery..."></script>
<!-- endbower -->
<!-- inject:js -->
<script src="/wwwroot/js/main.min.js"></script>
<!-- endinject -->
I serve from wwwroot:
gulp.task('serve',function(){
return gulp
.src('wwwroot')
.pipe(plugins.webserver(
{ directoryListing:false,open:"http://localhost:8000/"}))
}
I've tried lots of different inject and wiredep option flags (relative:true, ignorePath, cwd, -- but wwwroot is always mentioned. Can't get rid of it!)
So my question is...
a) is my directory structure approximately right -- or totally flawed
b) if basically right, what tweak can I do to get the paths generated by inject and wiredep to be relatively right?
Thank you!

Try this
gulp.task('render', function () {
var target = gulp.src('./Views/Shared/_Layout.cshtml');
var sources = gulp.src([path.wwwroot + "/**/*.js", path.wwwroot + "/**/*.css"], { read: false });
return target.pipe(inject(sources, {
transform: function (filepath) {
//Delete wwwroot
for (var i = 0; i < arguments.length; i++) {
if (typeof (arguments[i]) == 'string')
arguments[i] = arguments[i].replace("/wwwroot", '');
}
return inject.transform.apply(inject.transform, arguments);
}
}))
.pipe(gulp.dest('./Views/Shared'));

Had the same issue, solved it based on this solution:
https://stackoverflow.com/a/34581414
gulp.task('inject', function () {
var target = gulp.src('src/_Layout.cshtml');
return target.pipe(inject(
gulp.src(paths.wwwroot + 'css/**/*.css', { read: false }),
{
transform: function (filePath) {
var newPath = filePath.replace('/wwwroot', '');
return '<link rel="stylesheet" href="' + newPath + '"/>';
}
})
)
.pipe(gulp.dest('Views/Shared'));
});

Related

How to download a PDF in Vue

So, here I've got a locally stored file named "its_me.pdf" in the assets folder.
I'm trying to reference a download to the PDF using an HTML tag
<a href="../assets/its_me.pdf" download>PDF</a>
It is a real PDF file, if I go double click on the file manually I can see it display and it's real. However, when I go to my application on: http://localhost:4200/its_me (name of route in which it lives), and click on the link, I get a "Failed - No File" error.
Based on #AkashBhave answer I was able to get to work this way.
In my script tag:
data () {
return {
publicPath: process.env.BASE_URL
}
}
then in my template.
<a:href="`${publicPath}whatever.pdf`" download="download">PDF</a>
Alternatively with webpack, in your vue.config.js you add this;
chainWebpack: config => {
config.module
.rule("pdf")
.test(/\.pdf$/)
.use("file-loader")
.loader("file-loader");
}
then in the script tag;
data () {
return {
pdfLink: require("#/assets/whatever.pdf"),
}
}
Finally, in the template;
<a :href="pdfLink" download="download">PDF</a>
Relative imports should work by default with Vue. Try putting your PDF file into the /public folder of your application.
You can then reference the file using string interpolation, like so:
<link rel="icon" href="<%= BASE_URL %>its_me.pdf">
More information is available at
https://cli.vuejs.org/guide/html-and-static-assets.html#interpolation
If that doesn't work, something might be wrong with your Webpack or build configuration.

include client side js in express.js

I've build a new app with an express-generator so i've got public dir with javascripts i guess for a client side. But i can't get access to this files.
My app.js has for an absolute path
app.use(express.static(path.join(__dirname, 'public')));
But when i put on my index.html page on the bottom of the body like this
<script type="text/javascript" src="/javascripts/main.js">
i've got an error inside a console with a 404 regarding to this script.
you need to install stylus and nib npm modules
var express = require('express')
, stylus = require('stylus')
, nib = require('nib')
function compile(str, path) {
return stylus(str)
.set('filename', path)
.use(nib())
}
app.use(stylus.middleware(
{ src: __dirname + '/public'
, compile: compile
}
))
app.use(express.static(__dirname + '/public'))
I am developing something similar. I have my javascript files inside js folder in public folder. This is my link to javascript and I am not getting any error:
<script src="js/options.js"></script>
I think you needed to remove a common slash in "src" tag or properly close the "script"

Using Bower with Express

I'm a late arrival to the Bower scene. I thought I'd try it with my current Express project. I installed it, and created the .bowercc and bower.json file per instructions. I installed a Bootstrap skin I planned on using, which brought with it jQuery. The thing is, you get tons of files, and I'd like to use just the minified versions of JS, CSS and fonts.
After scowering the net, I found a lot about using gulp or grunt to sift through the files, and pipe them to the /public folder Express provides. My question is: how do you do it properly? How do I get just the files I need there? Or am I better off foregoing bower and just downloading the zip file, picking up the end result and placing in the /public folder?
Looking at the comments, it seems like the answer is yes - manual job is required to get your components distributeables to your public folder. Using gulp will automate it, but basically it'd be a hit-and-miss at first, requiring some fine tuning. In case someone lands on this question, here's the solution I went with:
1) Provide package overrides in the bower.json file to ake sure only the minified files are exposed:
{
"name": "charlie",
"dependencies": {
"bootstrap-material-design": "~0.3.0"
},
"overrides": {
"bootstrap-material-design": {
"main": ["**/dist/js/*.min.js", "**/dist/css/*.min.css", "**/dist/fonts/*"]
},
"jquery": {
"main": "**/dist/jquery.min.js"
}
}
}
2) Use the main-bower-files gulp package to grab those "mains" and distribute them to the final locations. Here's my gulpfile.json (just the bower part:
var bower = require('main-bower-files');
var gulpFilter = require('gulp-filter');
var uglify = require('gulp-uglify');
var minifyCSS = require('gulp-minify-css');
var clean = require('gulp-clean');
var debug = require('gulp-debug');
var getDist = function(vendor) {
var publicDir = 'public';
var dist = vendor ? publicDir + '/vendor' : publicDir;
return {
dir: dist,
css: dist + '/css/',
js: dist + '/js/',
fonts: dist + '/fonts/'
};
};
gulp.task('cleanVendor', function() {
return gulp.src(getDist(true).dir, {read: false})
.pipe(clean());
});
gulp.task('bower', ['cleanVendor'], function() {
var dist = getDist(true);
var jsFilter = gulpFilter('**/*.js');
var cssFilter = gulpFilter('**/*.css');
var fontsFilter = gulpFilter(['**/*.woff*', '**/*.eot', '**/*.svg', '**/*.ttf']);
return gulp.src(bower())
.pipe(fontsFilter)
.pipe(gulp.dest(dist.fonts))
.pipe(fontsFilter.restore())
.pipe(jsFilter)
.pipe(gulp.dest(dist.js))
.pipe(jsFilter.restore())
.pipe(cssFilter)
.pipe(gulp.dest(dist.css))
.pipe(cssFilter.restore());
});
3) In your HTML file, include /vendor/js/blah.min.js or /vendor/css/blah.min.css
Note: the annoying part was that I had to specify every font extension in the fontsFilter. I tried using '**/fonts/*' but main-bower-files returns a flat list of files, and if you provide the {base: 'mybase'} parameter, it returns a tree, meaning you get the entire tree structure per file - anyone who can come up with a fix, is invited to submit an answer.

jQuery not defined + MVC4

Im creating the below MVC view that has got some jquery script in it.
However this script is not getting executed. Getting jQuery undefined error.
I want to write including script directly in view instead of using layout page.
Can somebody advise what am I doing wrong here?
#{
ViewBag.Title = "FileUpload";
}
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - What up boyeez!</title>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-ui-1.10.0.min.js"></script>
<h2>FileUpload</h2>
#using (Html.BeginForm("UploadFile", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary();
<ol>
<li class="lifile">
<input type="file" id="fileToUpload" name="file" />
<span class="field-validation-error" id="spanfile"></span>
</li>
</ol>
<input type="submit" id="btnSubmit" value="Upload" />
}
</body>
</html>
<script type="text/jscript">
(function ($) {
function GetFileSize(fileid) {
try {
var fileSize = 0;
if ($.browser.msie) {
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size;
fileSize = fileSize / 1048576;
}
else {
fileSize = $("#", fileid)[0].files[0].size
fileSize = file / 1048576;
}
return fileSize;
}
catch (e) {
alter("Error is: " + e);
}
}
function getNameFromPath(strFilepath) {
debugger;
var objRE = new RegExp(/([^\/\\]+)$/);
var strName = objRE.exec(strFilepath);
if (strName == null) {
return null;
}
else {
return strName[0];
}
}
$("#btnSubmit").live("click", function () {
debugger;
if ($('#fileToUpload').val == "") {
$("#spanfile").html("Please upload file");
return false;
}
else {
return checkfile();
}
});
function checkfile() {
var file = getNameFromPath($("#fileToUpload").val());
if (file != null) {
var extension = file.subst((file.last('.') + 1));
switch (extension) {
case 'jpg':
case 'png':
case 'gif':
case 'pdf':
flag = true;
break;
default:
flag = false;
}
}
if (flag == false) {
$("#spanfile").text("You can upload only jpg, png, gif, pdf extension file");
return false;
}
else {
var size = GetFileSize('fileToUpload');
if (size > 3) {
$("#spanfile").text("You can upload file up to 3 MB");
return false;
}
else {
$("#spanfile").text("");
}
}
}
$(function () {
debugger;
$("#fileToUpload").change(function () {
checkfile();
});
});
})(jQuery);
You are missing a reference to jquery itself. You probably also want a css file for jquery ui:
<link rel="stylesheet" href="css/themename/jquery-ui.custom.css" />
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui.custom.min.js"></script>
See the "Basic Overview: Using jQuery UI on a Web Page" section on the jquery-ui learning docs for full details of how to use and customise jquery ui.
Razor techniques for jquery files
To make your life easier in your view template, you could use the scripts render function:
#Scripts.Render("~/Scripts/jquery-1.9.1.min.js")
#Scripts.Render("~/Scripts/jquery-ui-1.10.0.min.js")
In itself, not too impressive: the syntax is slightly more expressive and 5 characters shorter, that's all.
But it leads you into bundles (references at the end), which are really what you should be using.
Bundles are awesome
Bundles allow you to:
Group dependent files: grouping js and/or css files together reduces the chances of this happening, and also means you can "modularise" your own scripts into multiple files in one folder.
Increase performance: Send out everything inside a single Bundle in a single file - speeding up load times for clients by reducing the number of http requests from the browser
Help development: Use non-minified javascripts (and css) for debugging during development
Publish without changes to code: Use the minified scripts for live deployment
Use in-built minifying for your own scripts
Optimise client experience: Use CDNs for standard scripts like jquery (which is better for your users)
Upgrade easily: Not have to change code when you update your version numbers for things like jquery through NuGet by use of the {version} wildcard (as below)
Example:
// This is usually in your MVC 4 App_Start folder at App_Start\BundleConfig
public class BundleConfig {
public static void RegisterBundles(BundleCollection bundles) {
// Example with full use of CDNs in release builds
var jqueryCdnPath = "https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js";
bundles.Add(new ScriptBundle("~/bundles/jquery", jqueryCdnPath).Include("~/Scripts/jquery-{version}.js"));
And in your razor file you only need a tiny change:
#Scripts.Render("~/bundles/jquery");
This will:
send out the full jquery script during debugging
send out the minified script for a release build
even minify your own bundles such as #Scripts.Render("~/bundles/myScripts"); for live builds
Bundle details
Under the hood bundles will use the CDNs, or minify your own scripts as well, or send already minified files (like jquery-1.9.1.min.js) during release builds, but you can control this by using bundles.UseCdn and BundleTable.EnableOptimizations inside your RegisterBundles method. By using this along with AppSettings in your web.config you can have very close control so that you could even send out debugging scripts for certain users on a live site.
Also note the use of {version} in the bundle configuration.
You can include multiple scripts in a bundle as well:
bundles.Add(new ScriptBundle("~/bundles/jqueryWithUi")
.Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui-{version}.js"
));
This razor command will now send out both files for you:
#Scripts.Render("~/bundles/jquery");
And you can use bundles for css:
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
References:
www.asp.net - Bundling and Minification
You're loading the jQuery UI library without loading the jQuery library.
<script src="~/Scripts/path/to/jquery"></script
<script src="~/Scripts/jquery-ui-1.10.0.min.js"></script
I was having the same problem of client side validation not working. I brought up the JavaScript console in Chrome and saw I was receiving an error stating "JQuery was not defined.".
Turns out I had some code in my View that was causing problems with jQuery not loading.
Recommendation to others who come across this, check your JS console in your browser to ensure you are not getting a JQuery error.

Ensure phonegap and plugins load before Sencha loader

I have written an application in Sencha Touch 2.1, of which I embed a package build into Cordova/PhoneGap 2.5.0 and compile in xCode to run on iOS Simulator / iOS. I have added the PGSQLite plugin to PhoneGap, and built my own PhoneGap/SQLite Proxy for Sencha, which I used on a few of my Stores.*
Problem: When I embed a package build into PhoneGap and run in iOS Simulator, I see that Cordova does not load before Sencha initializes. I see this because my calls in my Sencha app to Cordova.exec that I make in my Proxy initialization result in an error telling me that the Cordova object cannot be found.
I do successfully use Cordova.exec later in my application to run things like the Childbrowser plugin for PhoneGap, and it works. But using Cordova.exec at an early stage in the app's execution, i.e., initialization, is too soon to guarantee that the Cordova object will have been instantiated.
Already tried: I already tried the following approaches:
I tried simply embedding the developer build of my Sencha app into PhoneGap. Although this worked, I don't want to deploy my development build as my released app because it is inefficient and takes up a lot of space. I have learned from this experiment, however, that the way the Sencha Touch microloader works on package and production builds loads PhoneGap after Sencha. This can be clearly seen when inspecting the DOM after Sencha loads in a package build.
I have already configured my app.json file to include PhoneGap and
my plugins before app.js and the Sencha Touch framework. Playing
with the order of my JS file references in my app.json did not
seem to affect the load order.
I also tried creating a script loader, as described here
(StackOverflow). I then ran the script loader for Cordova, and in
the callback for that, ran the script loader for my plugin, and
then, finally, in the callback for that, ran the Sencha Touch
microloader. This resulted in an error. Additionally, I had to
manually set that up in my index.html file after Sencha built my
package. This seems unacceptable.
What I am looking for: I am looking for answers to the following:
Is there a way to configure Sencha's microloader or my Sencha app in general so that Cordova is ensured to have loaded before Sencha's microloader runs?
Is there a way to set this up so that using Sencha Cmd still works, and I don't have to hack around in my index.html file after I build the app?
Note:
*Please don't suggest I use the existing, so-called, SQLite Proxy for Sencha. I specifically chose my approach because, though I appreciated the existing work on a SQLite proxy for Sencha Touch 2 (namely, this), it is actually a WebSQL proxy that does not store natively in SQLite on iOS. My proxy uses the PGSQLite plugin for PhoneGap to natively store data in SQLite on iOS. I plan to open-source it when I have an opportunity to clean it up and untangle it from my code.
I ended up solving this myself by building a custom loader. I am not sure if there is a more Sencha-ish way to do it, but here are the details of what I did, which does work, in case anyone else wants to ensure that PhoneGap is completely loaded in package and production builds before running anything in Sencha. (That would probably be the case in all scenarios in which PhoneGap is packaging a Sencha app).
My index.html file:
<!DOCTYPE HTML>
<html manifest="" lang="en-US">
<head>
<!-- Load Cordova first. Replace with whatever version you are using -->
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function onBodyLoad() {
// Check for whatever mobile you will run your PhoneGap app
// on. Below is a list of iOS devices. If you have a ton of
// devices, you can probably do this more elegantly.
// The goal here is to only listen to the onDeviceReady event
// to continue the load process on devices. Otherwise you will
// be waiting forever (literally) on Desktops.
if ((navigator.platform == 'iPad') ||
(navigator.platform == 'iPhone') ||
(navigator.platform == 'iPod') ||
(navigator.platform == 'iPhone Simulator') ||
(navigator.platform == 'iPadSimulator')
) {
// Listening for this event to continue the load process ensures
// that Cordova is loaded.
document.addEventListener("deviceready", onDeviceReady, false);
} else {
// If we're on Desktops, just proceed with loading Sencha.
loadScript('loader.js', function() {
console.log('Finished loading scripts.');
});
}
};
// This function is a modified version of the one found on
// StackOverflow, here: http://stackoverflow.com/questions/756382/bookmarklet-wait-until-javascript-is-loaded#answer-756526
// Using this allows you to wait to load another script by
// putting the call to load it in a callback, which is
// executed only when the script that loadScript is loading has
// been loaded.
function loadScript(url, callback)
{
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
// Attach handlers for all browsers
var done = false;
script.onload = script.onreadystatechange = function()
{
if( !done && ( !this.readyState
|| this.readyState == "loaded"
|| this.readyState == "complete") )
{
done = true;
// Continue your code
callback();
}
};
head.appendChild(script);
}
function onDeviceReady() {
console.log("[PhoneGap] Device initialized.");
console.log("[PhoneGap] Loading plugins.");
// You can load whatever PhoneGap plugins you want by daisy-chaining
// callbacks together like I did with pgsqlite and Sencha.
loadScript('pgsqlite_plugin.js', function() {
console.log("[Sencha] Adding loader.");
// The last one to load is the custom Sencha loader.
loadScript('loader.js', function() {
console.log('Finished loading scripts.');
});
});
};
</script>
<meta charset="UTF-8">
<title>Sencha App</title>
</head>
<!-- Don't forget to call onBodyLoad() in onLoad -->
<body onLoad="onBodyLoad();">
</body>
</html>
Next, create a custom loader in loader.js in your document root, alongside your index.html. This one is heavily based on the development microloader that comes with Sencha. Much props to them:
console.log("Loader included.");
(function() {
function write(content) {
document.write(content);
}
function meta(name, content) {
write('<meta name="' + name + '" content="' + content + '">');
}
var global = this;
if (typeof Ext === 'undefined') {
var Ext = global.Ext = {};
}
var head = document.getElementsByTagName("head")[0];
var xhr = new XMLHttpRequest();
xhr.open('GET', 'app.json', false);
xhr.send(null);
var options = eval("(" + xhr.responseText + ")"),
scripts = options.js || [],
styleSheets = options.css || [],
i, ln, path;
meta('viewport', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no');
meta('apple-mobile-web-app-capable', 'yes');
meta('apple-touch-fullscreen', 'yes');
console.log("Loading stylesheets");
for (i = 0,ln = styleSheets.length; i < ln; i++) {
path = styleSheets[i];
if (typeof path != 'string') {
path = path.path;
}
var stylesheet = document.createElement("link");
stylesheet.rel = "stylesheet";
stylesheet.href = path;
head.appendChild(stylesheet);
}
for (i = 0,ln = scripts.length; i < ln; i++) {
path = scripts[i];
if (typeof path != 'string') {
path = path.path;
}
var script = document.createElement("script");
script.src = path;
head.appendChild(script);
}
})();
Notice that your index.html file does not contain a #microloader script element. That's because you should take it out and use your custom loader.
With all that in place, you will be able to sail smoothly, knowing that the whole PhoneGap environment is in place before your Sencha javascript starts doing things.