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

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!

Related

How to fix issue "IOException: Read-only file system" ASP.NET Core in Azure App Service with linux os?

I deploy a web app based on ASP.NET Core to Azure with Visual Studio 2019. Everything is ok except the upload images feature that actually accesses to folder/file. Thanks a lot for your suggestions.
public string UploadFile(IFormFile image)
{
if (image == null) return null;
try
{
string fileName = Guid.NewGuid().ToString() + image.FileName;
string filePath = Path.Combine(_hostingEnvironment.WebRootPath, "Images", "ProductImages", fileName);
var extension = new[] { "image/jpg", "image/png", "image/jpeg" };
if (!extension.Contains(image.ContentType))
return null;
using (FileStream file = new FileStream(filePath, FileMode.Create))
{
image.CopyTo(file);
}
return fileName;
}
catch (Exception ex)
{
throw;
}
}
Error:
An unhandled exception occurred while processing the request.
IOException: Read-only file system
I have test your code and found it works fine in local. So I try to deploy this app to azure webapp (linux platform).
And also encountered this situation. So I check the application settings in azure portal.
Solution
Delete WEBSITES_RUN_FROM_PACKAGE option at application settings in azure portal.
Why and How to solve it
Maybe there are some settings in publishsettings file cause the issue, you can download the publishsettings from azure portal.
And import into your IDE (like vs2019), or you can try to use another pc to deploy the app to prevent generate WEBSITES_RUN_FROM_PACKAGE.
add FileAccess Permission
FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);

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.

MVC5 File Upload and Display

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

Sharepoint Object Model applicaton cannot run outside of WSS server

I create a C# console application using Microsoft.SharePoint object model VS WSS extensions on Windows Server 2003. The application is supposed to iterate WSS3.0 sites looking for all available lists. It runs just fine on the server. But if I try to run the exe from another computer on the network, the application crashes instantly on SPSite siteCollection = new SPSite("http://devsharepoint);
Even my try and catch doesn't help as catch is not executed.
Is it intended to run the Sharepoint object model applications only on machines with VS SharePoint extensions installed?
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace ConsoleApplicationWSSobjectModel
{
class Program
{
static void Main(string[] args)
{
string url = "http://sharepoint";
Console.WriteLine("Trying to access: " + url);
try
{
SPSite siteCollection = new SPSite(url);//"http://Server_Name");
SPWebCollection sites = siteCollection.AllWebs;
foreach (SPWeb site in sites)
{
SPListCollection lists = site.Lists;
Console.WriteLine("Site: " + site.Name + " Lists: " + lists.Count.ToString());
}
Console.WriteLine("Press ENTER to continue");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
You cannot use the SP object model ”outside sharepoint” you will have to use web services (or if your go with sharepoint 2010 you can use the new client object model)
Anything built with the SharePoint object model can only run on a server with SharePoint installed. There is however no dependency on the VS extensions.
You can use Client Object Model using C# or VB as your language. Add references Microsoft.sharepoint.client.dll and Microsoft.sharepoint.client.Runtime.dll it can be found under 14(SP2010) or 15(SP2013) hive ISAPI folder.

Upload a file to SharePoint through the built-in web services

What is the best way to upload a file to a Document Library on a SharePoint server through the built-in web services that version WSS 3.0 exposes?
Following the two initial answers...
We definitely need to use the Web Service layer as we will be making these calls from remote client applications.
The WebDAV method would work for us, but we would prefer to be consistent with the web service integration method.
There is additionally a web service to upload files, painful but works all the time.
Are you referring to the “Copy” service?
We have been successful with this service’s CopyIntoItems method. Would this be the recommended way to upload a file to Document Libraries using only the WSS web service API?
I have posted our code as a suggested answer.
Example of using the WSS "Copy" Web service to upload a document to a library...
public static void UploadFile2007(string destinationUrl, byte[] fileData)
{
// List of desination Urls, Just one in this example.
string[] destinationUrls = { Uri.EscapeUriString(destinationUrl) };
// Empty Field Information. This can be populated but not for this example.
SharePoint2007CopyService.FieldInformation information = new
SharePoint2007CopyService.FieldInformation();
SharePoint2007CopyService.FieldInformation[] info = { information };
// To receive the result Xml.
SharePoint2007CopyService.CopyResult[] result;
// Create the Copy web service instance configured from the web.config file.
SharePoint2007CopyService.CopySoapClient
CopyService2007 = new CopySoapClient("CopySoap");
CopyService2007.ClientCredentials.Windows.ClientCredential =
CredentialCache.DefaultNetworkCredentials;
CopyService2007.ClientCredentials.Windows.AllowedImpersonationLevel =
System.Security.Principal.TokenImpersonationLevel.Delegation;
CopyService2007.CopyIntoItems(destinationUrl, destinationUrls, info, fileData, out result);
if (result[0].ErrorCode != SharePoint2007CopyService.CopyErrorCode.Success)
{
// ...
}
}
Another option is to use plain ol' HTTP PUT:
WebClient webclient = new WebClient();
webclient.Credentials = new NetworkCredential(_userName, _password, _domain);
webclient.UploadFile(remoteFileURL, "PUT", FilePath);
webclient.Dispose();
Where remoteFileURL points to your SharePoint document library...
There are a couple of things to consider:
Copy.CopyIntoItems needs the document to be already present at some server. The document is passed as a parameter of the webservice call, which will limit how large the document can be. (See http://social.msdn.microsoft.com/Forums/en-AU/sharepointdevelopment/thread/e4e00092-b312-4d4c-a0d2-1cfc2beb9a6c)
the 'http put' method (ie webdav...) will only put the document in the library, but not set field values
to update field values you can call Lists.UpdateListItem after the 'http put'
document libraries can have directories, you can make them with 'http mkcol'
you may want to check in files with Lists.CheckInFile
you can also create a custom webservice that uses the SPxxx .Net API, but that new webservice will have to be installed on the server. It could save trips to the server.
public static void UploadFile(byte[] fileData) {
var copy = new Copy {
Url = "http://servername/sitename/_vti_bin/copy.asmx",
UseDefaultCredentials = true
};
string destinationUrl = "http://servername/sitename/doclibrary/filename";
string[] destinationUrls = {destinationUrl};
var info1 = new FieldInformation
{
DisplayName = "Title",
InternalName = "Title",
Type = FieldType.Text,
Value = "New Title"
};
FieldInformation[] info = {info1};
var copyResult = new CopyResult();
CopyResult[] copyResults = {copyResult};
copy.CopyIntoItems(
destinationUrl, destinationUrls, info, fileData, out copyResults);
}
NOTE: Changing the 1st parameter of CopyIntoItems to the file name, Path.GetFileName(destinationUrl), makes the unlink message disappear.
I've had good luck using the DocLibHelper wrapper class described here: http://geek.hubkey.com/2007/10/upload-file-to-sharepoint-document.html
From a colleage at work:
Lazy way: your Windows WebDAV filesystem interface. It is bad as a programmatic solution because it relies on the WindowsClient service running on your OS, and also only works on websites running on port 80. Map a drive to the document library and get with the file copying.
There is additionally a web service to upload files, painful but works all the time.
I believe you are able to upload files via the FrontPage API but I don’t know of anyone who actually uses it.
Not sure on exactly which web service to use, but if you are in a position where you can use the SharePoint .NET API Dlls, then using the SPList and SPLibrary.Items.Add is really easy.

Resources