MVC5 File Upload and Display - asp.net-mvc-5

I am currently having an issue with an MVC application that uploads a image to a file server.
public ActionResult UploadFile(HttpPostedFileBase file, string newFileName)
{
try
{
if (file.ContentLength > 0)
{
Bitmap bm = new Bitmap(file.InputStream);
Bitmap final = new Bitmap(bm, 150, 150);
final.SetResolution(72.0F, 72.0F);
string _FileName = newFileName + ".jpg";
string _path = Path.Combine(ConfigurationManager.AppSettings["imageDirectory"], _FileName);
final.Save(_path,System.Drawing.Imaging.ImageFormat.Jpeg);
}
ViewBag.Message = "File Uploaded Successfully!!";
return RedirectToAction("Index");
}
catch
{
ViewBag.Message = "File upload failed!!";
return RedirectToAction("Error");
}
}
So the user chooses a file and uploads it to the to the Windows share. This code works on my machine using IISExpress and on our Test server. When deployed to our Production server, it appears to be working in that it redirects to Index but the file never changes on the File Server.
IISExpress, the Test server, and the Production Server all point to the same file directory too.
Another issue I ran into while troubleshooting this is that the image from the file server does not display when using the FQDN of the application. So http://[appName].[domain].[com] cannot display pictures, but http://[appName] does display the image. Just another weird issue, that did not show up in testing at all.

Here is the problem and solution;
If it works on your development system then the problem is that you did not give readwrite access to app_data folder. HttpPostedFileBase always upload file temporarily into App_Store and its from there that your Save() method takes the file from. If you don't have App_Data folder, create it. You must give full ReadWrite access to IIS_USERS on your server

Related

Need help to develop simple Sharepoint 2013 app to upload excel files to a library

I spun up a new windows 2012 Server R2, installed Sharepoint 2013, and Visual Studio 2019 with the Office/Sharepoint dev options on an old Dell server. I'm trying to write and debug an app I found on the web to upload excel files from a shared drive to a sharepoint document library. I'm at the point where everytime I try to run this app, I get an error stating:
The Web application at http://tcaserver01/my/MPR could not be found.
Verify that you have typed the URL correctly. If the URL should be
serving existing content, the system administrator may need to add a
new request URL mapping to the intended application.
I just need a bit of hand-holding to get things properly configured I think. However, when I put in the url in a web browser, it shows the empty library fine.
using System;
using System.IO;
using Microsoft.SharePoint;
namespace SPTest2
{
class Program
{
[STAThread]
static int Main(string[] args)
{
String site = "http://tcaserver01/my/MPR"; //URL of SharePoint site
String library = "Review_Workbooks"; //Library Name
String filePath = #"S:\MPR\MPR Template.xlsx"; //Entire path of file to upload
try
{
using (SPSite spSite = new SPSite(site))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
//Check if file exists in specified path
if (!System.IO.File.Exists(filePath))
Console.WriteLine("Error - Specified file not found.");
//Get handle of library
SPFolder spLibrary = spWeb.Folders[library];
//Extract file name (file will be uploaded with this name)
String fileName = System.IO.Path.GetFileName(filePath);
//Read file for uploading
FileStream fileStream = File.OpenRead(filePath);
//Replace existing file
Boolean replaceExistingFile = true;
//Upload document to library
SPFile spfile = spLibrary.Files.Add(fileName, fileStream, replaceExistingFile);
spfile.CheckIn("file uploaded via code");
spLibrary.Update();
}
}
Console.WriteLine("File uploaded successfully !!");
Console.ReadLine();
}
catch (Exception exp)
{
Console.WriteLine("Error uploading file - " + exp.Message);
Console.ReadLine();
}
return 0;
}
}
}
Well, it seems when I logged in as the Sharepoint admin user account, I was able to move further in the app, successfully opening up the Sharepoint site. So, when I was logged in as myself, I must not have had the appropriate permissions to open the site. So, this question should be closed as I can now get past what was blocking me. Thanks for anyone who may have read this question already!

.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.

Azure and File.CreateText: FileNotFoundException: Could not find file

I have a simple .Net Core MVC web application that I deploy to Azure. In the application, I am creating a little text file called "test.txt" using File.CreateText(). This works fine on my local PC, but when I deploy it to Azure, I get a strange message: "Could not find file 'D:\home\site\wwwroot\wwwroot\test.txt'."
Indeed, the file does not exist--that's why I'm creating it. Also, it appears someone else on SO is having a similar problem: FileNotFoundException when using System.IO.Directory.CreateDirectory()
Do I not have write permissions? Why is Azure not letting me create the file?
Code (in Startup.cs):
public void Configure(IApplicationBuilder app, IHostingEnvironment env){
using (var sw = File.CreateText(env.WebRootPath + "/test.txt")) { }
}
Screenshot of error:
I found the reason for this error shortly after posting this question, but forgot to post the answer:
It turns out that when you deploy to Azure, your site runs from a temporary directory, which gets wiped and re-created every time you deploy. Because of this, Azure disables the creation and editing of files in the app's directory, since they're just going to get wiped upon your next deployment (it would be nice if the error message Azure displayed was a little more informative).
Therefore, the way to create and edit files on your Azure app and have them persist across deployments is to use one of the following:
Database BLOB storage (simply store your files as byte arrays in a database. doesn't cost any money if you are already using a database)
Azure BLOB storage (store your files to a special cloud on Azure. costs money)
I read this on some site shortly after posting this question but I can't remember where, so I apologize for not having the source.
The best way is use the blog storage AZURE to do this. But you can try save in the root this way:
static void Main(string[] args)
{
// Create a string with a line of text.
string text = "First line" + Environment.NewLine;
// Set a variable to the Documents path.
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Write the text to a new file named "WriteFile.txt".
File.WriteAllText(Path.Combine(docPath, "WriteFile.txt"), text);
// Create a string array with the additional lines of text
string[] lines = { "New line 1", "New line 2" };
// Append new lines of text to the file
File.AppendAllLines(Path.Combine(docPath, "WriteFile.txt"), lines);
}
Reference: https://learn.microsoft.com/pt-br/dotnet/standard/io/how-to-write-text-to-a-file

How to store file into inetpub\wwwroot instead of local machine folder on UWP application

I am currently developing a UWP application for my school project and one of the pages allows the user to take a picture of themselves. I created the feature by following this tutorial: CameraStarterKit
For now I am storing the pictures taken on my desktop's picture folder. But the requirement of my project is to store the pictures taken in a folder called "Photos" under inetpub\wwwroot.
I dont really understand what wwwroot or IIS is... hence, I have no idea how I should modify my codes and store them into the folder.
Here are my codes for storing on my local desktop:
private async Task TakePhotoAsync()
{
idleTimer.Stop();
idleTimer.Start();
var stream = new InMemoryRandomAccessStream();
//MediaPlayer mediaPlayer = new MediaPlayer();
//mediaPlayer.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/camera-shutter-click-03.mp3"));
//mediaPlayer.Play();
Debug.WriteLine("Taking photo...");
await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
try
{
var file = await _captureFolder.CreateFileAsync("NYPVisitPhoto.jpg", CreationCollisionOption.GenerateUniqueName);
Debug.WriteLine("Photo taken! Saving to " + file.Path);
var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());
await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
Debug.WriteLine("Photo saved!");
}
catch (Exception ex)
{
// File I/O errors are reported as exceptions
Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
}
}
For the storing of the files:
private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation)
{
using (var inputStream = stream)
{
var decoder = await BitmapDecoder.CreateAsync(inputStream);
using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };
await encoder.BitmapProperties.SetPropertiesAsync(properties);
await encoder.FlushAsync();
}
}
}
I would add an answer since there are tricky things about this requirement.
The first is the app can only access a few folders, inetpub is not one of them.
Using brokered Windows runtime component (I would suggest using FullTrustProcessLauncher, which is much simpler to develop and deploy) can enable UWP apps access folders in the same way as the traditional desktop applications do.
While this works for an ordinary folder, the inetpub folder, however, is different that it requires Administrators Privileges to write to, unless you turn UAC off.
The desktop component launched by the app does not have the adequate privileges to write to that folder, either.
So it think an alternative way would be setting up a virtual directory in IIS manager that maps to a folder in the public Pictures library, and the app saves picture to that folder.
From the website’s perspective, a virtual directory is the same as a real folder under inetpub, what differs is the access permissions.
Kennyzx is right here that you cannot access inetpub folder through your UWP application due to permissions.
But if your application fulfills following criteria then you can use Brokered Windows Component(a component within your app) to copy your file to any location in the system.
Your application is a LOB application
You are only targetting desktop devices(I assume this will be true because of your requirement)
You are using side-loading for your app installation and distribution.
If all three are Yes then use Brokered Windows Component for UWP, it's not a small thing that can be showed here on SO using an example. So give worth a try reading and implementing it.

Why am I getting an UnauthorizedAccessException when trying to write a file to LocalStorage in Azure

I have created a local storage in my web role called "MyTestCache" as so in my
ServiceDefinition.csdef file. But when ever I call the System.IO.File.WriteAllBytes method I get a UnauthorizedAccess exception. Does anyone know what would be causing this? I dont get this when creating the directory in the code below, only when writing. I am using SDK 1.3.
private void SaveFileToLocalStorage(byte[] remoteFile, string filePath)
{
try
{
LocalResource myIO = RoleEnvironment.GetLocalResource("MyTestCache");
// Creates directory if it doesn't exist (ie the first time)
if (!Directory.Exists(myIO.RootPath + "/thumbnails"))
{
Directory.CreateDirectory(myIO.RootPath + "/thumbnails");
}
string PathToFile = Path.Combine(myIO.RootPath + "/thumbnails", filePath);
var path = filePath.Split(Char.Parse("/"));
// Creates the directory for the content item (GUID)
if (!Directory.Exists(Path.Combine(myIO.RootPath + "/thumbnails", path[0])))
{
Directory.CreateDirectory(Path.Combine(myIO.RootPath + "/thumbnails", path[0]));
}
// Writes the file to local storage.
File.WriteAllBytes(PathToFile, remoteFile);
}
catch (Exception ex)
{
// do some exception handling
return;
}
}
Check ACLs. In SDK 1.3 by default web roles are started in full IIS worker process, using Network Service as identity of application pool. Make sure Network Service account has permissions to execute operations you expect. In your case you are trying to create a sub-directory, so most probably you need at least Write permission. If your role also modifies ACLs on this directory, you need to grant Full access to this directory.

Resources