Find web.config location - iis

Given virtual directory and port can you find the actual path of a web application?
I can get the virtual directory and port via a visual studio setup project, and I'd like to make some modification to the web.config file after install (using a custom action).

You could use DirectoryEntry class:
using (var entry = new DirectoryEntry("IIS://server/W3SVC/1/root/VirtualDirectoryName"))
{
var physicalPath = entry.Properties["Path"].Value;
}

Related

NullPointerException downloading pdf file from azure app service, Spring-boot Java 8

I have a spring boot application with Java 8 in which I can create and download a PDF file with Itext PDF library, in local and development environment this works fine but when I deploy the application in my azure app service I can't download this file, I had a NullPointerException.
2020-11-24T13:04:12.310887019Z: [INFO] ****Downloading PDF file: /home/site/descargas/
2020-11-24T13:04:13.814155878Z: [INFO] *** ERROR : java.lang.NullPointerException
2020-11-24T13:04:13.815304521Z: [ERROR] com.itextpdf.text.DocumentException: java.lang.NullPointerException
2020-11-24T13:04:13.816149053Z: [ERROR] at com.itextpdf.text.pdf.PdfDocument.add(PdfDocument.java:821)
2020-11-24T13:04:13.816580670Z: [ERROR] at com.itextpdf.text.Document.add(Document.java:277)
And my code is:
document = new Document();
FileOutputStream coursesFile = new FileOutputStream(DIRECTORIO_TEMP+"cursos.pdf");
PdfWriter writer = PdfWriter.getInstance(document, coursesFile);
PDFEvent eventoPDF = new PDFEvent();
writer.setPageEvent(eventoPDF);
document.open();
//margenes de documento
document.setMargins(45, 45, 80, 40);
PdfPTable table = new PdfPTable(new float[] {15,35,50,10});
table.setWidthPercentage(100);
table.getDefaultCell().setPaddingBottom(20);
table.getDefaultCell().setPaddingTop(20);
Stream.of("ID", "Área", "Nombre", "Horas").forEach(columnTitle -> {
PdfPCell header = new PdfPCell();
header.setBackgroundColor(COLOR_INFRA);
header.setBorderWidth(1);
header.setHorizontalAlignment(Element.ALIGN_CENTER);
header.setPhrase(new Phrase(columnTitle, fuenteCabecera));
table.addCell(header);
});
for (Curso curso : cursos) {
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(new Phrase(curso.getCodigoCurso(), fuenteNegrita ) );
table.addCell(new Phrase(curso.getAreaBean().getNombre_area(), fuenteNormal ));
table.addCell(new Phrase(curso.getNombreCurso(), fuenteNormal ));
PdfPCell celdaHoras = new PdfPCell( new Phrase(curso.getHoras() + "", fuenteNormal ) );
celdaHoras.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(celdaHoras);
}
document.add(new Paragraph(Chunk.NEWLINE));
document.add(new Paragraph(Chunk.NEWLINE));
document.add(table);
document.close();
coursesFile.close();
The file permission in my Azure app service are:
Newest
Answer For Linux:
I don't know what method you used to deploy the whole process of webapp. However, the descargas folder will not be created automatically in any way.
No matter what method you use to deploy the webapp, it is recommended that you log in to kudu and check the descargas folder and whether the files under the folder exist. It is not recommended to use FTP to upload.
In addition, there should be no concept of D:\ drive and virtual application under Linux. It is recommended to use relative paths in the code to read files.
And
PRIVIOUS
Answer For Windows:
This error occurs because the access path must be wrong. I don't know if your code uses a relative path or an absolute path.
So my advice is:
Use absolute paths to access files.
I have test and it works for me, both in my local and on azure.
The file path like D:\home\site\myfiles\a.pdf .
Use virtual directories to access files
You also can use Virtual Directory to access your file, the path you access by broswer,like https://www.aa.azurewebsites.net/myfiles/a.pdf, and you also can check it by kudu, like D:\home\site\myfiles\a.pdf.
For more details, you can refer to the offical doc,https://learn.microsoft.com/en-us/azure/app-service/configure-common#windows-apps-uncontainerized .

.net core web API,static file images not loading properly?

I have .net core web API PROJECT. I want to put some static images in this project.I have below code in start up file
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
provider.Mappings[".png"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), #"MyStaticFiles")),
RequestPath = new PathString("/StaticFiles"),
ContentTypeProvider = provider
});
when I run or deployed this web project, i have checked under it has StaticFiles folder has test.png
when I browse for test.tt/StaticFiles/test.png, or test.tt/wwwroot/StaticFiles/test.png or test.tt/wwwroot/StaticFiles/images/test.png
browser is not loading that image, it is displaying white page, where I check on network console of by F12,it is delivering response of type document and json.
My problem is image is not displaying, i have tried more images but not helpful.I am sure there is image,folder in my path.
can you tell how if I browse test.png,direct hitting path to get static file .net core WEB API images?
By default, static files go into the wwwroot in your project root. Calling app.UseStaticFiles(), causes this directory to be served at the base path of the site, i.e. /. As such, a file like wwwroot/images/test.png would be available at /images/test.png (note: without the wwwroot part).
I'm not sure what in the world you're doing with the rest of this code here, but you're essentially adding an additional served directory at [project root]/MyStaticFiles, which will then be served at /StaticFiles. As such, first, test.png would have to actually be in MyStaticFiles, not wwwroot, and then you'd access by requesting /StaticFiles/test.png.
However, there's no need for this other directory. If you simply want to add some additional media types, you can do that via:
services.Configure<StaticFileOptions>(o =>
{
var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".myapp", "application/x-msdownload");
// etc.
o.ContentTypeProvider = provider;
});
And then just use:
app.UseStaticFiles();
Nothing else is required.

Accessing an IIS Virtual Directory from Dotnet Core

I'm building a Dotnet Core web app that needs to allow the Windows-Authenticated user to browse through the connected virtual directories and view and select files hosted there.
Is there a way for a Dotnet Core application to access a virtual directory? And barring that, is there a way for a regular Dotnet application to do it?
It is possible to do so. I've been working on this thing for two weeks now, looked everywhere to get an answer. Here is how I did it.
You will need to add in the configure app.UseFileServer() in the Configure method of the Startup.cs
app.UseFileServer(new FileServerOptions
{
PhysicalFileProvider("\\\\virtualPath\\photos\\wait\\"),
RequestPath = new PathString("/AROULETTE"),
EnableDirectoryBrowsing = true
});
How does this work?
The way it is set up, you would enter http://localhost:5000/AROULETTE
and it would open the virtual path provided in the PhysicalFileProvider in the browser. Of course this is not what I actually wanted.
I needed to create a directory and copy files into the virtual directory with C#.
Once I had the FileServer setup, I tried something like this which does not work.
if(!Directory.Exists("/AROULETTE/20170814"))
{
Directory.Create("/AROULETTE/20170814")
}
of course, neither does this
var path = Path.Combine("http://localhost:5000/", "AROULETTE/20170814")
if(!Directory.Exists(path)
{
Directory.Create(path)
}
Instead, you just use the actual virtual path of the folder.
if(!Directory.Exists("\\\\virtualPath\\photos\\wait\\20170814"))
{
Directory.Create("\\\\virtualPath\\photos\\wait\\20170814")
}
Thus UseFileServer is used to create a "bridge" between the application and the virtual folder the same way that you would create a virtual directory with ASP.Net 4.5
Hope this can help some people because most of the answers about this topic were not clear at all.

Accessing Azure IIS logs from within the same website

I have an Azure website configured to write IIS logs to file system. I would like to have a dashboard page within my website where administrators can view reports about traffic on the site, which has been generated by parsing these logs.
I have tried to access the log directory in code by both DirectoryInfo.GetFiles(), and by attempting to connect over FTP using FtpLib.
From outside of Azure, I can connect to the FTP and download the logs, but from code running in the Azure website, I cannot.My assumption is that Azure does not allow outbound FTP traffic from website code.
The folder structure for Azure (by inspecting the FTP) looks something like:
Site: /site/wwwroot
Logs: /LogFiles/http/RawLogs
Within the Azure portal you can create virtual directories, but they are only allowed within /site.
Site is running as an Azure Web Site, MVC 4, Integrated pipeline, 64bit, .NET 4.5, and for FTP I am using FtpLib v1.0.1.2. FtpLib fails at Login() with message: Unknown error (0x2ee2)
I am aware that I can change the logging within Azure to log to Blob Storage, however this would result in additional monthly cost. Are there any other options to access these files?
Thanks.
Edit: Have been asked to supply code, here is the FTP version (works locally, not on Azure):
using (var ftp = new FtpConnection("XXXXXXXX.windows.net", "XXXXXXXX", "XXXXXXXX"))
{
ftp.Open();
ftp.Login(); //Fails here
ftp.SetLocalDirectory(Server.MapPath("~/")); //Temp
ftp.SetCurrentDirectory("/LogFiles/http/RawLogs");
foreach (var f in ftp.GetFiles("*.log"))
{
ftp.GetFile(f.Name, f.Name, false);
ftp.RemoveFile(f.Name);
}
}
And here is the file system version:
//var logRoot = Server.MapPath("~/../../LogFiles/http/RawLogs"); //Throws error about traversal outside of site root
//var logRoot = "/LogFiles/http/RawLogs"; //Throws error: Could not find a part of the path 'D:\LogFiles\http\RawLogs'.
var logRoot = "LogFiles/http/RawLogs"; //Throws error: Could not find a part of the path 'D:\Windows\system32\LogFiles\http\RawLogs'.
foreach (var f in new DirectoryInfo(logRoot).GetFiles("*.log"))
{
f.CopyTo(root + f.Name, true);
f.Delete();
}
I see the problem with paths to the log files. AzureWebsites uses C Drive, but in your implementation you are getting D Drive. Use Server.MapPath("~") and then do string manipulations on top of it to get the right ROOT Path. So Root directory will be having two more directories - LogFiles and Site. As you already got the Root directory, append it with LogFiles directory and read all files from there.

IIS 7 - Virtual directory redirection path?

I wrote this little web app that lists the websites running on the local IIS + virtual directories attached to the websites.
Using the following line I was able to get the HTTP Redirection URL of a virtual directory, if it was set to redirect:
_directoryEntry.Properties["HttpRedirect"].Value.toString()
Which works quite nicely in IIS 6 - but the value is empty when I try my app in an IIS 7 - and I tried switching the application pool to Classic pipeline as well - what has changed in IIS 7 here? And why?
In IIS7 <httpRedirect> element replaces the IIS 6.0 HttpRedirect metabase property.
You need to set it up like this in your web.config file:
<system.webServer>
<httpRedirect enabled="true" destination="WebSite/myDir/default.aspx" />"
</system.webServer>
If you do not want to tweak web.config, this article talks about a way to do them the IIS 6 way: Creating Http Redirects in IIS7 on Virtual Directories like IIS6
Hope this helps.
What has changed?: IIS7 has a completely new configuration system similar to .NET's hierarchical configuration system. Checkout this link for more detail here on what's changed.
How to get the HttpRedirect value: In C#, rather than using the System.DirectoryServices namespace to access the IIS configuration settings, use the new Microsoft.Web.Administration.dll.
Your code should look something like this example from IIS.net:
using System;
using System.Text;
using Microsoft.Web.Administration;
internal static class Sample
{
private static void Main()
{
using (ServerManager serverManager = new ServerManager())
{
Configuration config = serverManager.GetWebConfiguration("Default Web Site");
ConfigurationSection httpRedirectSection = config.GetSection("system.webServer/httpRedirect");
Console.WriteLine("Redirect is {0}.", httpRedirectSection["enabled"].Equals("true") ? "enabled" : "disabled");
}
}
}
You can actually do quite a lot with the new Microsoft.Web.Administration.dll. Checkout Carlos Ag's blog here for some ideas.
Two quick notes:
Microsoft.Web.Administration.dll is available if the "IIS Management Scripts and Tools" role service is installed. It should be under the inetsrv directory in systemroot.
Any code you run with the MWA dll needs to run as Administrator to access IIS configuration, so just make sure the account running the script has admin rights.
Hope this helps!

Resources