Uploading in MVC Dynamically creating folder with persmissions - asp.net-mvc

VS'12 Ineternet Application Template asp.net C# MVC4, EF Code First
Upload Post Method
if (ModelState.IsValid)
{
foreach (var file in attachments)
{
string strMappath = "~/UploadedImages/" +var1+ "/" + var2+ "/" + var3+ "/" + var4+ "/" + var5 + "/";
if (!Directory.Exists(strMappath))
{
DirectoryInfo di = Directory.CreateDirectory(strMappath);
}
// Some browsers send file names with full path. We only care about the file name.
//var fileName = Path.GetFileName(file.FileName);
var fileName = Path.GetFileNameWithoutExtension(file.FileName) + Path.GetExtension(file.FileName);
var destinationPath = Path.Combine(
Server.MapPath(strMappath), fileName);
file.SaveAs(destinationPath);
}
My Questions are
Why is it not creating my Folders
When i ( cheat and make them myself ) i have no permissions...
How can you best upload Dynamically ( I would like to keep uploaded files separately )
Is there a better way to manage them?
This is for both on the Dev machine though IIS and on my Server-also IIS

Use Server.MapPath(strMappath) to create folders and check if exist.

Related

why asp.net mvc does not include the image uploaded folder in the project?

what I have found that the images uploaded by my application are not included in the project and that I have to include them manually image by image so what is the correct way of asp.net mvc project to let the images uploaded to be included in the project.
The following code is the one that upload the images to the folder and creates a unique name for each image. but still those images are not included in the project explorer.
public ActionResult Create(Job job, HttpPostedFileBase JobImage)
{
var value = "999999999";
var result4 = from app in db.Job where app.UniqueJobImageName.Contains(value) select app;
if(result4.FirstOrDefault() != null)
{
value = generateRandom();
}
if (ModelState.IsValid && CheckFileType(JobImage.FileName))
{
string ext = Path.GetExtension(JobImage.FileName);
var fileName = Path.GetFileName(JobImage.FileName);
job.JobImage = JobImage.FileName;
job.UniqueJobImageName = value + ext;
var path = Path.Combine(Server.MapPath("~/Images"), value + ext);
JobImage.SaveAs(path);
job.UserId = User.Identity.GetUserId();
job.jobUrl = "";
job.Month = DateTime.Now.ToString("MMMM");
job.DateAndTime = DateTime.Now;
AllJobModel all = new AllJobModel
{
JobTitle = job.JobTitle,
JobDescription = job.JobDescription,
JobImage = job.JobImage,
UniqueJobImageName = job.UniqueJobImageName,
locationName = job.locationName,
minimumSalary = job.minimumSalary.ToString(),
maximumSalary = job.maximumSalary.ToString(),
jobUrl = job.jobUrl,
PostedDate = DateTime.Now.ToString("dd/MM/yyyy"),
UserId= User.Identity.GetUserId(),
};
db.AllJobModel.Add(all);
db.SaveChanges();
db.Job.Add(job);
db.SaveChanges();
return RedirectToAction("Index","Home");
}else if (!CheckFileType(JobImage.FileName))
{
}
return View(job);
}
enter image description here
This doesn't make any sense. The uploaded images are content created by the user. They are not a deployable component of the site (or, they shouldn't be anyway). They are user-generated content, not developer resources.
If you are looking to effectively migrate your data (i.e. copy database entries and other user-generated content such as image files) from one environment to another, then that is a separate task for which you can create a separate process and/or automated script. Don't confuse it with the job of uploading a new version of your application code.
P.S. Even if what you were asking for was a sensible goal, it's impossible anyway - the executable version of your code is not the same as the code you see in Visual Studio in your project. In a modern ASP.NET application the executable code is in a different folder (even when you're running in debug mode in Visual Studio) and it has no concept or knowledge of the original project it was compiled from, or where to find it, or how to interact with it.

Unable to view screenshots in Jenkins reports

My jenkins reports do not show the screenshots captured in the runs. (They are run on a MAC). However, when I run the same job locally (windows machine), the reports have the screenshots.
I see the error as below in the Jenkins report.
When I try to open the image, It shows below. It's unable to find the path to the image actually.
Error : http://*****-mac:8080/job/***Test/job/******/ws/target/screenshots/2019-01-14/Sign%20In20190114154253.png
Actual: http://*****-mac:8080/job/***Test/job/******/HTML_20Report/target/screenshots/2019-01-14/Sign%20In20190114154253.png
I'm using the below code to capture the screenshot. It does capture the screenshots & I can see them in the actual location.
I don't know when I did a mistake, these images are not seen as links/not available in the report:
public void captureScreenshot() throws IOException {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateForScreenshots = dateFormat.format(date);
File localScreenshots = new File(new File("target/screenshots"), dateForScreenshots);
if (!localScreenshots.exists() || !localScreenshots.isDirectory()) {
localScreenshots.mkdirs();
}
System.setProperty("org.uncommons.reportng.escape-output", "false");// this is to create a link in ReportNG
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String destination = System.getProperty("user.dir") + "/target/screenshots/" + dateForScreenshots + "/" + getDriver().getTitle() + Utils.generateRandomString() + ".png";
File screenshotName = new File(destination);
//Now add screenshot to results by copying the file
FileUtils.copyFile(scrFile, screenshotName);
Reporter.log("<br> <img src='" + destination + "' height='90' width='160' /><br>");
Reporter.log("");
}
From this line
Error : http://*****-mac:8080/job/***Test/job/******/ws/target/screenshots/2019-01-14/Sign%20In20190114154253.png
I think that Jenkins cannot find the target branch in the workspace folder (ws). Probably you need to specify the workspace folder in the Jenkins job (as in this answer) or just change the destination variable somehow to something like (added /HTML_20Report):
String destination = System.getProperty("user.dir") + "/HTML_20Report/target/screenshots/" + dateForScreenshots + "/" + getDriver().getTitle() + Utils.generateRandomString() + ".png";

ASP.NET MVC download prompt not appearing

I'm trying to generate a Excel .xlsx file in a controller action. I would like to have the website show a download prompt to download the resulting file. The controller actions executes fine, but no download prompt is shown. Nothing happens.
I've tried:
MemoryStream mstream = ... //generated file;
return File(mstream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", model.DisplayName + ".xlsx");
I've tried:
return new FileStreamResult(mstream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = model.DisplayName + ".xlsx" };
I've tried:
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + model.DisplayName + ".xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.Write(mstream.ToArray());
Response.End();
return Content("");
I even tried saving the file to disk, then returning via the filepath
return File(filepath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
What am I doing wrong?
Thanks!
I am using the following code in an MVC project.
public ActionResult GetCSV()
{
string filename = "example";
string csv = MyHelper.GetCSVString();
return File(Encoding.UTF8.GetBytes(csv.ToString()), "text/csv", string.Format("{0}.csv", filename));
}
My csv string could look something like this
"Col1,Col2,Col3\nRow1Val1,Row1Val2,Row1Val3\n"
To trigger this download in a new window I call the following JavaScript
window.open('/MyUrl/GetCSV', 'DownloadWindowName');
Add the header as follows.
var cd = new System.Net.Mime.ContentDisposition
{
FileName = model.DisplayName + ".xlsx",
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
then return the file as follows
return File(mstream, ".xlsx");
Regarding download prompt. If you mean a prompt where it asks where to save the file, then it depends on how the user has set it up in their browser settings. For example in chrome, users can choose not to get a prompt when downloading files and have it downloaded to a pre specified location like the download folder.
http://malektips.com/google-chrome-prompt-download-file.html#.VM-DbFWsUm8

Rotativa BuildPdf is working on local computer but not on production server

I am using Rotativa to generate a pdf from a view I have created. Locally this works fine, the pdf is stored on my local computer and the email functiont then attaches and sends the file. But when I release it on our server, it basically breaks at this part:
var binary = pdf.BuildPdf(this.ControllerContext);
The website takes ages to load and then finally just says
Sorry, an error occurred while processing your request.
What i did to test this was to redirect to the actual view which will be generated in a pdf until this error was shown. I thought the issue was that the website does not have any write rights but could create directories in the required folder up until the above part mentioned.
What can I do to solve this?
Here is my full section of code for this part:
string Switches = string.Format("--print-media-type --header-html {0} --footer-html {1}", Url.Action("Header", "Home", new { area = "" }, "http"), Url.Action("Footer", "Home", new { area = "" }, "http"));
var fileName = ReportName+objScor.Name+"_"+objScor.Surname + DateTime.Now.ToString("dd MMM yyyy HHmmss") + ".pdf";
var filePath =(#"C:\\PDFReport\\" + fileName);
if (!System.IO.File.Exists(#"C:\\PDFReport\\"))
{
Directory.CreateDirectory(#"C:\\PDFReport\\");
}
var pdf = new Rotativa.ViewAsPdf("Report", report)
{
FileName = fileName,
CustomSwitches = Switches
};
var binary = pdf.BuildPdf(this.ControllerContext);
Thanks in advance.

C# Open Url and download a file, the last part of the file name changes

I want to download a file from an URL, the file name is updated frequently
For E.g.: filename_Date.zip where date changes.
Below is the Query I used
WebClient webClient = new WebClient();
webClient.DownloadFile("http://nppes.viva-it.com/NPPES_Deactivated_NPI_Report_081214.zip", #"C:\Users\gnanasem\Documents\NPIMatcher\NPI.zip");
Landing Page of the URL: http://nppes.viva-it.com/NPI_Files.html
Here you can see multiple files and I want to download the first one.
One way of doing this is to:
Get the HTML of the webpage
Find the URLs on the webpage using RegEx
Find the first URL containing the relevant text, in your case "Deactivated"
Download the file
I got it working like this:
using (var webClient = new WebClient())
{
var websiteHtml = webClient.DownloadString("http://nppes.viva-it.com/NPI_Files.html");
var urlPattern = "href\\s*=\\s*(?:[\"'](?<1>[^\"']*)[\"']|(?<1>\\S+))";
Match match = Regex.Match(websiteHtml, urlPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled, TimeSpan.FromSeconds(1));
var urlToDownload = string.Empty;
while (match.Success)
{
var urlFound = match.Groups[1].Value;
if (urlFound.ToLower().Contains("deactivated"))
{
urlToDownload = urlFound;
break;
}
match = match.NextMatch();
}
webClient.DownloadFile(urlToDownload, #"C:\Users\gnanasem\Documents\NPIMatcher\NPI.zip");
}

Resources