MVC 3 VirtualPathUtility Issue - asp.net-mvc-3

I have an MVC 3 app with a Configuration folder that holds XML files specific to my application. I'm trying to enumerate the files in a view like this:
string configPath = VirtualPathUtility.ToAbsolute("~/Configuration");
foreach (string path in Directory.EnumerateFiles(configPath, "*.xml"))
{
// ...
}
However, the path resolves to C:\Configuration as evidenced by the error message:
Could not find a part of the path 'C:\Configuration\'.
What am I missing?

I don't know but this should work in your controller:
string configPath = Server.MapPath("~/Configuration");

Related

springboot load a folder as Resource or file inside src/main/resources

i would like to ask how to load a folder as Resource or File in SpringBoot.
Let's say i have src/main/resources/testfolder, I want to do something like:
File f = ResourceUtils.getFile("classpath:testfolder");
^ But then that would fail since ResourceUtils can only load actual file(.txt, .csv etc..), not a folder.. Thank you very much in advance..
Edit:
The reason is that i need to get the absolute path of the folder..
File f = ResouceUtils.getFile("classpath:testfolder");
String folderpath = f.getAbsolutePath();
folderpath should be "/workspace/intellij/ProjectName/src/main/resource/testfolder";
Thanks
As you want to use a temporary directory for testing instead of trying to use Spring classes to obtain a path and shoehorn your test in there use the TemporaryFolder rule from JUnit.
#RunWith(SpringRunner.class)
public class YourTest {
#Rule
private TemporaryFolder tempFolder = new TemporaryFolder();
#Test
public void yourTestMethod() {
String folder = tempFolder.getRoot();
when(yourMock.getOutputFolder()).thenReturn(folder);
// do your thing
// use tempFolder object to check files/read files etc.
}
}
If you have any folder(for ex: config) under resource folder you should try below i mentioned
File file = ResourceUtils.getFile("classpath:config/test.txt")
Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);

Spring Boot load another file from app.properties

I am new to Spring Boot. I have this emailprop.properties in src/main/resource:
//your private key
mail.smtp.dkim.privatekey=classpath:/emailproperties/private.key.der
But I am getting the error as
classpath:\email properties\private.key.der (The filename, directory
name, or volume label syntax is incorrect)
How do I properly load this file?
Update-1
my java code is
dkimSigner = new DKIMSigner(emailProps.getProperty("mail.smtp.dkim.signingdomain"), emailProps.getProperty("mail.smtp.dkim.selector"),
emailProps.getProperty("mail.smtp.dkim.privatekey"));
its working as "D:\\WorkShop\\MyDemoProj\\EmailService\\src\\main\\resources\\private.key.der"Instead of emailProps.getProperty("mail.smtp.dkim.privatekey")
Update-2
i have tried java code is
String data = "";
ClassPathResource cpr = new ClassPathResource("private.key.der");
try {
byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
dkimSigner = new DKIMSigner(emailProps.getProperty("mail.smtp.dkim.signingdomain"), emailProps.getProperty("mail.smtp.dkim.selector"),data);
Error is : java.io.FileNotFoundException: class path resource [classpath:private.key.der] cannot be resolved to URL because it does not exist
Tried Code is :
ClassPathResource resource = new ClassPathResource(emailProps.getProperty("mail.smtp.dkim.privatekey"));
File file = resource.getFile();
String absolutePath = file.getAbsolutePath();
Still same error..
please update the answer..
If you want to load this file runtime then you need to use ResourceLoader please have a look here for the documentation - section 8.4.
Resource resource = resourceLoader.getResource("classpath:/emailproperties/private.key.der");
Now if you want to keep this exact path in properties file you can keep it there and then load it in your Autowired constructor/field like that:
#Value("${mail.smtp.dkim.privatekey}") String pathToPrivateKey
and then pass this to the resource loader.
Full example you can find here. I don't want to copy paste it.
If your file is located here:
"D:\\WorkShop\\MyDemoProj\\EmailService\\src\\main\\resources\\private.key.der"
then it should be:
mail.smtp.dkim.privatekey=classpath:private.key.der
EDIT:
I see now, you are using DKIMSigner, which expects file-path string,
Try changing your code like this:
ClassPathResource resource = new ClassPathResource(emailProps.getProperty("mail.smtp.dkim.privatekey"));
File file = resource.getFile();
String absolutePath = file.getAbsolutePath();
dkimSigner = new DKIMSigner(emailProps.getProperty("mail.smtp.dkim.signingdomain"), emailProps.getProperty("mail.smtp.dkim.selector"),absolutePath
);

Maven java.io.FileNotFoundException

I'm developing a project with Maven. In a class to send e-mails, in run and dev modes, I get the following error: Caused by: java.io.FileNotFoundException: jQuery/images/logo.png (Ficheiro ou directoria inexistente) ==> translation = File or directory not found.
I've tryed lots of paths, like "./jQuery/images/logo.png", "/jQuery/images/logo.png" and others. The full relative path is: "src/main/webapp/jQuery/images/logo.png".
In "target" folder, the path is "project-1.0-SNAPSHOT/jQuery/images/logo.png".
Inside war file, is "jQuery/images/logo.png".
I don't think it's important, but I'm using NetBeans 7.1.1 as IDE.
I found that the absolute path returned in runtime is "/home/user/apache-tomcat-7.0.22/bin/jQuery/images/logo.png"!... It's not the project path!
How can I get a file in webapp folder and descendents from a Java class, in a Maven project?
The code is:
MimeBodyPart attachmentPart = null;
FileDataSource fileDataSource = null;
for (File a : attachments) {
System.out.println(a.getAbsolutePath());
attachmentPart = new MimeBodyPart();
fileDataSource = new FileDataSource(a) {
#Override
public String getContentType() {
return "application/octet-stream";
}
};
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
attachmentPart.setFileName(fileDataSource.getName());
multipart.addBodyPart(attachmentPart);
}
msg.setContent(multipart);
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, from, "password");
transport.sendMessage(msg, msg.getAllRecipients());
The path .../apache-tomcat-7.0.22/bin/jQuery/... is really odd. bin contains scripts for Tomcat, it should not contain any code nor any resources related to your application. Even if you deploy your app in the context /bin, the resources would end up under `.../apache-tomcat-7.0.22/webapps/bin/...
This looks like a mistake made in an earlier deployment.
Now back to your question. To get the path of resource of your web app, use this code:
String absolutePath = getServletContext().getRealPath("/jQuery/images/logo.png");
(docs)

ASP.NET MVC 3: How to look for the controller instead of file when id is file name

I've encountered with some strange problem. It's strange for me because I don't understand it and because before everything worked fine. So, my task is to call for controller and pass it file name (with extension) and controller should recognize this file, write into log and then return the file itself if it exists (in Downloads folder). What I'm doing:
public class DownloadController : Controller
{
public ActionResult Files(string id)
{
string filePath = Server.MapPath(Url.Content(string.Format("~/Downloads/{0}", id)));
string serverPath = Url.Content(string.Format("~/Downloads/{0}", id));
string ext = Path.GetExtension(filePath);
if (!System.IO.File.Exists(filePath))
{
//return to the error controller
}
string mem = "text/html";
if (ext == ".zip")
{
mem = "application/x-zip-compressed";
}
else if (ext == ".html" || ext == ".htm")
{
mem = "text/html";
}
else if (ext == ".pdf")
{
mem = "application/pdf";
}
//Save info about downloads into DB
repStat.SaveStatInfo(id, HttpContext.Request.UserHostAddress,
HttpContext.Request.UserHostName, HttpContext.Request.UserAgent);
return File(serverPath, mem, id);
}
}
There is part of the Global.asax:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("Content/{*pathInfo}");
It doesn't have more "ignores".
So, the problem is when I'm doing the call: mysite.com/download/files/test.pdf the server returns me "Page not found". Of course there is no such file in download/files path! It should call for the controller but not the real file. As soon as I delete the extension like mysite.com/download/files/test the server calls for the controller. I don't understand why it doesn't recognize the file name just as parameter and tries to find the file.
There is absolutely the same behaviour if I try to do with other controllers - as soon as parameter doesn't have any extension it works good else the server looks for the file.
The most strange thing is everything works good locally but doesn't work on the server (worked not tool long but then stopped).
It looks strange to me too. A workaround would be to encode the dot (.) like, for example,
test.pdf -> test++pdf
and then decode it then decode it back.
Probably not the best solution, but will certainly solve the problem.

Returning an MVC FileContentResult to download .pdf file from

Hi I've search around for this quite a bit but I didn't find a situation that really resembled mine..hope I didn't miss a duplicate somewhere
The Goal: Return a file from a UNC share to the client as a download/open option.
Info: The share is located on a different server than the one hosting the web site. When a corresponding folder name on the menu is clicked, I am able to successfully read from the share (I return the files as a JSON result) and in Jquery I then append list items for each file found in the folder and make the list item ID's the filename. This works great.
When these appended list items are clicked on I pass their ID's (which are the filename, like "thefile.pdf") to the following controller which returns a FileContentResult.
files[0].ToString() below is similar to "\server\folder\"
public ActionResult OpenTheFile(string id)
{
List<string> files = new List<string>();
files.AddRange(Directory.GetFiles(LNFiles.ThePath, id, SearchOption.AllDirectories));
Response.AppendHeader("Content-Disposition", "attachment; filename=" + id + ";");
return File(files[0].ToString(), System.Net.Mime.MediaTypeNames.Application.Pdf, id);
}
And yes the obligatory "it works on my local machine". When deployed to the IIS 7.5 server and I click on the list item I get this YSOD error:
The handle is invalid. (Exception from
HRESULT: 0x80070006 (E_HANDLE))
I'm impersonating a user with rights to the file share...I'm at a loss, i was thinking something with encoding or screwed up rights? I've tried using a virtual dir instead but alas same issue.
In my case
changing this:
public ActionResult Download(int id)
{
var item = ItemRepo.GetItemById(id);
string path = Path.Combine(Server.MapPath("~/App_Data/Items"), item.Path);
return File(path, "application/octetstream", item.Path);
}
to this:
public ActionResult Download(int id)
{
var item = ItemRepo.GetItemById(id);
string path = Path.Combine(Server.MapPath("~/App_Data/Items"), item.Path);
return File(new FileStream(path, FileMode.Open), "application/octetstream", item.Path);
}
has worked. I am putting this here just in case anyone needs.
Check out this for a workaround
You may want to try a packet capture to see if you are receiving the same issue as documented here:
http://forums.asp.net/t/1473379.aspx/1
For your unc path - are you directly referencing \servername\share or are you using a network mapped drive letter?
God Bless you : ProgRockCode.
and since that involved an ActionResult, I wrote a custom ActionResult that used the "WriteFile" method.
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.WriteFile(FilePath, true);
context.HttpContext.Response.End();
}

Resources