I'm attempting to switch out the css file on the fly - based on which part of the web-system the user is in (i.e. if the user is on mydomain/students/page then the page loads with students.min.css, rather than site.min.css).
I've tried doing it within the _Host.cshtml:
#page "/"
#namespace FIS2withSyncfusion.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#{
Layout = null;
//sniff the requst path and switch the stylesheet accordingly
string path = Request.Path;
string css = "site.min.css";
if (path.ToLowerInvariant().StartsWith("/students"))
{
css = "students.min.css";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Martin's Blazor Testing Site</title>
<base href="~/" />
<link rel="stylesheet" href="css/#(css)" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
<script type="text/javascript">
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob) {
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<script src="_framework/blazor.server.js"></script>
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
</body>
</html>
However, it doesn't seem to hit this codeblock after the first load of the site; meaning whichever page they first landed on denotes the stylesheet for the entire site.
Do I have to put this codeblock on every page or is there another way of doing this?
another way you could approach this is to create components that respond to different styling that you desire. From there you have two options:
Create dedicated css associate with the component. From the docs
Create a class toggle in the code block of the component, similar to how the NavMenu works.
After further experimentation, I've found that adding this block:
#{
//sniff the requst path and switch the stylesheet accordingly
string path = navManager.Uri;
Uri uri = new Uri(path);
List<string> parts = uri.Segments.ToList();
string module = parts[1].ToLowerInvariant().Trim('/');
string css = "site.min.css";
if (module == "students")
{
css = "students.min.css";
}
}
<head>
<link rel="stylesheet" href="css/#(css)" />
</head>
To the top of MainLayout.razor works perfectly - so long as you remove the equivalent block from _Host.cshtml
Related
I tried to apply some of these settings.
Some work, some don't.
//_Layout.cshtml
#using Microsoft.AspNetCore.Components.Web
#namespace BlazorApp1.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="~/" />
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />
<link href="BlazorApp1.styles.css" rel="stylesheet" />
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>
<body>
#RenderBody()
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<environment include="Development">
<script src="_framework/blazor.server.js" autostart="false"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
Blazor.start({
configureSignalR: function (builder) {
let c = builder.build();
c.serverTimeoutInMilliseconds = 5000;
c.keepAliveIntervalInMilliseconds = 2500;
builder.build = () => {
return c;
};
},
reconnectionOptions: {
retryIntervalMilliseconds: 500,
maxRetries: 25
}
});
});
</script>
</environment>
<environment exclude="Development">
<script src="_framework/blazor.server.js"></script>
</environment>
</body>
</html>
[above Code edited to reflect comment.]
Note: the important part is the 2nd script tag, which follows <script src="_framework/blazor.server.js" autostart="false"></script>. Also note, that in this variation I use the DOMContentLoaded event, but some examples simply omit this and only use Blazor.start(...), which IMHO both are valid, and I did not notice any difference so far.
Sidenote: Some sources say that the JS for Starting Blazor should/can be placed in _Host.cshtml. I assume from the project structure, that both styles are valid options. (_Host.cshtml is simply the #RenderBody and holds the App-component, which should result in roughly the same final DOM).
and
//program.cs
builder.Services.AddServerSideBlazor(options =>
{
options.DetailedErrors = true;
}).AddHubOptions(options =>
{
options.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
options.EnableDetailedErrors = true;
options.HandshakeTimeout = TimeSpan.FromSeconds(15);
options.KeepAliveInterval = TimeSpan.FromSeconds(1);
//options.MaximumParallelInvocationsPerClient = 1;
//options.MaximumReceiveMessageSize = 32 * 1024;
//options.StreamBufferCapacity = 10;
});
Test when clicking "PAUSE" in VS Debug-Mode:
When I pause the App in VS, the reconnect UI shows:
Attempting to reconnect to the server: 6 of 35
But each attempt takes over 1:30 minutes (not always the same time)!
Another Test showed: one attempt ~40sec another over ~90sec.
Another Test showed: the first few (5) took a longer time but then for the remaining it was ~7sec consistently.
Specifically maxRetries: 35 works as expected every time, but it seems to me retryIntervalMilliseconds: 1000 does not work at all.
Why is that, what can I do that each attempt takes the same time, and how can I reliably set it up?
Maybe a working example?
Specifically, I'd like to have a setup where each attempt really runs quickly (<1000ms) and a lot of them.
Are there some min values maybe, if so, where is the documentation on that?
[Edit]:
I ran more tests with a remote PC:
With very different results for the time taken of each attempt, depending on how the connection is disturbed.
Firewall (all always 20s)
Wi-Fi (first one 10s then 0.5s)
Browser offline mode (all always 0.5s)
VS Pause / Stop (inconsistent ~40s, ~90s)
Console Output:
I have an image at the URL http://192.168.1.53/html/cam.jpg (from a Raspberry Pi) and this image is changing very fast (it is from a camera).
So I want to have some JavaScript on a website that will reload this image every second for example.
My HTML is:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Pi Viewer</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<style>
img,body {
padding: 0px;
margin: 0px;
}
</style>
<img id="img" src="http://192.168.1.53/html/cam.jpg">
<img id="img1" src="http://192.168.1.53/html/cam.jpg">
<script src="script.js"></script>
</body>
</html>
And my script:
function update() {
window.alert("aa");
document.getElementById("img").src = "http://192.168.1.53/html/cam.jpg";
document.getElementById("img1").src = "http://192.168.1.53/html/cam.jpg";
setTimeout(update, 1000);
}
setTimeout(update, 1000);
alert is working, but the image is not changing :/ (I have 2 images (they are the same))
The problem is that the image src is not altered so the image is not reloaded.
You need to convince the browser that the image is new. A good trick is to append a timestamp to the url so that it is always considered new.
function update() {
var source = 'http://192.168.1.53/html/cam.jpg',
timestamp = (new Date()).getTime(),
newUrl = source + '?_=' + timestamp;
document.getElementById("img").src = newUrl;
document.getElementById("img1").src = newUrl;
setTimeout(update, 1000);
}
I'm working on ASP.NET MVC. I have a problem when using Rotativa to rendering a Pdf page by ViewAsPdf function. It's work fine on Visual Studio debugging, but when published to localhost IIS font size was changed, It's bigger on IIS.
I have compared to HTML page without ViewAsPdf function and no problem, font size does not change, it's changed when I'm using Rotativa.
Here is Controller code:
return new ViewAsPdf(TempData["gridData"])
{
PageSize = Rotativa.Options.Size.A4,
PageOrientation = Rotativa.Options.Orientation.Landscape,
CustomSwitches = string.Format("--footer-left \"Note:.....\" "
+ "--footer-font-size \"8\" "
+ "--footer-right \"Page [page] of [toPage]\" ")
};
This my View code for rendering pdf page:
#model IEnumerable<PM_Calibration.ViewModels.CalibrationDataList>
#{
ViewBag.Title = "Monthly List of Calibration Task";
Layout = null;
}
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/PrintStyle.css" rel="stylesheet" type="text/css" />
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
</head>
<body>
#{
IList<PM_Calibration.ViewModels.CalibrationDataList> ModelList = Model.ToList();
List<PM_Calibration.ViewModels.CalibrationDataList> TableList = new List<PM_Calibration.ViewModels.CalibrationDataList>();
var i=1;
for (int x = 0; x < ModelList.Count; x++ )
{
var item = ModelList[x];
TableList.Add(ModelList[x]);
if(i==24)
{
#Html.Partial("PartialMonthlyCalibration_Table", TableList)
i = 0;
TableList.Clear();
}
i++;
}
}
</body>
I'm not sure is these code enough for this question.
My question is why my font size was changed on localhost IIS?
I have been fighting this issue for quite some time now, and have been (still) unable to print my div with its styling.
Currently, my script is:
$('#printMeButton').click(function () {
//alert("a");
var data = document.getElementById('thisPrintableTable').outerHTML;
var mywindow = window.open('', data);
mywindow.document.write('<html><head><title>Print Me!!!</title>');
// mywindow.document.write('<link rel="stylesheet" type="text/css" href="Site.css" media="screen">');
mywindow.document.write('</head><body>');
mywindow.document.write(data);
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus();
mywindow.print();
mywindow.close();
return true;
});
which is nested within a $(document).ready function.
When I include the desired stylesheet (currently commented out), Nothing appears in the print preview.
I also have some script that has an effect on the appearance of the table, and, as such, I believe this may hold the key of having these included into the popup window.
How can i include this into the new popup?
Could someone please suggest a way of printing this as it stands?
Edit History
removed space at end of </head><body>
Changed var data to have outerHTML instead of innerHTML
Altered Question/details from better understanding of issue
Try to open a local html file using window.open with css linked within it. And set the content html to be printed to the local html file using js.
Here is the page to be printed:-
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="test.css" rel="stylesheet" type="text/css" />
<script src="jquery.js"></script>
</head>
<body>
<div id="print">
<div class="red">TODO write content</div>
</div>
<button id="print_btn">Print</button>
<script>
$('#print_btn').click(function(){
var newWindow = window.open('print.html','_blank');
$(newWindow).load(function(){
$(newWindow.document).find('body').html($('#print').html());
});
})
</script>
</body>
</html>
The css file test.css is linked here, and I'm opening print.html at the time of window.open, the test.css is also linked in the print.html
Now, in print.html I'll write:-
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="test.css" rel="stylesheet" type="text/css" />
</head>
<body>
</body>
</html>
Since you provide an empty string as a new window's URL (the first parameter of the open function), the page inside it most likely can't figure out where your stylesheet is (as it's address is "relative to nothing"). Try specifying an absolute URL to your stylesheet.
Also, there is media="screen" attribute that should be changed to media="print"
mywindow.document.write('<link rel="stylesheet" type="text/css" href="http://my.site/Site.css" media="print"')
The issue can be solved by introducing some delay time before executing mywindow.close(); method. Seems that some time is needed for CSS to be applied (loaded), like this:
$('#printMeButton').click(function () {
var content = document.getElementById(id).innerHTML;
var mywindow = window.open('', 'Print', 'height=600,width=800');
mywindow.document.write('<!DOCTYPE html><html dir="rtl"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Print</title>');
mywindow.document.write('<link rel="stylesheet" type="text/css" href="/static/css/styles.css" />');
mywindow.document.write('</head><body >');
mywindow.document.write(content);
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus()
mywindow.print();
// this is needed for CSS to load before printing..
setTimeout(function () {
mywindow.close();
}, 250);
return true;
});
We can use this inline style.
var divToPrint = document.getElementById('DivIdToPrint');
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write('<html>' +
'<style>' +
".btn-petty-cash-split{display: none}"+
".btn-petty-cash-split{display: none}"+
'</style>' +
'<body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
newWin.document.close();
setTimeout(function(){
newWin.close();
window.location.reload();
},10);
I'm creating extension using crossrider. In this extension I want to open a new tab with html from resources. Its opening page in new tab without issues. Now I want to add js & css to that, that to available in resources. Kindly help in adding css & js.
code in background.js
appAPI.openURL({
resourcePath: "troubleShooter.html",
where: "tab",
focus: true
});
in troubleShooter.html
<html>
<head>
<link media="all" rel="stylesheet" type="text/css" href="css/ie.css" />
<script type="text/javascript" src="js/ie.js"></script>
</head>
<body>
</body>
</html>
Crossrider recently introduced the ability to open a new tab with HTML from resources. However, such pages cannot directly access other resource file using link and script tags embedded in the HTML.
Though in it's early release, one of the features of the HTML page is the crossriderMain function that runs once the page is ready. In this early release, the function supports the following Crossrider APIs: appAPI.db.async, appAPI.message, and appAPI.request.
Hence, even though in this early release there isn't a direct method to add resource CSS & script files to the resource HTML page, you can workaround the issue by loading the resources into the asynchronous local database and applying it to the HTML page using standard jQuery. For example:
background.js:
appAPI.ready(function() {
// load resource file 'style.css' in to local database
appAPI.db.async.set('style-css', appAPI.resources.get('style.css'));
// load resource file 'script.js' in to local database
appAPI.db.async.set('script-js', appAPI.resources.get('script.js'));
// open resource html
appAPI.openURL({
resourcePath: "troubleShooter.html",
where: "tab",
focus: true
});
});
troubleShooter.html:
<!DOCTYPE html>
<html>
<head>
<!-- This meta tag is relevant only for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type="text/javascript">
function crossriderMain($) {
appAPI.db.async.get('style-css', function(rules) {
$('<style type="text/css">').text(rules).appendTo('head');
});
appAPI.db.async.get('script-js', function(code) {
// runs in the context of the extension
$.globalEval(code.replace('CONTEXT','EXTN'));
// Alternatively, run in context of page DOM
$('<script type="text/javascript">')
.html(code.replace('CONTEXT','PAGE DOM')).appendTo('head');
});
}
</script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
style.css:
h1 {color:red;}
script.js
console.log('CONTEXT:: script.js running');
Disclaimer: I am a Crossrider employee