I am rendering the following simple HTML in a Windows Forms WebBrowser control:
<HTML>
<HEAD></HEAD>
<BODY bottommargin='0' leftmargin='10' rightmargin='0' topmargin='10'>
<span>Programs</span><br /><br />
<a href='file:///C:\Temp\prog1.cnc'>Program 1</a><br />
<a href='file:///C:\Temp\prog2.cnc'>Program 2</a><br />
<a href='file:///C:\Temp\prog3.cnc'>Program 3</a><br />
</BODY>
</HTML>
The issue is that the links do not navigate to the file identified in the href attribute.
I can confirm that the AllowNavigation property on the control is set to True.
Also, the Navigating event does not fire when I click the links.
If I change the paths to reference a file on a remote share, everything works as expected, for example:
<a href='file://\\servername\Temp\prog1.cnc'>Program 1</a>
OR without the file prefix:
<a href='\\servername\Temp\prog1.cnc'>Program 1</a>
Both fire the Navigating event.
What am I missing when referencing a local file?
I have tried changing the file path to a public folder to rule out permission issues.
The same app is also writing the files so permission issues seem unlikely.
The files are simple text files which I'm trying to display in the browser control when the links are clicked.
Code setting the DocumentText Property of the browser control:
Private Shared Function LoadProgramHtml(ByVal programFiles() As String) As String
Dim programHtml As New StringBuilder
If ProgramFiles.Length > 0 Then
programHtml.AppendLine("<HTML>")
programHtml.AppendLine("<HEAD></HEAD>")
programHtml.AppendLine("<BODY bottommargin='0' leftmargin='10' rightmargin='0' topmargin='10'>")
programHtml.AppendLine("<span>Programs</span><br /><br />")
For Each program As String In ProgramFiles
Dim progInfo As New FileInfo(program)
programHtml.AppendLine(String.Format("<a href='file://{0}'>{1}</a><br />", progInfo.FullName, progInfo.Name.ToUpper))
Next
programHtml.AppendLine("</BODY>")
programHtml.AppendLine("</HTML>")
End If
WebViewer.DocumentText = programHtml.ToString()
End Function
Code to handle the navigating event:
Private Sub WebViewer_Navigating(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserNavigatingEventArgs) Handles WebViewer.Navigating
Dim filepath As String = e.Url.OriginalString
If File.Exists(filepath) Then
Dim progInfo As New FileInfo(filepath)
If progInfo.Extension.ToLower = ".cnc" Then
WebViewer.ScrollBarsEnabled = True
WebViewer.DocumentText = File.ReadAllText(e.Url.OriginalString).Replace(Chr(13), "<br />")
End If
e.Cancel = True
End If
End Sub
I have found a work around which will keep me going for the time being but I would still be interested if anyone has an explanation for the behaviour described.
By faking a remote file path, I can cause the Navigating event to fire as it did for actual remote files, then in the Navigating event, I re-write the path to re-reference the local file as follows:
Setting Document Text
Change:
programHtml.AppendLine(String.Format("<a href='file://{0}'>{1}</a><br />", progInfo.FullName, progInfo.Name.ToUpper))
To:
programHtml.AppendLine(String.Format("<a href='{0}' target='_top'>{1}</a><br />", progInfo.FullName.ToLower.Replace("c:", "\\faked"), progInfo.Name.ToUpper))
'note the `\\faked`
Handling the Navigating event
Add the following:
Dim filepath As String = e.Url.OriginalString.Replace("\\faked", "c:")
If File.Exists(filepath) Then
....
Related
I have the following asp.net C# code to upload an image, and when I try to run it and select the file to upload, it does not recognize that I have selected a file to upload, so I get the message "file not uploaded successfully. I get the following error when trying. Object reference not set to an instance of an object.
I believe I have to add code, to instantiate. I am new to this, and I believe I do not have the correct syntax. I have a data entry form where the File Upload. Can someone tell me what I need, I think I need to add a declaration, as in Line 3 (with ******), but what I have may not be correct if it is not setting the file I am trying to upload, the debugger shows no file, although I am selecting one. Thanks.
See code below
protected void ButImg_Click(object sender, EventArgs e)
{
******FileUpload fileImg = (FileUpload)this.FindControl("fileImg");*****
if (fileImg.HasFile)
{
string imgfile = Path.GetFileName(fileImg.PostedFile.FileName);
string savePath = Path.Combine(ConfigurationManager.AppSettings["ImagesFolder"], imgfile);
fileImg.SaveAs(Server.MapPath("UsrImage/"+ imgfile));
_connstr = System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
/* Save file to Ticket Attachments folder */
if (System.IO.File.Exists(savePath))
{
System.IO.File.Delete(savePath);
}
SqlConnection sqlconn = new SqlConnection(_connstr);
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(_procUpdateImage);
sqlcomm.CommandType = CommandType.StoredProcedure;
sqlcomm.Connection = sqlconn;
sqlcomm.Parameters.AddWithValue("#UsrID", this.txtUsrID.Text);
sqlcomm.Parameters.AddWithValue("#ImageName", imgfile);
sqlcomm.Parameters.AddWithValue("#ImagePath", "Images/" + imgfile);
sqlcomm.Parameters.AddWithValue("#UsrID", _UsrName);
sqlcomm.ExecuteNonQuery();
LitImg.Text = "Image saved successfully";
sqlconn.Close();
fileImg.SaveAs(savePath);
}
else
{
LitImg.Text = "Image not saved successfully";
}
}
.aspx web form for Upload control
<td class="tdSingle">Usr Image</td>
<td class="tdSingle">
<asp:FileUpload ID="fileImg" runat="server"></asp:FileUpload><br/>
<asp:Button ID="ButImg" runat="server" Text="Image Save" OnClick="ButImg_Click" ></asp:Button><br/>
<p>
<asp:Literal ID="LitImg" runat="server"></asp:Literal>
</p>
</td>
I would like to know if there is a way to create a link (Using HTML) to open an attachment embedded in the pdf document.
Something like this...
Open the attachment file or Open the attachment file
Any suggestion or recommendation?
Thanks
I have been able to implement this scenario after reading the next useful post
https://groups.google.com/forum/#!topic/flying-saucer-users/KuwPoTjaQYU
Steps:
Check out the next repository https://github.com/osnard/flyingsaucer
Analyse the file ITextOutputDevice.java, method processLink(RenderingContext c, Box box)
Make changes based on your needs
Build the project and use the jar file generated
Here the code to create an embedded file based on base64 content.
Java
...String doEmbedFile = handler.getAttributeValue( elem, "data-fs-embed-file" );
if ("true".equals(doEmbedFile.toLowerCase())) {
String fileName = new File(uri).getName();
String content = handler.getAttributeValue( elem, "content" );
com.lowagie.text.Rectangle targetArea = checkLinkArea(c, box);
if (targetArea == null) {
return;
}
try {
if (!_attachments.contains(fileName)) {
byte[] fileBytes = Base64.getDecoder().decode(content.getBytes("UTF-8"));
PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(_writer, null, fileName, fileBytes);
fs.addDescription(fileName, true);
_writer.addFileAttachment(fs);
_attachments.add(fileName);
}
targetArea.setBorder(0);
targetArea.setBorderWidth(0);
//This only works on Adobe Acrobat Reader
PdfAction action = PdfAction.javaScript(
"this.exportDataObject({cName:\"" + fileName + "\", nLaunch:2});",
_writer
);...
HTML
<body><div id='div1'><p><a href='test.png' data-fs-embed-file='true' content='iVBORw0KGgoAAAANSUhEU...'>open test.png file</a></p></div><div id='div2'><p><a href='test.pdf' data-fs-embed-file='true' content='JVBERi0xLjUNCiW1tbW1D...'>open test.pdf file</a></p></div><div id='div3'><p><a href='test.txt' data-fs-embed-file='true' content='VEVFRUVFRUVFRVNUIFRYVA=='>open test.txt file</a></p></div></body>
*base64 content truncated
Output
Greetings and I hope it can help others
just open it on new tab, add attribute target="_blank" in your anchor tag
Open attachment
I receive some html data from server, and I try to build a webview to show these data.
Then I need to set some labels to navigate to other page of UWP.
In Windows Phone 8 projects, I can add a label like this to navigate to another page and pass parameters.
But UWP doesn't support it anymore, so how to navigate to another page and pass parameters??
Here is a solution.
1.This is the string that webview will navigate to.
"<html>"+
"<body>"+
"<script type='text/javascript'>" +
"function Click()" +
"{window.external.notify('parameter1+" + "parameter2"+"...");}" +
"</script>" +
"<a href='#' onclick='Click();'>" + "NameOfLabel</a>" +
"</body>"+
"</html>";
2.Webview add a scriptnotify event in your xaml.
<WebView ScriptNotify="webView_ScriptNotify"></WebView>
3.Get parameter from javascript
private async void webView_ScriptNotify(object sender, NotifyEventArgs e)
{
//Get the paramter from javascript
string parameter=e.value;
}
4.One more, there is another wat to pass complicate parameters like a class.
But I can't find this artilce, I will add the url later if I find it.
I am struggling with this problem of accessing the sound file (mp3) download in isolated storage to be used in Alarm ,
The problem mentioned before
I am getting this error:
BNS Error: The action request's sound uri is invalid
Please help me but remember I am using the sound file for Alarm
Regarding the code it is the same as the link above.
This is download and save code of the sound file :
Public Async Function DownloadFile(url As Uri) As Task(Of Stream)
wc = New WebClient()
AddHandler wc.OpenReadCompleted, AddressOf OpenReadCompleted
AddHandler wc.DownloadProgressChanged, AddressOf DownloadProgress
wc.OpenReadAsync(url)
Dim r As IO.Stream = Await tcs.Task
Return r
End Function
Private Sub OpenReadCompleted(sender As Object, e As OpenReadCompletedEventArgs)
If e.[Error] IsNot Nothing Then
tcs.TrySetException(e.[Error])
ElseIf e.Cancelled Then
tcs.TrySetCanceled()
Else
tcs.TrySetResult(e.Result)
Dim file As IsolatedStorageFile
file = IsolatedStorageFile.GetUserStoreForApplication()
Using Stream As IsolatedStorageFileStream = New IsolatedStorageFileStream("Sound.mp3", System.IO.FileMode.Create, file)
Dim buffer As Byte() = New Byte(1023) {}
While (e.Result.Read(buffer, 0, buffer.Length) > 0)
Stream.Write(buffer, 0, buffer.Length)
End While
End Using
End If
End Sub
Private Sub DownloadProgress(sender As Object, e As DownloadProgressChangedEventArgs)
Proind.Value = e.ProgressPercentage / 100
Proind.Text = e.ProgressPercentage.ToString & " %" & " ( " & (e.BytesReceived \ 1000).ToString & "/" & (e.TotalBytesToReceive \ 1000).ToString & " ) KB"
End Sub
The problem is that you are trying to set a file in the isolated storage as the sound of the alarm, and that's not allowed. Only files packaged in .xap can be set as sound source of the alarm:
Remarks
The Sound URI must point to a file packaged in the application’s .xap
file. Isolated storage is not supported. When the alarm is launched,
the sound is played quietly and then gradually increases in volume.
There is no way to modify this behavior.
From:
Alarm.Sound Property
However, there is a way you could use a downloaded song as alam's sound. In OpenReadCompleted method, instead of saving the downloaded file in the isolated storage, create a file using File.Create method, and store the data there. Then it will be possible to use this file as the alarm sound:
Here is the C# code, I think you will easily translate to VB:
byte[] buffer = new byte[e.Result.Length];
e.Result.Read(buffer, 0, buffer.Length);
using (var fs = File.Create("file.mp3"))
{
fs.Write(buffer, 0, buffer.Length);
}
Then, you can set the Sound property of the alarm as:
alarm.Sound = new Uri("/file.mp3", UriKind.Relative);
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;
}