Access to the path is denied C# error - asp.net

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">

Related

Set background-url css property to a memory image in .net

Please read about my following situation. So we have a web application in .net. Because some customers wanted to pay for some custom layout, we first started to use themes. It was ok until there were more than 10. Because after that it was difficult to maintain and more of them wanted custom design, I had to design a solution so that the user could change only a few css attributes through a front-end page.
So when a user clicked a button a folder with its name and another css file was generated and he could change the attributes and save the new file. This file was dynamically loaded on the Page_Load on some basebage. This was ok, until more and more users payed for this and now we have tens of folders and expect hundreds. There is also the problem of rights, by default IIS doesn't have writing right to the application folder. Also the deployment process builds a new version by deleting the whole app folder and recreating one so we had to do a workaround and make a copy of this mega folder that holds the users css. And anyway, I don't like the idea of having hundreds of files not under source control.
And now, I have a new requierement. The users to be allowed to upload a custom image to replace one of our own. So i said it is time to move evrything to the database. For basic attributes I solved it.
I have a "mutant" aspx page:
<%# Page Language="C#" ContentType="text/css" %>
.labelText
{
color:<%= WebApplication1.UserProfile.LabelColor%>
}
So the UserProfile class gets it's data from a table.
And then in the page_load of the basepage
HtmlLink link = new HtmlLink();
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("href", "~/Styles/Override.aspx");
this.Header.Controls.Add(link);
It works ok, the problem the images are used like this:
.divHeader
{
background: 15px 0 url("logo.gif")
}
That logo.gig will be uploaded by the user,but I would like to be saved in the database. However when reading it as a stream I can't do something like:
background: 15px 0 url(WebApplication1.UserProfile.Logo)
Is there any otehr way I can specify an object in a css class?If it isn't what is the best approach? I was thinking about keeping the image in the db and also as a file, something similar to what we have now.
I realize that if it were for an image control it would have been a lot easier, but this is the design now, and remaking it is a little bit troublesome
Thanks for reading this novel and for any oppinions on this.
I hope you're saving the mime-type value of every image that you save to database (mime type is reported by the request during upload). If you don't, you'll have to look up what a mime type would be based on image-file extension or its content format. You'll need this value when images are requested (from within CSS files).
Implement an HTTP handler (.ashx) specifically for these images (new file > generic handler > fill up ProcessRequest).
Then, replace url(logo.gif) in your css files with something like this:
url(/GetImage.ashx?user=1234&image=logo);
Obviously, you can have the filename and query to be whatever you like/need. Maybe you have user info in session, so you don't have to include user id there. Maybe you'll want to implement this handler only for logo images, and if you have user info in session, you can simply say (css):
url(GetLogo.ashx);
Then, within that ashx handler, write code to get the image from the database (or where ever it is), and stream it to the browser. Something like this:
byte[] imageData = ... // get this from db
MemoryStream ms = new MemoryStream(imageData); // System.IO namespace
Response.ContentType = "image/png"; // remember the mime-type?
ms.WriteTo(context.Response.OutputStream); // context is current HttpContext
Alternatively, you can inject the whole image into the CSS, by encoding it to base-64 format. Note that the size of css file will grow for the size of the image, and you're practically combining multiple downloads into 1, which may be a good or a bad thing.
Example below (google's logo); paste this in CSS (notice the size of that thing).
Besides CSS, the data in this example (data:image/png;base64,iVBORw0KGg ...) can be used as URL with IMG tags, or manipulated by JS.
.somediv
{
width:275px;
height:95px;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARMAAABfCAMAAAD8mtMpAAAC/VBMVEUBIrIZH6qfBSGwAyWSDiTEAym9DifSCyysGCiQISvJES3eDDLMFinYGDDdFyzkGjbmGzGhMTePNjwsSa3JKDQYTukOZh3iKDKKQUPvKzHwKjnoLUDFODyxQUTAQEPuNT3kOEDeO0anS0xJYKH2OTf0Oz6fVVY5aN3zRErSXAD3SkflUE2cZmTgU1tGg1DAYV32U1HXXVyVcG60aGO1cSLOcAKfeEncbgD4YVaugED5Z1+1enfNfxGqf3x5ibPjfACgh168hTKXi3nJfHuih4WdjXP5dGnJih7mhQDvenOKla2ck5Bcqm7wjwDnkQhxne++llbfiYa6m1/JmkHyioDwmQDZnSe+nZnnoA7Wmpb6nwDyoQy+p3jTqUa5qpD5pgDoqB+5q6v4npH/rgCps834rxD/tADiuDvWs7D+uQ3/wCLiwXTPwqSZ1az+xjWw0rvjyYrg0K722YvH6tL35bX98tT99uEAQOKlpqNIh/03dPsAVP1UivYqSvC7vLnn6ebr7ert8Pjw8+8iYvojXvr19/P5+/j3+/4aReoAR/Gwsq50f5sMrBcAsBgvbvwGtCGkvvYSTfgANtvGx8QCLMLP0M0AS+3W2NV9qPnQ3Pnd39zY4PY0Wcf529fj5OErZu4yZPIjaPwbPOI8ff0AS/VGascSV/mNsvgAL8yYm5f///9ZcrKUlZstV9NueZ778vFfcacaMdHwrqcYPdABN9THyM8IdwW/y+domfj608cpUdQiUt8jSOZjdKBaie3x5cQHjhg1a+336OVvh8UAgQzxo56xtcUQML9Marmcu/mAoeUAkw4jljYJQe2kvOv+zETk6fm5z/ogUfUZVuyFiZc2VrJNyWJKf/g1c/MAmwgjRrXsysYEpSUpQOcRdyP546X41HgdQsP7zlc/rlHyzGf1uLCssLWPn8rc7+NkiNnKzt6JvJUApRP2xr/g4el/hpoJbB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kps7Ey3H0AfmT12gJOiIpzyoJ/+VTEaWFUZ31PvKiWnFDImOVNdErwZKZefQn3q+Z5gkR3eYJQpDezFjBUTqD9JMKiqPiB4UJhkdHXk5+YbKLwXMRSEp7EHngdRpmf5BYZKWl1efICfaWZ+TJ3U1qJOiosW6B4RJS4zZnKMhlPtZ91FLyEsUk9RdQ3685B5hklxfnwTRpKLbyb5MS60BW3/bHhQm1Tk5OSaFoWqZkxsmsykm13QPCJNeiUQCuYnS6TNGvdjoun7jQYmxZpPJpAEm+7XOmRSl3rzjV9TdszrRtLUBE0O7k3giy0Emw/Dg+D3CpIdqBRAGZ6fL0uWGCpsjbfc5kxPUERmAwn5oqGQlyKRx2zA8JH2PMIk3GaDsBWtmbQaka4iK1FvDIJN7hQl5jMCyt5lobmZ5x2RLPcikvXg4XkNxr+T2olIltgMMzfLmOqYtyhYzILm9F6ndN0zIy+ew/UngzpPpmD0VWTLuJYzdKdAPR4PnnukVSC/voxrDEFfkGlNdckbf659lLelp2XKDsvJW8fAguYd6SpZdSqDS3Cz39TVl9/bgCfc6s0mDPYKxXzJtvd7nTEqkumWd/Xu3uO+EJm+mOkljtzndVbtvmZSQQvWy9kabfSfcYak6d7Ob3/fakweNCe70qi8untZ5ndq/LSpKbbze2V7efSNRpRUN4xvD7rW/G0Iq0quPLC7fcfNme/vNph2Ll11k3Y18YJggFrFIT++ianV6/b9gu+le/TtESHKwfdS7t/8Dw4+o6YNxgfwAAAAASUVORK5CYII=);
}
+1 if you like this :)

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

asp.net - Hyperlink not working

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.

How to generate HTML in a Pop Up window with Asp.Net

I have very simple html report generated from one of my objects on server. I generate html code at PageLoad because I need to clear that object from session and don't want ask external web service for data after user clicks on link button.
Roughly idea is that user clicks on button on page and the report will be displayed at new window.
As I said I have html generated at PageLoad and right now stored in unique file at server. I also thought that I could hide the html code in hidden control. But that wont work without extra work, that would convert html code into some nonsense string and restored later on.
I can manage to display my html code into current window by using Response.Write(myhtml as string);
So my question are:
where could I store my html code beyond file system (that is tricky with security issues)
how to display my htmlcode into new window on click event. What way could I use.
I found one possible solution described here.
UPDATE:
Just adding pieces of code. It displays html string in current window which is not exactly I want.
private void InitData(){
string filename = DateTime.Now.ToString("yyyyMMdd_HHmmssfff");
lbtnPrintOutOrder.CommandArgument = filename;
StreamWriter swXLS = new StreamWriter((MapPath("Files\\")) + filename);
string message = GetEmail();//get data form session object
swXLS.Write(message);//save data to file
swXLS.Close();
}
protected void lbtnPrintOutOrder_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
{
string filePath = (MapPath("Files\\")) + e.CommandArgument.ToString();
string content;
using (StreamReader reader = File.OpenText(filePath)) {
content = reader.ReadToEnd();//get html from file
}
Response.Write(content);//load it to current window
Response.End();
}
One big question, is why do you need to clear the object from Session? Why cant you keep the object in session until after the string is displayed in the new window?
You could open an aspx page in the new window, use the string object stored in the session to output the html, and clear the session once the html is displayed.

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