I am creating a Windows Form Application to insert data into MSSQL but also upload a file of user's choosing to SharePoint.
I tried to use the below code, however I have some serious problem due to Multi-Factor Authentication (MFA) not being lifted for my service account. IT is very firm on this matter.
string SiteUrl = "https://company.sharepoint.com/sites/mySite";
string DocumentLibrary = "Documents";
string FileName = #chkAttach1.Text.ToString();
string CustomerFolder = "Application Test";
string Username = "testuser";
string Password = "123";
foreach (char c in Password)
{ securePassword.AppendChar(c); }
var olCred = new SharePointOnlineCredentials(UserName, securePassword);
using (ClientContext cContext = new ClientContext(SiteUrl))
{
cContext.Credentials = olCred;
Web web = cContext.Web;
FileCreationInformation newFile = new FileCreationInformation();
byte[] FileContent = System.IO.File.ReadAllBytes(FileName);
newFile.ContentStream = new System.IO.MemoryStream(FileContent);
newFile.Url = System.IO.Path.GetFileName(FileName);
Microsoft.SharePoint.Client.List docLib = web.Lists.GetByTitle(DocumentLibrary);
Microsoft.SharePoint.Client.Folder uplFold = docLib.RootFolder.Folders.Add(CustomerFolder);
uplFold.Update();
Microsoft.SharePoint.Client.File uplFile = uplFold.Files.Add(newFile);
cContext.Load(docLib);
cContext.Load(uplFile);
cContext.ExecuteQuery();
}
So obviously the above is not working.
Speaking to a fellow from IT, he advised me to use API, but I have difficulties in finding a sample code online to upload a file to SharePoint using the user's current credentials.
Any advice?
Related
I'd like to download a file from Sharepoint online using a non-interactive C# program.
Recently MFA was enabled, and since then I'm unable to get the files with any user through my code, though I can still access it through the portal web access.
At first I have tried using the following, getting an The sign-in name or password does not match one in the Microsoft account system. when executing the query (using either username#mydomain.com or username#mydomain.onmicrosoft.com)
var ctx = new ClientContext(Properties.Settings.Default.SharepointBaseUrl)
{
Credentials = credentials,
};
var web = ctx.Web;
ctx.Load(web);
try
{
ctx.ExecuteQuery();
}
catch (Exception ex)
{
return string.Empty;
}
var fileUrl = $"{web.ServerRelativeUrl}/{file.Location}";
var fi = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileUrl);
Then I generated an AppId and AppSecret, and used the following code:
var authenticationManager = new OfficeDevPnP.Core.AuthenticationManager();
var ctx = authenticationManager.GetAppOnlyAuthenticatedContext(
"https://mydomain.sharepoint.com/sites/defaultcollection/MyDir",
appId,
appSecret);
But got a 401 unauthorized when trying to access the file with SharePoint.Client.File.OpenBinaryDirect(ctx, fileUrl);
Use File.OpenBinaryStream() instead like this:
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core;
using System.IO;
string siteUrl = "https://tenant.sharepoint.com/";
using (var ctx = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, "yourappid", "yourappsecret"))
{
ctx.Load(ctx.Web, p => p.Title);
ctx.ExecuteQuery();
Console.WriteLine(ctx.Web.Title);
Microsoft.SharePoint.Client.File file = ctx.Web.GetFileByUrl("https://tenant.sharepoint.com/Shared%20Documents/test.txt");
ctx.Load(file);
ctx.ExecuteQuery();
string filepath = #"C:\temp\" + file.Name;
Microsoft.SharePoint.Client.ClientResult<Stream> mstream = file.OpenBinaryStream();
ctx.ExecuteQuery();
using (var fileStream = new System.IO.FileStream(filepath, System.IO.FileMode.Create))
{
mstream.Value.CopyTo(fileStream);
}
};
string urlSite = "https://intranet.site.dk";
string user = "myuser#vid.net.local";
string pwd = "mypass";
using (ClientContext clientContext = new ClientContext(urlSite))
{
SecureString passWord = new SecureString();
foreach (char c in pwd.ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(user, passWord);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
Console.WriteLine(web.Title);
Console.ReadLine();
}
I'm trying to login on a sharepoint web site.
This code is what i could come up with.
No matter what i do, i'll get the Not authorized (401)
But if i type the exactly same in my browser, it's working fine..
Can anyone see the problem?
make your code simple ;) use this codes:
using (ClientContext clientContext = new ClientContext(urlSite))
{
clientContext.Credentials = new NetworkCredential(user, pwd, domain);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
Console.WriteLine(web.Title);
Console.ReadLine();
}
I have a byte[] data and I want to upload it to sharepoint site using c#. I also want to pass credentials for it. Can anyone please guide me.
The code I tried is:
Uri destUri = new Uri("http://test.net/excel/docs/Forms/AllItems.aspx/");
WebRequest req = WebRequest.Create(destUri);
req.Method = "PUT";
req.Credentials = CredentialCache.DefaultCredentials;
using (req.GetRequestStream())
{
string destFilename = #"\\test.net\excel\docs\501.xls";
byte[] data = new byte[10];
System.IO.File.WriteAllBytes(destFilename, data);
}
ERROR:
Access Denied
Current user should have add permissions on this library
public void UploadFileToDocmentLibrary(Byte[] contentArray)
{
using (SPSite sharePointtopLevelSite = new SPSite("http://localhost"))
{
SPWeb websiteCollection = sharePointtopLevelSite.AllWebs["webName"];
websiteCollection.AllowUnsafeUpdates = true;
websiteCollection.Lists.IncludeRootFolder = true;
SPList docLibrary = websiteCollection.Lists["listName"];
SPFile file = websiteCollection.Files.Add(websiteCollection.Url.ToString() + "/" + docLibrary.Title.ToString() + "/" + "fileName.ext", contentArray);
file.Update();
}
}
If user without permissions should do it, use RunWithElevatedPrivileges statement
If I understood your requirements properly, you need to upload file into SharePoint On-Premise, right? There are several options on how to accomplish it.
Send file via HTTP POST using .NET
At least the following components could be utilized for that purpose:
HttpWebRequest
WebClient
HttpClient
Example
The example demonstrates how to upload file using WebClient.UploadFile Method:
public static void UploadFile(Uri targeUri, ICredentials credentials, string fileName)
{
using (var client = new WebClient())
{
client.Credentials = credentials;
//client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
var targetFileUri = targeUri + "/" + Path.GetFileName(fileName);
client.UploadFile(targetFileUri, "PUT", fileName);
}
}
Usage
var filePath = #"C:\Documents\SharePoint User Guide.docx";
var credentials = new NetworkCredential(userName, password, domain);
UploadFile(new Uri("https://contoso.sharepoint.com/documents"),credentials, filePath);
Using Microsoft SharePoint Server Object Model
using (var site = new SPSite(url))
{
using (var web = site.OpenWeb())
{
var list = web.Lists.TryGetList(listTitle);
var targetFolder = list.RootFolder;
var fileContent = System.IO.File.ReadAllBytes(fileName);
var fileUrl = Path.GetFileName(fileName);
targetFolder.Files.Add(fileUrl, fileContent);
}
}
Using Microsoft SharePoint Client Object Model
SharePoint 2010 Client Components SDK
SharePoint 2013 Client Components SDK
How to upload a file to a SharePoint site using File.SaveBinaryDirect Method
using (var ctx = new ClientContext(url))
{
ctx.Credentials = new NetworkCredential(userName, password, domain);
using (var fs = new FileStream(fileName, FileMode.Open))
{
var fi = new FileInfo(fileName);
var list = ctx.Web.Lists.GetByTitle(listTitle);
ctx.Load(list.RootFolder);
ctx.ExecuteQuery();
var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, fileUrl, fs, true);
}
}
Using SharePoint Web Services
How to upload file using Copy Web Service:
var webUri = new Uri("http://contoso.sharepoint.com");
string sourceUrl = #"C:\Documents\SharePoint User Guide.docx";
string destinationUrl = webUri + "/documents/SharePoint User Guide 2013.docx";
var fieldInfo = new FieldInformation();
FieldInformation[] fieldInfos = { fieldInfo };
CopyResult[] result;
using (var proxyCopy = new Copy())
{
proxyCopy.Url = webUri + "/_vti_bin/Copy.asmx";
proxyCopy.Credentials= new NetworkCredential(userName, password, domain);
var fileContent = System.IO.File.ReadAllBytes(sourceUrl);
proxyCopy.CopyIntoItems(sourceUrl, new[] { destinationUrl }, fieldInfos, fileContent, out result);
}
string remoteUri = "http://www.contoso.com/library/homepage/images/";
string fileName = "ms-banner.gif", myStringWebResource = null;
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
// Concatenate the domain with the Web resource filename.
myStringWebResource = remoteUri + fileName;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource,fileName);
Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource);
Console.WriteLine("\nDownloaded file saved in the following file system folder:\n\t" + Application.StartupPath);
I'am Using this code from MSDN Web Site
But I have coming across the error: 403 forbidden
Can someone Help me Put this working ?
I was facing the same issue and tried the answer suggested by Vadim Gremyachev. However, it still kept giving 403 error. I added two extra headers to force form based authentication like below:
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add("User-Agent: Other");
After this it started working. So the full code goes like below:
const string username = "username#tenant.onmicrosoft.com";
const string password = "password";
const string url = "https://tenant.sharepoint.com/";
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
var credentials = new SharePointOnlineCredentials(username, securedPassword);
DownloadFile(url,credentials,"/Shared Documents/Report.xslx");
private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl)
{
using(var client = new WebClient())
{
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add("User-Agent: Other");
client.Credentials = credentials;
client.DownloadFile(webUrl, fileRelativeUrl);
}
}
This error occurs since the request is not authenticated. In order to access resource in Office/SharePoint Online you could utilize SharePointOnlineCredentials class from SharePoint Server 2013 Client Components SDK (user credentials flow).
The following example demonstrates how to download a file from SPO:
const string username = "username#tenant.onmicrosoft.com";
const string password = "password";
const string url = "https://tenant.sharepoint.com/";
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
var credentials = new SharePointOnlineCredentials(username, securedPassword);
DownloadFile(url,credentials,"/Shared Documents/Report.xslx");
private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl)
{
using(var client = new WebClient())
{
client.Credentials = credentials;
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.DownloadFile(webUrl, fileRelativeUrl);
}
}
I am using the SSRS WinForms client control to display reports in an app. User's behind proxies are getting a 407 (proxy authentication) error. How do I specify proxy settings for the request? i.e. proxy server, username & password. I was expecting it to be similar to the HttpRequest and WebProxy.
This is helpful C# Connecting Through Proxy however I need to specify proxy settings on a per SSRS request basis.
Any ideas?
Thanks.
You can specify the proxy settings by using reporting web services.
Add the reporting web reference to your project. The URL of the web service is :
http://servername/ReportServer/ReportExecution2005.asmx
In the code calling the web service.
byte[] report = null;
//create an instance of the reporting service web reference
var reportReference = new ReportExecutionService();
<strong>//Set your proxy settings
reportReference.Proxy = new WebProxy("address:port");
//create a credential that will be used to authenticate again the
reporting services
var credential = new NetworkCredential("username",
"password", "domainName");
reportReference.Credentials =
credential;
reportReference.PreAuthenticate =
true;
//the virtual path to the report
string virtualPath = "/Folder/ReportName";
//Specify the device info
string deviceInfo =
"<DeviceInfo><Toolbar>False</Toolbar><Parameters>False</Parameters><DocMap>True</DocMap><Zoom>100</Zoom></DeviceInfo>";
//Create an array of parameters, for example our report needs 2 parameters
var parameters = new ParameterValue[2];
//Specify the value for the parameter
var startDateParameter = new ParameterValue();
startDateParameter.Name = "StartDate";
startDateParameter.Value = "01/01/2008";
parameters[0] = startDateParameter;
var endDateParameter = new ParameterValue();
endDateParameter.Name = "EndDate";
endDateParameter.Value = "31/12/2008";
parameters[1] = endDateParameter;
//Create variables for the remainder of the parameters
string extension = string.Empty;
ExecutionHeader executionHeader = null;
reportReference.ExecutionHeaderValue =
executionHeader;
reportReference.LoadReport(virtualPath,
null);
reportReference.SetExecutionParameters(parameters,
"en-AU");
try
{
//Execute the report
string[] streamIDs;
Warning[] warning = null;
string encoding;
string mimeType;
string format = "PDF";
<strong>//Execute the report
report = reportReference.Render(format,
deviceInfo, out extension, out
mimeType, out encoding,
out warning, out streamIDs);
using (var fileStream = new FileStream("myReport.PDF", FileMode.Create))
{
fileStream.Write(report, 0,
report.Length);
fileStream.Close();
}
> Process.Start("myReport.pdf");
}
catch (SoapException exception)
{
}