ASP.NET Generating .pdf files, UnauthorizedAccessException on Save() - asp.net

I have a list of jobs and i give users the option to get job description in form of a pdf file. I use MigraDoc/PDFsharp to generate pdf files.
The problem is, after i render the pdf document and want to save it somewhere on the DevServer i get UnauthorizedAccessException on creating FileStream in PDFsharp PdfDocument.Save() method.
I never really used Windows for anything more advanced than playing games and i'm not sure why would i get this exception since i'm logged in as Administrator user and i guess that my ASP.NET application is running with Administrator privilleges and should be able to write files pretty much anywhere on filesystem.
The Code.
GridViewRow jobRow = (GridViewRow)(sender as Control).Parent.Parent;
Document jobDocument = new Document();
Section xyz = jobDocument.AddSection();
xyz.AddParagraph("Wonderfull job");
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true);
pdfRenderer.Document = jobDocument;
pdfRenderer.RenderDocument();
string filename = "Job_" + jobRow["3"] + ".pdf"; // Job_[title].pdf
pdfRenderer.PdfDocument.Save(filename);
Last line is the line that causes the exception.
Any suggestions? I'm not an ASP.NET developer and I'm forced to use ASP.NET for my school project so this may be a very simple problem but i really don't know what to do and what to search. Thanks for answering!

Administrator account =! IIS user.
The IIS User needs to have writing privileges, too!
On most machines it is know as "IIS_User" or maybe "network service". First you can grant writing permissions to every User. If this works for you, you know what to do.
First try to set an absolute path as filename, maybe a directory outside of "C:\inetpub\wwwroot"?
Hope this helps!

Related

Files on network drive are not accessible when website is published on IIS

I have a website that shows a list of recommended documents retrieved from a network drive, Z drive. for each document, if the user pushes a button, he can navigate to the path of the file through windows explorer. below is the code.
string argument = #"/select, " + filePath;
System.Diagnostics.Process.Start("explorer.exe", argument);
an example of filepath is : z:\ecomarathon2012\04-Reports\fuel cell and batteries comparative.docx
Now, I have published the website on IIS but the button does not work anymore to show me the path of the file.
What changes I need to add in order to solve this problem for the published version of the website?
Sounds like your IIS user identity doesn't have access to the network drive. Give that user read access and I believe your code should work. If not, try to log some errors using try catch and post them here.

Understanding Directory Securities with an ASP.NET Web Application

I have a requirement to create a directory on my applications server which is secure to all, but the application itself.
I have read this article
System.IO.Directory.CreateDirectory with permissions for only this current user?
Converting to VB, the code it suggests is:
Dim ds As New DirectorySecurity()
Dim sid As New SecurityIdentifier(WellKnownSidType.CreatorOwnerSid, Nothing)
Dim ace As New FileSystemAccessRule(sid,
FileSystemRights.FullControl,
AccessControlType.Allow)
ds.AddAccessRule(ace)
Directory.CreateDirectory(Dir, ds)
But when I follow that code instruction there, I cannot add files to the directory I have created.
I am guessing I should change the value of WellKnownSidType but I do not know what to!
To recap - what I need is a directory which my application can read and write to, but a user cannot access from a web browser to download any content.
Any help much appreciated!

Download and run file in client machine using asp.net

I'm trying to download and run a file to the client machine. The client is aware of that.
It's a ttkgp file that's dynamicly generated.
I've tried using Processs.Start() that worked fine on my local machine (first saved the file to C:\ then lunched it), but it's not working from the server. It's not my server but a hosted one. They are trying to help but no luck so far.
I've seen this code:
public void ProcessRequest(HttpContext context)
{
string fileName = context.Request.QueryString["filename"];
FileInfo fi = new FileInfo(fileName);
context.Response.ContentType = "application/x-rar-compressed";
context.Response.AppendHeader("Content-Disposition",
string.Format("attachment; filename=download{0}", fi.Name));
context.Response.WriteFile(fileName);
context.Response.End();
}
But since I dont know what's "HttpContext context" is, I've no idea if it works.
Is it some server previlges need to be changed? or simply this code will do the trick?
Thank you
UPDATE (24.6.12): I'm nearly finished with the problem, all I need now is to know how to open an html page in a new tab / window and close it second later. Once I'm done, I'll post back here all the process, I'm sure it'll help other people.
UPDATE (26.6.12):
Here's what I've got:
The goal is to download an TTKGP file from asp.net webiste to local user machine and run it.
Step 1: generate the file with code behaind (c#) on the server (V)
Step 2: copy the file or it's content to user machine (X)
Step 3: run the file using JS (V)
Here's the thing: I CAN copy from a text file on the server to a text file on the user machine, but not from TTKGP files. It's strange because this are just text files just a different extantion.
The code for copying text files:
enter code here
function copyremotetxt() // works
{
// copy the txt file
var fso = new ActiveXObject("Scripting.FileSystemObject");
var newfile = fso.CopyFile("remote.txt", "C:\\Users\\***\\local.txt");
}
Perhaps I can change the file type on the user machine?
Notice 1: I know that's a security issue, the site is just for known user not the open public
Notice 2: I know there are better ways to get the task done, but there are strict limitaions on many things
Thanks for those how can help!!
This code will do the trick. It will prompt the client to download and save the file on his computer at the location he decides. What happens next with this file is the client's decision, not yours. He might simply close the Save As dialog, interrupt the download, delete the file, ... It's up to him.
Another remark: this code is extremely dangerous because it allows the client to pass any filename he wants as query string parameter and download it. So he could read absolutely all files on the server which is probably not something that you want to happen.
Ok, this need a different aproach.
I'll try using JavaScript do read the file on the server, rewrite it in the user machine and activate it. Any clues would be grate! For a start, how to I read file in JS? I'm new to it.

Parameter is not valid error when creating new bitmap

I am displaying images on my page and then attempting to find the current height of the images in order to vertically position them. I am doing this by creating a new bitmap and then getting the height of the bitmap, as follows:
Dim sampleImg As New System.Drawing.Bitmap(Server.MapPath(String.Format("/Uploads/Products/Images/w100h100/{0}", e.Item.DataItem("Filename"))))
Dim imgHeight As Integer = sampleImg.Height
When I run this on my local machine, all works fine. However, I have recently uploaded the site so far to my development server and when I run the same code from there, I get this error message:
Parameter is not valid
I have been searching forums to try to find a solution but I have ended up a bit unsure where else to look because the file definitely exists on the development server and the code works fine on my local machine. The server I am using is a VPS and I am quite a beginner with working with servers so I don't know if there is anything I haven't set up on there which is stopping it from working?
Whilst trying to find a solution, I have also tried the following code but I get a System.IO.FileNotFoundException error message:
Dim sampleImg As System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath(String.Format("/Uploads/Products/Images/w100h100/{0}", e.Item.DataItem("Filename"))))
I am wondering if anyone can help me find a solution to this, or alternatively is there a different method to acheiving the same end?
All help is very much appreciated. Thanks.
It may be a file permissions issue, you need to ensure that the IUSR account for your site has read access to the image file. To do this -
R-click the file, Properties, Select the "Security" tab - you will have a list of users who have access to the file. A quick check is to add "Everyone" with read priviliges. To keep it locked to your ASP.Net instance only you should start IIS Manager, r-click your app pool and the Identity is the user your app runs under.
If you are running through IIS it may be that the file type isn't set up in the available MIME types for the site.
http://technet.microsoft.com/en-us/library/bb742440.aspx
With IIS7 there is a module for each Site called "MIME Types". Check whether the File Extension is in the list, and if not, add it with the appropriate MIME Type (list of mime types in link above)
I think you have to use ~ root operator to resolve the path issue.
Dim sampleImg As System.Drawing.Image =
System.Drawing.Image.FromFile(Server.MapPath(
String.Format("~/Uploads/Products/Images/w100h100/{0}",
e.Item.DataItem("Filename"))))
OR the specified file is not a valid image file.

Change script execute permissions of a directory in IIS6 dynamically thru ASP

This is kind of an advanced problem, hopefully one of you asp/VB gurus will have a suggestion. I am trying to dynamically set a folder's execute permissions in IIS6 from an asp page. I have given the server full permissions to make the changes necessary. When I run the code I get:
Microsoft VBScript runtime error '800a0046'
Permission denied: 'GetObject'
/learning.asp, line 11
I have a server setup with IIS6 running a couple asp websites. I use a code like this to create a folder called "files"
set fso = Server.CreateObject("Scripting.FileSystemObject")
set folder3 = fso.CreateFolder(Server.MapPath(username & "/files"))
set folder3 = nothing
set fso = nothing
Works fine and creates the files folder just where I want it. However, the new folder has execute permissions set to "scripts and exe's" and I need it to be "never" or false. There is a system object that you can call to make this change, and I even have a piece of code that I wrote after reading another tutorial.
It doesn't work and gives the above error. I think, maybe, I am just leaving something out, but this stuff is a little over my head. Here is what I used, but I don't know the syntax or what exactly to call.
Set root = GetObject("IIS://localhost/" & username)
Set newVDir = root.Create("IIsWebVirtualDir","files")
newVDir.Path = "e:\iis3\server2\ADSI"
newVDir.AccessScript = False
newVDir.SetInfo
I have searched around for 3 days trying to find a solution to this, but not very many people do this type of thing apparently, because there are no posts about it that I can find.
Anyway, I don't understand what the getobject is supposed to do, and what newVDir.path I am supposed to be using?
Thank you, in advance, for any helpful suggestions you may have.
This article (see http://technet.microsoft.com/en-us/library/bb742439.aspx) explains what the GetObject actually does.
I believe, what happens behind the scene is that a COM object of type "IIS Admin Service" is (needs to be) created to perform your operations. By default, the IIS application pool account is not allowed to create such object. So maybe its worth to check it. Open Control panel->Administrative services, run "Component services". Find "my computer" in the tree and there find "IIS admin service". Check "activation" and "launch" permissions, add some if necessary.

Resources