Css stylesheet loaded as html in Firefox - html

I've got a css file injected into my asp.net web form application page through a base page. The method I use look like the following:
private void InjectLocalStyleSheet()
{
if (this.Page.Header == null)
return;
Literal cssFile = new Literal()
{
Text =
#"<link rel=""stylesheet"" type=""text/css"" href=""" + Page.ResolveUrl("~/Common/Theme.css") +
#""" />"
};
Page.Header.Controls.Add(cssFile);
}
When I run the page in firefox, that css file gives me a 302 warning. Apparently, firefox view this file as html type while I've specified the type to be "text/css".
snap of request and response headers
I also run the web page in Chrome and get "Failed to load resouce: net::ERR_TOO_MANY_REDIRECTS"
Anyone has an idea about what is going on? Please help. Thank you.

Related

Qt - Problem to Getting all source ( HTML code ) with qtNetworkAccesManager of a web page

I have some difficulties with the QtNetworkAccesManager.
I want to fetch the source code from an URL. The problem is that I'm getting only parts of the HTML source code, but not all of it. Can you tell me, what I am missing?
void MyClass::importFromWeb()
{
QUrl url = QUrl("https://doc.qt.io/qt-5/classes.html");
QNetworkAccessManager* manager = new QNetworkAccessManager(this);
QObject::connect(manager, &QNetworkAccessManager::finished, this, &MyClass::onNetworkReply);
response = manager->get(QNetworkRequest(url));
}
void MyClass::onNetworkReply()
{
QFile* data = new QFile("test.txt");
data->open(QIODevice::WriteOnly);
QTextStream write(dat koa);
write << response->readAll();
data->close();
}
For example if i want to fetch the source code of "https://doc.qt.io/qt-5/classes.html", the result size of test.txt is of 134 ko
However html code size when i'm doing a "ctrl+s" on the web site is of 192 ko.
So is missing some source code but what and why ?
Thanks for your help.

MVC 5 Content Disposition errors in Chrome and Firefox

I would like to display the user manual of the system as pdf in the browser.
The following code works fine in IE9 but not
Chrome - Error duplicate errors received from server
Firefox - Corrupted content error
The MVC 5 code ( I think is adding duplicate headers which IE can handle)
Just wondering is there any way this will work with all browsers?
public FileResult UserManual()
{
var FileName = "user-manual.pdf";
var cd = new ContentDisposition
{
Inline = true,
FileName = FileName
};
Response.AddHeader("Content-Disposition", cd.ToString());
string path = AppDomain.CurrentDomain.BaseDirectory + "App_Data/";
return File(path + FileName, MediaTypeNames.Application.Pdf, FileName);
}
I know this is old but I got into the same issue today.
If you add a "Content-Disposition" header then do not return File with the "FileName" argument added
Check this:
if (myFile.IsInlineContent()) // Evaluate the content type to check if the file can be shown in the browser
{
Response.AppendHeader("content-disposition", $"inline; myFile.Filename}");
return File(myFile.Path, myFile.Type); // return without filename argument
}
// if not, treat it as a regular download
return File(myFile.Path, myFile.Type, myFile.Filename); // return with filename argument
Hope this helps...
In order to show the file in the browser, do not provide the file name as the third parameter to the File method in your return statement. This forces a content-disposition of attachment behind the scenes. As such, your code should result in an invalid response with an ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION error.

The html page not showing correct link when using htmlunit driver

I have written a selenium script which runs in java :
String pageName = "my test url which invloves an link to html which has javscript excution";
logger.log(Level.INFO,"Page name : " + pageName);
WebDriver driver = new HtmlUnitDriver(true);
logger.log(Level.INFO,"driver instance created " );
String str ="";
logger.log(Level.INFO,"opening the url now.... " );
driver.get(pageName);
logger.log(Level.INFO,"url is now opened :: url = "+driver.getCurrentUrl());
logger.log(Level.INFO,"driver now going to sleep = "+driver.getCurrentUrl());
Thread.sleep(150000);
logger.log(Level.INFO,"Wake up from sleep now....");
logger.log(Level.INFO,"URL ::"+driver.getCurrentUrl());
logger.log(Level.INFO,"PageSource ::"+driver.getPageSource());
try {
logger.log(Level.INFO,"Driver going to wait now...");
driver.wait(100000);
logger.log(Level.INFO,"Driver came out of wait now normally...");
} catch (Exception e) {
logger.log(Level.INFO,"Driver came out of wait now exception::"+e);
}
logger.log(Level.INFO,"driver instance task completed " );
logger.log(Level.INFO,driver.getCurrentUrl());
logger.log(Level.INFO,driver.getCurrentUrl());
logger.log(Level.INFO,str);
driver.close();
Now when I debug this code I get my proper result but when I run this piece of code from servlet I get only the html content not the proper content which is excepted to come from the given link.
I also tried using the firefox driver and the same code works fine with it.
I also tried the same code with Web client but the same problem is coming.
Can anyone help me with this exception?
Thanks,
When you debug the code, you can halt at checkpoints. But you cannot stop browser from loading. It loads itself independently.
Htmlunitdriver pagesource returns all html contents as it cannot execute javascript completely.If the htmlpage contains Ajax, javascript calls then it shows the calls as it is .

The right way of setting <a href=""> when it's a local file

I'm trying to link to a local file. I've set href as follows:
Link Anchor
In Firefox, when I right click and "open link in new tab", nothing happens.
When I right click and "copy link location", then manually open a new tab and paste the copied link, it works fine. So it seems my file:// syntax is fine. I've also tried it with 3 slashes like file:/// but it's the same result.
What am I doing wrong?
By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)
So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).
If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,
Organize your files in hierarchical directories and then just use relative paths.
Demo:
HTML (index.html)
<a href='inner/file.html'>link</a>
Directory structure:
base/
base/index.html
base/inner/file.html
....
The href value inside the base tag will become your reference point for all your relative paths and thus override your current directory path value otherwise - the '~' is the root of your site
<head>
<base href="~/" />
</head>
This can happen when you are running IIS and you run the html page through it, then the Local file system will not be accessible.
To make your link work locally the run the calling html page directly from file browser not visual studio F5 or IIS simply click it to open from the file system, and make sure you are using the link like this:
Intro
../htmlfilename with .html
User can do this
This will solve your problem of redirection to anypage for local files.
Try swapping your colon : for a bar |. that should do it
Link Anchor
The right way of setting a href=“” when it's a local file.
It will not make any issue when code or file is online.
FAQ
Hope it will help you.
Here is the alternative way to download local file by client side and server side effort:
<a onclick='fileClick(this)' href="file://C:/path/to/file/file.html"/>
Js:
function fileClick(a) {
var linkTag = a.href;
var substring = "file:///";
if (linkTag.includes(substring)) {
var url = '/cnm/document/v/downloadLocalfile?path=' + encodeURIComponent(linkTag);
fileOpen(url);
}
else {
window.open(linkTag, '_blank');
}
}
function fileOpen(url) {
$.ajax({
url: url,
complete: function (jqxhr, txt_status) {
console.log("Complete: [ " + txt_status + " ] " + jqxhr);
if (txt_status == 'success') {
window.open(url, '_self');
}
else {
alert("File not found[404]!");
}
// }
}
});
}
Server side[java]:
#GetMapping("/v/downloadLocalfile")
public void downloadLocalfile(#RequestParam String path, HttpServletResponse
response) throws IOException, JRException {
try {
String nPath = path.replace("file:///", "").trim();
File file = new File(nPath);
String fileName = file.getName();
response.setHeader("Content-Disposition", "attachment;filename=" +
fileName);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
response.setStatus(200);
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, numBytesRead);
}
// out.flush();
in.close();
out.close();
}
else {
response.setStatus(404);
}
} catch (Exception ex) {
logger.error(ex.getLocalizedMessage());
}
return;
}

How do I display a PDF onto a JSF page

I want to display a PDF file onto my JSF page, I have check this how to display a pdf document in jsf page in iFrame, but I dont want to display it on an iframe(since it will generate scroll bar). I just want to display the pdf onto a page like an image and able to give a width and height for it.
EDIT Hi BalusC. I still cant be able to display the pdf inline. Here is my code.
#WebServlet(name = "pdfHandler", urlPatterns = {"/pdfHandler/*"})
public class pdfHandler extends HttpServlet {
private static final int DEFAULT_BUFFER_SIZE = 10240;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String requestedFile = request.getPathInfo();
File file = new File("/Users/KingdomHeart/Downloads/Test/pdf/" + requestedFile);
response.reset();
response.setContentType("application/pdf");
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try{
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while((length = input.read(buffer)) > 0){
output.write(buffer, 0, length);
}
}finally{
output.close();
input.close();
}
}
...
}
It still prompt me to download the pdf file. The pdf file that get downloaded to my computer is the correct pdf file btw. Can u spot anything wrong?
There's not really another way (expect from HTML <object> tag which would have the same "problems"), but you can just give the <iframe> a fixed size and disable the scrolling as follows:
<iframe src="foo.pdf" width="600" height="400" scrolling="no"></iframe>
If you also want to hide the (default) border, add frameBorder="0" as well.
You should take a look at ICEpdf, it creates an image on the server side, gives zooming, and other controls (demo).
Try going into Adobe Reader, and under the Options dialog there are web settings where you can indicate that you always want PDF type documents to open within the browser.
This is unfortunately a client side fix and doesn't take into account other PDF readers.
What you want is impossible. Browsers are not magic, they just display different kinds of documents, some of which (HTML) can embed objects provided by plugins (flash, java) and other documents inside iframes (pdf, flash, html). If you want to show pdf miniatures, you will have to generate images on the server.