asp.net - Hyperlink not working - asp.net

protected void Button1_Click(object sender, EventArgs e)
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(#"C:\Documents and Settings\Admin\Desktop\New Folder\"+TextBox1.Text);
foreach (System.IO.FileInfo file in dir.GetFiles())
{
HyperLink h = new HyperLink();
h.NavigateUrl = "file:///c:/Documents and Settings/Admin/Desktop/New Folder/" + TextBox1.Text + "/" + file.Name;
h.Text = file.Name;
PlaceHolder1.Controls.Add(h);
}
}
On execution of this code hyperlinks get generated but they are not working.
nothing happens when i click on them.
Please help.

In ASP.NET hyperlinks must be URLs not a folder on the computer.
If your file is in your site try Sever.MapPath

This is due to security restrictions in the browser. If you generate a "file://" link, it is relative to the user's file system.
Theoretically, if browsers allowed these types of links, attackers could discover information about a user's file system remotely. Thus, modern browsers do not allow this type of link.
Unfortunately this is not very well documented, and most browsers allow the links and just drop the behaviour - so nothing happens when you click them. There aren't any good workarounds either.
See my question here for further discussion.

Check out this question. The solution may work for you too.

I have found that (in the context of redirecting to another one of your own web pages) using this:
compontent.NavigateUrl = "~/page.aspx";
instead of this:
compontent.NavigateUrl = server.MapPath("path");
worked for me. The server.MapPath created a File:// link so that it was not allowed by the browser.
Hope this helps someone, it won't work in some cases but it worked for my individual requirements.

Related

Fixing accessibility error for lang tag in Kentico

I am facing Site-improve accessibility error that my page doesn't have a "lang tag" defined. How can I accomplish this in Kentico?
There are possibly two ways to achieve this. One is through C# .NET code in Kentico and the other is through Javascript code. I'm providing you both solutions
In order to fix this problem you have fix two tags for your tool to stop pointing accessibility error. You have to set both "lang" as well as "xml:lang" tag. One way to achieve this through pure Javascript is below. I am proposing this solution as it is independent of any platform.
(function() {
document.getElementsByTagName('html')[0].setAttribute('lang', 'en-US');
document.getElementsByTagName('html')[0].setAttribute('xml:lang','en-US');
})();
You may replace 'en' with language of your choice to correctly point the correct language in place
In Kentico you may achieve this by placing this code in your master template so that these tags can be added on all pages.
In your Kentico master template just add a Head HTML web part and put this code inside it.
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (CurrentDocument != null)
{
CMS.UIControls.ContentPage page= this.Page as CMS.UIControls.ContentPage;
if (page != null)
{
string lang= CMS.Localization.LocalizationContext.CurrentCulture.CultureCode;
page.XmlNamespace += " lang=\"" + lang + "\"";
page.XmlNamespace += " xml:lang=\"" + lang + "\"";
}
}
}
</script>
This should fix everything for you.
The recommended way is to open ~/CMSPages/PortalTemplate.aspx web form and edit the lang attribute manually just as you see fit.
Please note that generally speaking the modification of Kentico system files is not recommended, but in this case it is the best way to go. Just keep in mind to document all changes you make.
Edit:
Other solution which does not involve any customization is to use CMSPortalTemplatePage web.config key to set up path to a custom PortalTemplate file. This way you can clone Kentico's PortalTemplate.aspx, make modification in this cloned file and keep the original.
Possible usage:
<add key="CMSPortalTemplatePage" value="~/CMSPages/CustomPortalTemplate.aspx" />

Web form non-responsive after download

I'm working in ASP.NET (2.0) and we have a page where a user is able to select and download a series of files as a zip. I got this to work without undo difficulty by using the DotNetZip library (which is probably not relevant to the problem, but included for completeness.)
After the user checks which files they want to download, the page does a postback, and in the button click event handler, I use the following code:
Response.Clear();
Response.BufferOutput = false; // false = stream immediately
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=FileRequest.zip");
using (ZipFile zip = new ZipFile())
{
zip.AddFile(MapPath("/datafiles/fileToZip.pdf"), "");
zip.Save(Response.OutputStream);
}
Response.Close();
And this all seems to work great. The user clicks the button, a download window pops up, the user downloads the zip. All is good...
...until they decide they want to do something else on the page. The buttons in the form are no longer responsive. For instance, if I click the download button again, it does nothing. If I reload the page, I can repeat this behavior...it works once, then does nothing.
I'm not understanding why the browser doesn't send the new request. It's not "spinning" or otherwise acting busy. I thought that this might be a browser issue, but I've repeated it in both IE and Firefox, so it seems likely that it's something I'm not understanding. Strangely, it's only form submission elements that seem to be non-responsive. Javascript still works, and so do regular links.
So why is this happening, and how do I get around it?
The problem is likely down to you returning;
Response.ContentType = "application/zip";
Once this has been sent (along with the actual content), the browser would assume it has nothing left to do (I believe).
You probably should create a new window specifically for downloading the files by saving the file selection in a session parameter (or equivalent) and opening a popup window that has your download code in.
This will leave the parent page in a suitable state.
Content-disposition header seems to be a discouraged solution. But the same effect of ASP.NET forms not being responsive occurs if you use standard Redirect to a zip file.
I solved very similar problem (returning *.csv files by the server for download) using Tančev Saša's code in "Response.Redirect to new window" Q&A and it works great. Perhaps it might produce some popup warnings in some browsers, but I think this is how it's often done in download sites.

Access to the path is denied C# error

I want my user to be able to hit the submit button and have a string write into a css file. When I hit the submit button, I am getting the error message:
Access to the path 'C:/.....' is denied
This happens when running the site from localhost and on my hosting (123reg)
protected void btnSubmit(object sender, EventArgs e)
{
using (StreamWriter writer = new StreamWriter("B00101168.css"))
{
writer.Write("Word ");
writer.WriteLine("word 2");
}
}
The first problem is, you can't write to a file without setting permissions on the folder. See this link for details. Essentially, you must give the Internet Guest Account permission to write to the folder.
But, the bigger problem is, you probably shouldn't be trying to dynamically write a CSS file anyway. At least, not the way you are trying to do it. Can you explain why you are trying to dynamically change a CSS file on your server? If you can explain what you are trying to accomplish, I might have some suggestions on how to do it that work better than what you are trying to do.
UPDATE: You're using WebForms, and you're trying to dynamically generate CSS. So here's one way to do that.
Use a generic page handler -- a file that ends in .ashx. You dynamically create the CSS however you're doing it now, but instead of writing it to a file, you output it directly to the browser. Here is some (untested!) code:
In the DynamicStyles.ashx file, there is basically nothing to add from what it automatically generates.
In the DynamicStyles.ashx.cs file:
public void ProcessRequest( HttpContext context )
{
StringBuilder css = new StringBuilder();
// Use the StringBuilder to generate the CSS
// however you are currently doing it.
context.Response.ContentType = "text/css";
context.Response.Write( css.ToString() );
}
Then, in your code that needs the CSS file, include it just like you would any other CSS:
<link rel="stylesheet" type="text/css" href="/path/to/DynamicStyles.ashx">

Display image from database in ASP.net with C#

I know this kind of question has been asked many times.
Yet I don't succeed in displaying an image from my db on a page.
I tried the following method.
protected void Page_Load(object sender, EventArgs e)
{
//Get the picture id by url
//Query here
byte[] picture = queryoutput;
Response.ContentType = "image/jpeg";
Response.BinaryWrite(picture);
}
Link to get the image.
<asp:Image runat="server" ImageUrl="~/givememypicture.aspx?pic=3" ID="testimage" />
The <asp:Image /> tag is located in between <asp:Content > tags.
When I run this code and check in firebug, it simply states 'Failed to load fiven URL'.
I also tried putting the Respone.Con...(picture); part into a public method and call that method with the byte var given.
I'm quite new to asp.net, but I have somewhat more experience in c#.
I start to really dislike asp.net... I have been struggling with this for about 20 hours already and tried a lot of options, yet none worked.
The best would be if I could just fill in the picture via the codefile from that same page. It seems quite illogical to me to call another page to load the image from.
Can somebody please tell me what I'm doing wrong here?
Solution: Master page reference removed from the page directive on the page that handles the image response. Also removed everything else except for the #page directive itself within the aspx file.
try using a handler file (.ashx) put the code form your page_load in that lie so
public void ProcessRequest (HttpContext context) {
//Get the picture id by url
//Query here
byte[] picture = queryoutput;
Response.ContentType = "images/jpeg";
Response.BinaryWrite(picture);
}
public bool IsReusable {
get {
return false;
}
}
then call the handler file and pass the correct querystring items from the
this should then work
There's an error in your path reference...
ImageUrl="/~givememypicture.aspx?pic=3"
should be:
ImageUrl="~/givememypicture.aspx?pic=3"
~ is shorthand for "the application root" and needs to be followed by a slash to indicate that it's a directory. Think of it as similar to other path shorthand notations such as . and ...
Make sure you call Response.Flush(); and also Response.End(); and see if that does the trick
Also, your content type has a misspelling. Is not "images/jpgeg" I think it's "image/jpeg"
EDIT: Yes, I just confirmed in Wikipedia that the correct content-type is image/jpeg.
I do this all the time. Here's some sample code:
Response.ContentType = "image/jpeg";
Response.BinaryWrite(bytes);
That's all there is too it. If it's not working, then something is probably wrong with your data.
A flush is not required. I have working code for this open on my screen right now.
I would suggest that you try writing that buffer of data to a file and see if it opens up as a valid picture. I bet something's wrong with that data.
Also, it's a good idea to enable browser side caching for your dynamic content. Here's a GREAT link that shows exactly how to do that, which will boost your performance / scalability a lot.
http://edn.embarcadero.com/article/38123

Is there a way to get images to display with ASP.NET and app_offline.htm?

When using the app_offline.htm feature of ASP.NET, it only allows html, but no images. Is there a way to get images to display without having to point them to a different url on another site?
Yes, it just can't come from the site that has the app_offline.htm file. The image would have to be hosted elsewhere.
Another solution is to embed the image inside the app_offline.htm page using a data URI. There is wide support for this these days - see the following for full details -
http://en.wikipedia.org/wiki/Data_URI_scheme
If you don't support browsers prior to IE 8, you can always embed the images using a data URI.
http://css-tricks.com/data-uris/
If you're willing to do a little more work you can easily create a custom page to take the application offline.
One possible solution:
Create DisplayOfflineMessage.aspx: Contains label to display your offline message from Application["OfflineMessage"].
ManageOfflineStatus.aspx: Contains an offline/online checkbox, textarea for offline message and an update button. The update button sets two application level variables, one for the message and a flag that states if the application is online. (This page should only be accessible to admins)
Then in Global.asax
public void Application_Start(object sender, EventArgs e)
{
Application["OfflineMessage"] = "This website is offline.";
Application["IsOffline"] = false;
}
public void Application_OnBeginRequest(object sender, EventArgs e)
{
bool offline = Convert.ToBoolean(Application["IsOffline"]);
if (offline)
{
// TODO: allow access to DisplayOfflineMessage.aspx and ManageOfflineStatus.aspx
// redirct requests to all other pages
Response.Redirect("~/DisplayOfflineMessage.aspx");
}
}
I have an idea.
You can create separate application, pointed to the same folder, without ASP.NET enabled. Then accessing to images by this application will not be affected by app_offline.htm file.
Or, point that application direсtly to folder with static content, there will not be any app_offline files.
But, of course, you need to assign separate dns name for this application, kind of static.somedomain.com.
You could just convert your images to base64 and then display them:
<html>
<body>
<h1>
Web under maintenance with image in base64
</h1>
<img src="data:image/png;base64,iVBORw0K...=">
</body>
</html>
I've created a Fiddle where you can see it in action

Resources