How do you use data-uri in dotless? - less

I am using dotless (1.4.1 I think) and I have this in my .less file
#btnSearch { background-image: data-uri('/images/btnSearch.png'); }
It throws this error:
Data-uri function could not read file '/images/btnSearch.png' on line 140 in file '/css/less/site.less'
If I change data-uri with url it works (to prove the file exists).
I also tried relative path (../../images/btnSearch.png) as well as some other JPEG images.

The code for the data-uri function on GitHub has the following comments in the exception handling.
// this is more general than just a check to see whether the file exists
// it could fail for other reasons like security permissions
I would check that there are no permission problems, as Dotless needs to read to image to convert it to base64

After messing about with this for ages I did get it to work with a fully qualified local (file system) path.
e.g.
.less input
body {
#divTest {
background-image: data-uri('C:\Users\Ben\Source\Repos\ASPNET\ASPNET\Content\accept.png');
}
}
Output
.#divTest {
border: solid 1px blue;
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAKfSURBVDjLpZPrS1NhHMf9O3bOdmwDCWREIYKEUHsVJBI7mg3FvCxL09290jZj2EyLMnJexkgpLbPUanNOberU5taUMnHZUULMvelCtWF0sW/n7MVMEiN64AsPD8/n83uucQDi/id/DBT4Dolypw/qsz0pTMbj/WHpiDgsdSUyUmeiPt2+V7SrIM+bSss8ySGdR4abQQv6lrui6VxsRonrGCS9VEjSQ9E7CtiqdOZ4UuTqnBHO1X7YXl6Daa4yGq7vWO1D40wVDtj4kWQbn94myPGkCDPdSesczE2sCZShwl8CzcwZ6NiUs6n2nYX99T1cnKqA2EKui6+TwphA5k4yqMayopU5mANV3lNQTBdCMVUA9VQh3GuDMHiVcLCS3J4jSLhCGmKCjBEx0xlshjXYhApfMZRP5CyYD+UkG08+xt+4wLVQZA1tzxthm2tEfD3JxARH7QkbD1ZuozaggdZbxK5kAIsf5qGaKMTY2lAU/rH5HW3PLsEwUYy+YCcERmIjJpDcpzb6l7th9KtQ69fi09ePUej9l7cx2DJbD7UrG3r3afQHOyCo+V3QQzE35pvQvnAZukk5zL5qRL59jsKbPzdheXoBZc4saFhBS6AO7V4zqCpiawuptwQG+UAa7Ct3UT0hh9p9EnXT5Vh6t4C22QaUDh6HwnECOmcO7K+6kW49DKqS2DrEZCtfuI+9GrNHg4fMHVSO5kE7nAPVkAxKBxcOzsajpS4Yh4ohUPPWKTUh3PaQEptIOr6BiJjcZXCwktaAGfrRIpwblqOV3YKdhfXOIvBLeREWpnd8ynsaSJoyESFphwTtfjN6X1jRO2+FxWtCWksqBApeiFIR9K6fiTpPiigDoadqCEag5YUFKl6Yrciw0VOlhOivv/Ff8wtn0KzlebrUYwAAAABJRU5ErkJggg==");
}
Looking at the source in DataUriFunction it's clear the function does not want a fully qualified web address, and claims "Filename must be a local file", but this is confusing as lesscss.org give the following example in their docs
Example: data-uri('../data/image.jpg');
I'd say this was a bug, certainly doesn't seem optimal, but without stepping into the source of dotless.Core.Parser.Functions.DataUriFunction I can't be sure.

Related

Why FileExtensionContentTypeProvider no work with .min.js extension?

I have some css&js files in my project and I used the BuildBundlerMinifier NuGet package to minify and obfuscate them.
For example, the app.js will minify and obfuscate into app.min.js in the same directory.
Now I want the user can access the app.min.js but can't access the app.js.
I do this for I don't want anybody else to access the source code of my js.
Although someone still can get its source code from the app.min.js while I don't want them to get it easily.
I tried to use FileExtensionContentTypeProvider in Configure of startup.cs to achieve this:
var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
provider.Mappings.Remove(".js");
provider.Mappings.Add(new KeyValuePair<string, string>(".min.js", "application/javascript"));
app.UseStaticFiles(new StaticFileOptions()
{
ContentTypeProvider=provider
});
However, after it runs I can access neither app.js nor app.min.js.
What's wrong with my code?
Thank you.
The FileExtensionContentTypeProvider is only meant to provide a mapping from file extension to the correct MIME type. In order to retrieve the file extension from a file name, it will do the following:
private static string? GetExtension(string path)
{
int index = path.LastIndexOf('.');
if (index < 0)
return null;
return path.Substring(index);
}
It will take the very last part of the extension. So with app.min.js, the reported file extension will still be .js and not .min.js, and as such the mapping for .js will be required.
Modifying the MIME type mapping in order to disallow certain file extensions is probably not the best strategy. It would be better to modify the underlying file provider itself to handle that.
Alternatively, if you want to prevent access to non-minified JavaScript files, you could also split the middleware to conditionally prevent serving static files for any request to a path that ends with .js that is not a .min.js:
app.UseWhen(ctx => !ctx.Request.Path.HasValue
|| !ctx.Request.Path.Value.EndsWith(".js")
|| ctx.Request.Path.Value.EndsWith(".min.js"), app2 =>
{
app2.UseStaticFiles();
});

Sending a pdf from public folder in express

I am trying to serve a PDF by adding watermark to it. I am using the image-watermark package for it
let option ={'text' : 'hello','color' : 'rgb(154, 50, 46)'};
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=test.pdf');
fs.createReadStream(watermark.embedWatermark('/pdf/js_tut.pdf', option)).pipe(res);
I am confused at what i did wrong? I am getting a 500 error. did I put the path name wrong? I have a public folder inside which I have a pdf folder inside which i have js_tut.pdf
Looking at the source code for the function embedWatermark, it doesn't actually return anything. You can see that here.
There is not a single return statement anywhere there.
So essentially what you're doing is this:
fs.createReadStream(undefined).pipe(res)
Which is likely why you're getting 500.

Where the statusFiles should be saved?

As mentioned here, I tried to use Status Files with the below code:
install(StatusPages) {
statusFile(HttpStatusCode.NotFound, HttpStatusCode.Unauthorized, filePattern = "#.html")
}
and saved the file as below:
But after running it, I got the standard 404 error, which means the file are not seen, do I need to add some thing, or I'm saving them in wrong place?
It looks like statusFiles() does a resolveResource(path), so it is looking at: src/main/resources/ and in order to make it understand/see the statusFiles folder, which is lying inside the resources folder, the filePattern is required to be tuned little nit to reflect it, so the correct code is:
statusFile(HttpStatusCode.NotFound, HttpStatusCode.Unauthorized, filePattern = "statusFiles/#.html")

gulp-sass missing some functionalities

I'm starting to work on an ongoing development with gulp and sass.
The workflow was set up for someone not avaialable at the momment and it has been working for people on the team.
Sass compiles on other people machines but not on mine.
I do compile sass on my machine in dozens of other projects without problem but not on this particular one.
I think I did initialize the project correctly but I suspect there is some version or configuration problem involved.
If I npm install everything and run gulp I get the following error:
Error: src/sass/utilities/mixins/_vendor-prefixes.scss
Error: Invalid CSS after "::-webkit-": expected "{", was "&-placeholder"
"&-placeholder" may only be used at the beginning of a compound selector.
on line 116 of src/sass/utilities/mixins/_vendor-prefixes.scss
I tried commenting the offending lines and running gulp again just to stumble with another error:
Error: src/sass/base/_base.scss
Error: "ul" failed to #extend "%reset-list".
The selector "%reset-list" was not found.
Use "#extend %reset-list !optional" if the extend should be able to fail.
on line 142 of src/sass/base/_base.scss
And so on:
Error: src/sass/utilities/_placeholders.scss
Error: You may not #extend an outer selector from within #media.
You may only #extend selectors within the same directive.
From "#extend %clearfix" on line 38 of src/sass/modules/_calendar.scss
on line 9 of src/sass/utilities/_placeholders.scss
This code works on other machines and all that advanced selector are being used on the development.
If I google for the particular errors I can find errors about them and people suggesting alternate selectors but I suspect that there is something else going on that I should fix.
I have updated my gulp to 3.9.1 and gulp-sass to 3.1.0 but I get the same errors.
How should I debug this?
Thanks!
EDIT: The errors are clearly stating that the code is not valid but the strange thing is that the same code is working on other peoples machines.
I'll post some code arround some of the errors just for reference anyway:
_vendor-prefixes.scss:116
// Placeholder focus text
#mixin placeholder-focus($color: $input-color-placeholder) {
&:focus::-webkit-&-placeholder { color:$color; }
&:focus:-moz-placeholder { color:$color; } /* FF 4-18 */
&:focus::-moz-placeholder { color:$color; } /* FF 19+ */
&:focus:-ms-input-placeholder { color:$color; }
}
_base.scss:142
// Unordered and Ordered lists
ul,
ol {
#extend %reset-list;
}
and the include on _placeholders.scss
// Reset List
%reset-list {
padding:0;
margin:0;
li {
list-style:none;
}
}
This had nothing to do with functionalities or versions.
As #rac pointed out the code is invalid.
The other developer was skiping the errors somehow and the compiled .css did not have the faulty lines or the faulty extends.
Removing all the faulty lines resulted in the same .css and a clean compile.
Thanks!

Display custom error page on all PHP errors and email them to administrator

Afternoon,
I've been looking around for a while without success to see if there's a method to display a custom error page, whenever any PHP error arises, hiding the error from users - currently achieved by error_reporting(0), then emailing the specific error to my email address.
Initial logic (I know it's not right, it's just to help you understand better):
if(error_reporting){
ob_clean();
include('classes/email.php');
$email = new email($pdo);
$email->mailError(ERROR_REPORT);
include('error-page.php');
die();
}
Any help would be much appreciated, thanks!
Well, you could use a custom error handling function. See set_error_handler()
function sendMailOnError($errno, $errstr, $errfile, $errline, $errcontext) {
$subject = 'An Error Occured';
$body = "An Error Occured\n\n".
"$errstr [$errno]\n".
"File: $errfile\n".
"Line: $errline\n".
"Current local variables: ".print_r($errcontext, true);
//send the email here
}
set_error_handler('sendMailOnError');
You can define a custom error handler function, and have that show the error page, no problem.
The only difficulty with this is with errors that occur after some HTML has already been output. In most cases, you can nevertheless shove a full error page down the browser's throat, but that is horrible practice, as you would essentially output two HTML structures, one of them broken.
What I like to do in such cases is either just output a message, or output a position: fixed div that will overlay anything that has already been output.
Something like
function errorPage($errno, $errstr, $errfile, $errline, $errcontext) {
// Perform some filtering here, you don't want to die on every notice
// or deprecated warning
echo "<div style='position: fixed; left: 0px; top: 0px; bottom: 0px;'>";
// ... you get the drift... add some more styling here
echo "Error message goes here</div>";
}
set_error_handler('errorPage');
The way to show a complete, clean error page, uncluttered by any previous output, is making extensive use of output buffering, and flushing the content only if no error has occurred at the end of the page.
I'm just about to release an open source project that does this, and more. It collects errors, sends them to an issue tracker, detects duplicates, turns them into issues and emails staff.
Details are at https://sourceforge.net/news/?group_id=317819&id=293422 and the version 0.1.7 it mentions is due out in a couple of days.
The open source tracker is at http://elastik.sourceforge.net/
Any feedback welcome,
Thanks