Understanding Directory Securities with an ASP.NET Web Application - asp.net

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!

Related

Different Path Folder vb.net

In case, i'm create function to process excel and in the end of process i want to save excel into my "Download" folder in my pc.. but i get a different folder path between my pc and my server.. when i running my application using my pc, i get path "C:/Users/MyPCUserName/Downloads" but when i running application on published file (iis server), i get path "C:\Users\SYSTEM\Downloads\85FE1000".. I don't know what's the wrong with my code / function..
This my Code :
Private Sub myMethod(ByVal pProjectNo As String, ByVal pOrderNo As String)
Dim dt As DataTable = ClsUploadBreakDownInquiryDB.GetFinalInspectionData(pProjectNo, pOrderNo)
if dt.Rows.Count > 0
'My Function Here
Dim user As String = System.Environment.UserName
exl_b2.SaveAs("C:\Users\" & user & "\Downloads\" & pProjectNo & "_" & Microsoft.VisualBasic.Format (Date.Now, "yyyyMMdd_HHmmss") & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook)
End If
End Sub
You can save a up-loaded file on your web server quite much any place you want.
However, if you talking about a client side user - and their browswer download lcoation? You have ZERO, but 100% ZERO control over that location.
In fact, the user might be using a iPhone, or Android - and not even a desktop comptuer.
You do not have ANY ability in ANY case to control the location of a user download of a file. Files on the local computer are 100% hands off. When they download, it will usually go to their downloads folder - but the user settings control that.
You can't grab, see, or set ANY file location on the client side computer. I mean, if you could do that, then when you come to my site to view a cat picture? My code would then rummage around on your computer - looking for files called passwords, or files called banking etc and steal them
So, server side code behind? Sure, you can in most cases save the file on the web server computer anywhere you like - it don't matter a whole lot.
However, if you talking about client side computer locations for the user and their browser hitting your web site? No, you have zero information, zero control over the users files, and even where they choose to save, or download such files - that is their computer - and browsers give protection for reasons of security.
This can sometimes be confusing when using Visual Studio during development, since your computer, your browser and your web site are all running on the ONE SAME computer, but in a typical deployment, that of course is not the case. So, code behind has zero knowledge about the users local file system.
As a result, you cannot grab, or set ANY kind of file location information on the client side computer.
So, saving to "users" with code behind is ONLY going to apply to the code behind web server "user", and has nothing to do with the client side user.
As a general rule, any and all folders you work with and use from code behind? In EVERY case that should be a sub folder of your root of your project.
Keep in mind:
Any markup code - urls - that is relative to your web site
Any code behind - plane jane windows path name.
So, if you add a folder to your project, it might be say folder UpLoadFiles.
So, then web based, mark up based will be like this:
https://localhost:44392/UpLoadFiles/doc.pdf
So, UpLoadFiles is simple a sub folder in your project.
However, in code behind, your code ALWAYS works with plane jane valid windows file names. So, to convert above to a plane jane file path in windows? You do this:
Dim strFile As String = Server.MapPath("~/UpLoadFiles/abc.txt")
Dim strText As String = File.ReadAllText(strFile)
At this point, now str file is a plane jane valid full good old fashioned windows file name.
So, code behind = always plane jane window path name
So, web markup and URL = always a relative path from your project root.
dim strTextFile = File.ReadAllText(strFile).

virtual directory - How to load image files for asp.net viewing?

There are so many similar questions around the web, but none of them have helped me with this.
I have an asp.net application on a company intranet server. It is used to access a database on another file server, which also contains a number of images relevant to each record in the database.
I am a developer, but not a network person. I know a little bit about IIS, and using the IIS Manager, I created a virtual directory inside the asp.net application folder that maps to the UNC address on the other server where the images are. Using IIS Manager, I can explore the virtual directory and see all the files there. The problem is getting them to show up in my asp.net application.
I've tried setting permissions on the folder for Network Service, IUSR_aspnetserver, and my own credentials; I've tried various permutations of the path string, with / or // or \ or \, etc. I've tried impersonation, but I don't know if I am doing it right. I've placed a "debug" label on the page that tells me the path of the image while the app is running, and it is correct. Nothing seems to work.
Obviously there's something I am missing, but my network comprehension is around zero, my IIS experience is hardly any better, and I can't seem to get our staff of IT "experts" to help. And before you jump to any conclusions, I have a great personality.
Any ideas would be appreciated.
Thanks!
EDIT for #MohsinMehmood:
(I hope this is not too convoluted)
The page has a mapped drive in IIS to UNC share \\OtherServer\AppName\Images to a folder named ReceiptImages.
The web.config file has this entry:
<appSettings>
<add key="ImageFilePath" value="ReceiptImages/"/>
</appSettings>
And in the PageLoad event I have
ViewState("ImagesPath") = ConfigurationManager.AppSettings("ImageFilePath")
To create a global path string.
Then in code (VB) it's:
Dim btnReceiptThumbnailButton As New ImageButton
With btnReceiptThumbnailButton
.ID = "btn" & LineItem
.CssClass = "thumbnails"
.ImageAlign = ImageAlign.AbsMiddle
.Visible = True
.BackColor = Drawing.Color.White
.BorderColor = Drawing.Color.Black
.BorderWidth = 1
.ImageUrl = ViewState("ImagesPath") & LineItem
.CommandName = "GetReceiptImage"
.CommandArgument = LineItem
End With
I don't know if it was important enough to mention that the image is being placed in a button control to make it a thumbnail.

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

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!

ASP.NET loses session data when delete directory on WebApplications

I'm creating a web application in asp.net mvc2 and I'm having a little problem in an interesting situation that I assume is a default behaviour on webapplications. (sessionstate= inproc)
When i delete a directory inside the webapplication root Directory, my session data is cleaned.
I've read some questions from people asking for a solution, but not much about the problem, does anyone know how to prevent this behaviour?
Note: I don't want to move directory for other "subdomain" served by other instance of IIS, and don't want to change sessionstate for sqlserver
Thanks in advance for your help.
THANKS GUYS, FOUND THE SOLUTION SOMEWHERE ON A LINK OF THAT ARTICLE.
i've added on my global.asax Application_Start the folowing code:
Dim p As System.Reflection.PropertyInfo = GetType(HttpRuntime).GetProperty("FileChangesMonitor", Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static)
Dim o As Object = p.GetValue(Nothing, Nothing)
Dim f As System.Reflection.FieldInfo = o.GetType.GetField("_dirMonSubdirs", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.IgnoreCase)
Dim monitor As Object = f.GetValue(o)
Dim m As System.Reflection.MethodInfo = monitor.GetType.GetMethod("StopMonitoring", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
m.Invoke(monitor, New Object() {})
THANKS.
http://dotnetslackers.com/Community/blogs/haissam/archive/2008/11/12/disable-session-expiration-when-using-directory-delete.aspx
Most likely relates to this one: ASP.NET Deleting a directory results in application restart.
this blog post might clarify things a bit for you: Deleting Directory in ASP.net 2.0
My suggestion would be to create a virtual directory and manipulate the contents of that directory (instead of touching app directory itself).

How do I get the current Application Name (in terms of IIS) in a classic asp Web application

I have a classic asp application which retrieves the current application name and sets an Application variable containing that name. This name is important (I wont go into why) and is essentially the friendly name in IIS.
The problem is, the implementation used to get this name is flawed, it a) assumes the home directory contains the string wwwroot, and b) assumes the folder name is the same as the application name. I can no longer guarantee these conditions.
I would have thought the application name is know at run-time but I can't seem to find it in either Session or Application variables (at application start up entry point in global.asa). Any ideas?
You may want to try something like this:
Dim obj
Dim inst
inst = Request.ServerVariables("INSTANCE_ID")
Set obj = GetObject("IIS://localhost/W3SVC/" + inst)
Response.Write obj.ServerComment
If by friendly name you are referring to the IIS description, you might get some mileage out of the findweb.vbs file in the AdminScripts Folder of IIS (normally c:\Inetpub\AdminScripts) Some of the other scripts in that folder might be able to get you further too.
Try this aswell. It shows how to enumerate the IIS Websites through ADIS

Resources