Why doesn't the hyperlink open the file? - asp.net

Earlier developer had put this code using a label and it was turned into a hyperlink during the run time.
<asp:Label ID="lbl_Attachment" runat="server">
</asp:Label>
lbl_Attachment.Text = "<a href='../Uploads/" +
ds_row["Attachment"].ToString() + "'>" +
ds_row["Attachment"].ToString() + "</a>";
But this is not working. So I changed the code to the following to open the any file (image/pdf/word) in a new browser tab and the error persists:
hyperlinkAppDoc.NavigateUrl =
ResolveUrl("../Uploads/" +
ds_row["Attachment"].ToString());
hyperlinkAppDoc.Target = "_blank";
What can I do to fix this issue? MIME types are available in the IIS.
UPDATE:
I am trying out a different approach. However the Server.MapPath is poiting at local drive instead of wwwroot. How can I point the path to wwwroot folder?
string pdfPath = Server.MapPath("~/SomeFile.pdf");
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(pdfPath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);

You could have used asp.hyperlink. Like following
<asp:HyperLink id="hyperlink1" NavigateUrl="<set_from_code_behind>" Text="Text to redirect" runat="server"/>
And set NavigateUrl from code behind as following.
hyperlink1.NavigateUrl= "Uploads/" + ds_row["Attachment"].ToString();

In your situation, I suggest you to add one key in <appSettings> tag in your web config file.
<appSettings>
<add key="WebsiteURL" value="http://localhost:1234/WebsiteName/"/>
</appSettings>
Next step is to take one hyperlink in your .Aspx file.
<asp:HyperLink ID="HyperLink1" runat="server" Target="_blank"></asp:HyperLink>
In code behind concatenate AppSettings Key + Download file path from root.
string base_path = ConfigurationSettings.AppSettings["WebsiteURL"];
HyperLink1.NavigateUrl = base_path + "Uploads/" + ds_row["Attachment"].ToString();
Please let me know if you have any questions.

All the sweat was due to path issue. Old code and new code works. There's no need for a web client code.
The upload path was set here:
public static string UploadDirectory = ConfigurationManager.AppSettings["UploadDirectory"];
It was pointing to a different directory in the root other than where the application was. Therefore the files were only uploaded but never picked up.
I changed it to AppDomain.CurrentDomain.BaseDirectory for now. After we talk with the users, we will set it accordingly.

Related

VB.NET 2.0: Where does a URL in code come from?

I have to debug an old VB.NET 2.0 code of someone who has left the company. We have a production system (let us call it http://prod) and a test system (http://test). Both are nearly similiar including a documents repository. When looking at docs in production, all the hyperlinks showing up at the bottom are okay (meaning they say something like http://prod/download.ashx?id={GUID}).
However in test it is the same (http://prod/download.ashx?id={GUID}), even it should be http://test/download.ashx?id={GUID} instead.
After hours of debugging I have found the relevant line of code:
html += "<td><a href='" + HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.PathAndQuery, "/") + "int/download.ashx?id=" + row.Item(0).ToString() + "' target='_blank' class='" + row.Item(3).ToString() + "'>" + row.Item(1).ToString() + "</a>" + privat + "</td><td>" + row.Item(2).ToString() + "</td>"
Looking at html this shows i.e.
"<table class='table_dataTable'><thead><tr><td>Name</td><td>Jahr</td></tr></thead><tbody><tr><td><a href='http://prod/int/download.ashx?id=4d280886-db88-4b25-98d8-cf95a685d4a4' target='_blank' class='doc'>Document for managers</a></td><td>2014</td>"
So I wonder, where does this come from incorrectly? I may have found the relevant part of coding, but I am not sure, what to do now, respectively if I am right on this?:
Public Class download : Implements IHttpHandler, IReadOnlySessionState
Dim debug As String = ""
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim fehler As String = ""
Try
' Get the file name from the query string
Dim queryFile As String = context.Request.QueryString("id")
debug += "id=" + queryFile + "<br>"
Any help is appreciated as VB.NET is not my main focus.
You have probably checked this but sometimes the obvious gets overlooked.
Verify the URL in your browser window. Make sure it has not changed to http://prod... while you were navegating.
Verify that your web application is not using frames. The page in question could be loaded in a frame using the prod URL. If this is the case your web.config might have a setting to say where this frame is loaded from or it might simply be hardcoded.
Check for URL Rewrite rules in IIS or your web.config

Linking to PDF stored on network via Webforms ASP.NET?

I'm trying to create a hyperlink to a pdf stored on our network drive. The problem is that I create the hyperlink through ASP.NET but clicking the link does absolutely nothing. If you inspect the element and click the link it works just fine.
It seems to be related to this issue on HTML links to local network shares.
By downloading the extension for Chrome referenced in that thread I am able to open local links. In Internet Explorer I am able to click the links without any issue or extensions.
I populate the NavigateNurl through a configuration value:
System.Net.WebUtility.HtmlEncode(configValue)
Here is the path I am using (with slight alterations in name):
file://unk-file01/forms%20engine/Templates/Fake/ES_User_Manual_GBA_FINAL_081514.pdf
<div id="manualMenu" runat="server">
<div id="manual">
<asp:HyperLink ID="ESUserManualLink" Target="_blank" runat="server" Text="GBA User Manual" >
GBA User Manual
</asp:HyperLink>
<asp:HyperLink ID="UnderwritingManualLink" Target="_blank" runat="server"
Text="GBA Underwriting Guide">
GBA Underwriting Guide
</asp:HyperLink>
</div>
</div>
Is there anything else I can do to make this work across all platforms besides hosting the files elsewhere?
If you can make your URLs look like http://example.com/DownloadPdf.ashx?file=ES_User_Manual_GBA_FINAL_081514 then suitable code-behind for DownloadPdf.ashx could look like
Imports System.IO
Imports System.Web
Imports System.Web.Services
Public Class DownloadPdf
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim fname = context.Request.QueryString("file")
Dim actualFile = Path.Combine("//unk-file01/forms engine/Templates/Fake", fname) & ".pdf"
If File.Exists(actualFile) Then
context.Response.ContentType = "application/pdf"
context.Response.AddHeader("Content-Disposition", "attachment; filename=""" & Path.GetFileName(actualFile) & """")
context.Response.TransmitFile(actualFile)
Else
context.Response.Clear()
context.Response.TrySkipIisCustomErrors = True
context.Response.StatusCode = 404
context.Response.Write("<html><head><title>404 - File not found</title><style>body {font-family: sans-serif;}</style></head><body><h1>404 - File not found</h1><p>Sorry, that file is not available .</p></body></html>")
context.Response.End()
End If
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Note that it forces the file to have an extension of .pdf - you could add additional security such as preventing directory traversal and checking the user is allowed to access the file.
Code not tested as-is, but the code it is derived from works in a production environment (where it does have more security).

Images not displaying in adrotator where its picture path like "C:\Uploader\Image.jpg"

Images not displaying in adrotator where its picture path like "C:\Uploader\Image.jpg" or some shared folder in server.If i give the path inside my project,its working but outside the project ( like "C:\Uploader\Image.jpg") it not showing anything.
<telerik:RadRotator ID="radSlider" runat="server" FrameDuration="400" ScrollDuration="500"
ScrollDirection="Left" Height="250px" Width="550px">
<ItemTemplate>
<img src='<%# Eval("FullName") %>' alt="Friday" width="550px" />
</ItemTemplate>
</telerik:RadRotator>
Here i am attaching the path dynamically using databind.What is the problem.Plz help me?Telerik or asp control
The client browser will never know where those images are unless you map a virtual directory to the images. Even you can not use Server.MapPath() etc to map the drive.
You should use an HttpHandler to access the file outside of your
application virtual directory.
Check following SO thread that much relevant to your problem:
Show Images from outside of ASP.NET Application
Another approach that i have gotten after goggle about this as follow:
You can try to access the file outside application's virtual directory. you need to pay attention to the folder/file enough permission.
you can to access the images in your website, you can check the following link:
Displaying images that are stored outside the Website Root Folder
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["FileName"] != null)
{
try
{
// Read the file and convert it to Byte Array
string filePath = "C:\\images\\";
string filename = Request.QueryString["FileName"];
string contenttype = "image/" +
Path.GetExtension(Request.QueryString["FileName"].Replace(".","");
FileStream fs = new FileStream(filePath + filename,
FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
//Write the file to response Stream
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contenttype;
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
catch
{
}
}
}
Hope this help.
You should use IHttpHandler to serve your files in a different location (e.g. outside of application root or in privileged folders). AFAIK, Telerik Rad Controls has a RadBinaryImage or something for such usages.

viewing the images problem

Using ASP.Net and VB.Net
Code
Image1.ImageUrl = "c:\Blue hills.jpg"
The above code is not viewing the image when i clicked the button.
How to solve this problem.
Need Code Help
You shouldn't be referencing the local file path - you should set the ImageUrl to be the URL on the webserver - for example, if you had the file in the root of your website, you'd reference it as:
Image1.ImageUrl = "/Blue%20hills.jpg"
The value you are supplying to the ImageUrl property is a file path and not a Url.
Ideally you should have a folder in your ASP.NET application that holds your image files which you can then reference with either a relative or absolute Url path i.e:
Image1.ImageUrl = "/Content/Images/Blue hills.jpg"
If you want to show pictures from the server disk that are outside of the website root, you have to build "proxy" page. For example call it ShowImage.aspx and it will get the picture name on the URL.
Then you'll have such code
Image1.ImageUrl = "ShowImage.aspx?image=Blue hills.jpg"
And the code for ShowImage.aspx code behind:
string imageName = Request.QueryString["image"] + "";
if (imageName.Length == 0 || imageName.Contains("/") || imageName.Contains("\\") || !imageName.ToLower().EndsWith(".jpg"))
{
throw new Exception("Invalid image requested");
}
else
{
string strFullPath = "C:\\" + imageName;
Response.ContentType = "image/jpeg";
Response.Clear();
Response.WriteFile(strFullPath);
}
Response.End();
This is C# but should be simple enough to translate into VB.NET as well.
Edit: added basic validation that verify that user does not try to fetch files from different directory and allows only .jpg files.
Image1.ImageUrl = System.Web.HttpContext.Current.Server.MapPath("~") + "/"+ "Images" + "/" + "Blue hills.jpg";
but as said before you can't reference a local file like this , except u use HttpHandler.
http://www.15seconds.com/issue/020417.htm

How to list some specific images in some folder on web server?

Let me explain:
this is path to this folder: > www.my_site.com/images
And images are created by user_id, and for example, images of user_id = 27 are,
27_1.jpg, 27_2.jpg, 27_3.jpg!
How to list and print images which start with 27_%.jpg?
I hope You have understood me!
PS. I am totally beginmer in ASP.NET (VB) and please give me detailed information
Here starts my loop
while dbread.Read()
'and then id user_id
dbread('user_id')
NEXT???
I nedd to create XML, till now I created like this:
act.WriteLine("")
act.WriteLine("http://www.my_site.com/images/"&dbread("user_id")&"_1.jpg")
act.WriteLine("")
But this is not answer because I need to create this nodes how many images of this user exist?
In database doesn't exist list of this images so that is reason why I must count them in folder. (this is not my site exacly, but I need to create XMl on this site)
Do you understand me?
The best way is to just loop through all the files in the directory.
While dbRead.Read
dim sUserId as String= dbread('user_id')
For Each sFile As String In IO.Directory.GetFiles("C:\")
if sFile.StartsWith (sUserId) Then
'Do something.
End If
Next
Loop
However, to actually show the images, you're best bet could be to create a datatable of these images, and then use a datalist or repeater control to display them.
Dim dtImages as new DataTable
dtImages.Columns.Add("Filename")
If dbRead.Read
dim sUserId as String= dbread('user_id')
For Each sFile As String In IO.Directory.GetFiles("C:\")
if sFile.StartsWith (sUserId) Then
Dim drImage as DataRow = dtImages.NewRow
drImage("Filename") = sFile
dtImages.Rows.add(drImage)
End If
Next
End If
dlImages.DataSource = dtImages
dlImages.DataBind
Then, on your ASPX page, you would have a datalist control called dlImages defined like:
<asp:datalist id="dlImages" RepeatDirection="Horizontal" runat="server" RepeatLayout="Flow" Height="100%">
<ItemTemplate>
<asp:Image ID="Image1" Runat=server ImageUrl='<%# Server.MapPath("photos") & Container.DataItem("FileName") %>'>
</asp:Image>
</ItemTemplate>
</asp:datalist>
The appropriate method would be to do the following
Get the listing of files using System.IO.Directory.GetFiles("YourPath", UserId + "_*.jpg")
Loop through this listing and build your XML or then render it out to the user.
Basically the GetFiles method accepts a path, and a "filter" parameter which allows you to do a wildcard search!
EDIT:
The GetFiles operation returns a listing of strings that represent the full file name, you can then manipulate those values using the System.IO.Path.GetFileName() method to get the actual file name.
You can use the XmlDocument class if you want to actually build the document, or you could do it with a simple loop and a string builder. Something like the following.
StringBuilder oBuilder = new StringBuilder();
oBuilder.Append("<root>");
string[] ofiles = Directory.GetFiles("YourPath", "yourMask");
foreach(string currentString in oFiles)
{
oBuilder.AppendLine("<file>http://yourpath/" + Path.GetFileName(currentString) + "</file>");
}
oBuilder.Append("</root");

Resources