Examples how to save file from external .Net application to Sharepoint - c#

I need to save files from the existing AngularJS/.NET application to Sharepoint. Most of the examples I see online is when applications reside on Sharepoint itself. How do I save files from outside?
I've been given a user access to our organization's Sharepoint site but no application user passwords. What do I need to request from administrators of SharePoint site to be able to write the code?

We can use CSOM C# code to upload file to SharePoint 2010 document library. We need use an admin user and password to pass the Credentials in the .NET application server.
public static void UploadFile(ClientContext context, string uploadFolderUrl, string uploadFilePath)
{
var fileCreationInfo = new FileCreationInformation
{
Content = System.IO.File.ReadAllBytes(uploadFilePath),
Overwrite = true,
Url = Path.GetFileName(uploadFilePath)
};
var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);
var uploadFile = targetFolder.Files.Add(fileCreationInfo);
context.Load(uploadFile);
context.ExecuteQuery();
}
Usage
var siteUrl="http://sp2010";
var username="admin";
var password="xx";
var domainName="domain1";
using (var ctx = new ClientContext(webUri))
{
ctx.Credentials = new System.Net.NetworkCredential(username, password, domainName);
UploadFile(ctx,"Documents/folder1",#"c:\upload\test.docx");
}
The following article for your reference.
Uploading files using Client Object Model in SharePoint 2010

Related

How to copy a file to a sharepoint site

I have to copy a file on a sharepoint site.
I have seen that the only authentication working is with the AuthenticationManager.
So this works:
var authManager = new AuthenticationManager();
var ctx = authManager.GetWebLoginClientContext(strHexagon);
Web web = ctx.Web;
User user = web.CurrentUser;
ctx.Load(web);
ctx.Load(user);
ctx.ExecuteQuery();
lbxInfo.Items.Add(web.Title);
lbxInfo.Items.Add(user.LoginName);
Now, after having authenticated I need to copy a file to the sharepoint site.
I have seen that there is ctx.Web.SaveFileToLocal but what if I have to copy from local to sharepoint?
Thanks
You can use the OfficeDevPnP.Core library
string str1_Url=... <--- sharepoint site
string str2_FileSource_Full= #"C:\temp\A.txt";
string str3_FileDestination_NameExt="B.txt";
string str4_TopDestination_Folder=... <--- sharepoint site title folder
string str5_TopDestination_SubFolder=... <--- folder e.g. Production
string str6_TopDestination_AllSubFolders=...<--- subfolder e.g. Test
// AuthenticationManager -> ByPasses Multi-Factor Authentication
var authManager = new AuthenticationManager();
var ctx = authManager.GetWebLoginClientContext(str1_Url);
// Web & User definitions
Web web = ctx.Web;
User user = web.CurrentUser;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(str2_FileSource_Full);
// Rename the destination file
newFile.Url = str3_FileDestination_NameExt;
Microsoft.SharePoint.Client.List docs = web.Lists.GetByTitle(str4_TopDestination_Folder);
// Selects a Folder inside the root one
Microsoft.SharePoint.Client.Folder folder = docs.RootFolder.Folders.GetByUrl(str5_TopDestination_SubFolder);
folder.Folders.Add(str6_TopDestination_AllSubFolders);
var targetFolder = folder.Folders.GetByUrl(str6_TopDestination_AllSubFolders);
// Uploads a file to the targetFolder
newFile.Overwrite = true;
Microsoft.SharePoint.Client.File uploadFile = targetFolder.Files.Add(newFile);
// Executes query
ctx.Load(docs);
ctx.Load(uploadFile);
ctx.Load(web);
ctx.Load(user);
ctx.ExecuteQuery();

Send Sharing Link for Sharepoint Folder

I have been battling with this for a few days now... I am using CSCOM to connect to SharePoint. Everything is working fine, creating folders and uploading files. However, I now need to create a shared folder (parent level) link for external users and then initiate the email invite as per the "links giving access" not direct access. I can create and send an anonymous link but this is not what we are after.
string s = "password";
SecureString passWord = new SecureString();
foreach (var c in s)
passWord.AppendChar(c);
string siteURL = "siteurl";
string parentFolder = "parentfolder";
using (Microsoft.SharePoint.Client.ClientContext CContext = new Microsoft.SharePoint.Client.ClientContext(siteURL))
{
CContext.Credentials = new SharePointOnlineCredentials("s-eConnect#nzblood.co.nz",passWord);
var subFolders = CContext.Web.GetFolderByServerRelativeUrl(parentFolder).Folders;
CContext.Load(subFolders);
CContext.ExecuteQuery();
<<create sharing link for parent folder and send email to external user>>>
foreach (var subFolder in subFolders)
{
Console.WriteLine(subFolder.Name.ToString());
}
}
The above code iterates thru the sub folders of the parent, this is me just making sure I am getting the right data. But I can't seem to find anything that allows me to create the sharing link and send to an external user so they get an invite etc...
If I add in the following, it creates an invite but adds the user to the entire site via Direct Access ... not by link to the folder....
var users = new List<UserRoleAssignment>();
users.Add(new UserRoleAssignment()
{
UserId = "rhyndman#altara.net",
Role = Role.View
});
WebSharingManager.UpdateWebSharingInformation(CContext, CContext.Web, users, true, "You've been invited...", true, true);
CContext.ExecuteQuery();
Any help would be appreciated.
Many thanks
You could try to use DocumentSharingManager.UpdateDocumentSharingInfo method to send Sharing Link for Sharepoint Folder: https://learn.microsoft.com/en-us/previous-versions/office/sharepoint-csom/mt143107(v=office.15)
DocumentSharingManager.UpdateDocumentSharingInfo(CContext, folderabsoluteUrl, users, true, true, true, "You've been invited...", true, true);

azure deploy multiple site's instance on demand

I have a website called www.Request.com, when users access this site they will be able to request the creation of a new instance of another website that is already deployed in AZURE with the name www.MyTechnicalApp.com
for example when I access to www.Request.com I will request the creation of MyTechnicalApp for my company called "MyCompany", it's supposed that there is a script that will be executed by request.com website to create automatically www.MyCompany.MyTechnicalApp.com website.
would you please let me know how could I do that?
According to your description, to create a web app on Azure automatically, there are two ways to achieve this.
One: using "Windows Azure Management Libraries", this SDK is a wrapper around "Azure Service Management" API.
First, we need to do authentication with ASM API and we can refer to: Windows Azure Management Librairies : Introduction et authentification, then we will be able to create a website with something like this:
using (var AwsManagement = new Microsoft.WindowsAzure.Management.WebSites.WebSiteManagementClient(azureCredentials))
{
WebSiteCreateParameters parameters = new WebSiteCreateParameters()
{
Name = "myAws",
// this Service Plan must be created before
ServerFarm = "myServiceplan",
};
await AwsManagement.WebSites.CreateAsync("myWebSpace", parameters, CancellationToken.None);
}
Two: We can create a web site by using a POST request that includes the name of the web site and other information in the request body. We can check the code example for azure-sdk-for-net
use this link to get the credentials Authentication in Azure Management Libraries for Java.
https://github.com/Azure/azure-libraries-for-java/blob/master/AUTH.md
The below link helped me to find the answer.
static void Main(string[] args)
{
try
{
var resourceGroupName = "your ressource group name";
var subId = "64da6c..-.......................88d";
var appId = "eafeb071-3a70-40f6-9e7c-fb96a6c4eabc";
var appSecret = "YNlNU...........................=";
var tenantId = "c5935337-......................19";
var environment = AzureEnvironment.AzureGlobalCloud;
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(appId, appSecret, tenantId, AzureEnvironment.AzureGlobalCloud);
var azure = Microsoft.Azure.Management.Fluent.Azure
.Configure()
.Authenticate(credentials)
.WithSubscription(subId);
azure.AppServices.WebApps.Inner.CreateOrUpdateHostNameBindingWithHttpMessagesAsync(resourceGroupName, "WebSiteName", "SubDomainName",
new HostNameBindingInner(
azureResourceType: AzureResourceType.Website,
hostNameType: HostNameType.Verified,
customHostNameDnsRecordType: CustomHostNameDnsRecordType.CName)).Wait();
}
catch (Exception ex)
{
}
}

How to upload a file in Sharepoint 2010 using c# console

Is there a way to automatically upload a file in Sharepoint 2010 using c#? We have no administrative control on the Sharepoint server. We just need to write a program that will upload a local file to a designated sharepoint library. The program will run on our server which in no way affiliated with the sharepoint server.
The following options could be considered for uploading the file into SharePoint via CSOM.
Prerequisites: SharePoint Foundation 2010 Client Object Model Redistributable
Using FileCollection.Add method
FileCollection.Add method adds a file to the collection based on provided file creation information
public static void UploadFile(ClientContext context, string uploadFolderUrl, string uploadFilePath)
{
var fileCreationInfo = new FileCreationInformation
{
Content = System.IO.File.ReadAllBytes(uploadFilePath),
Overwrite = true,
Url = Path.GetFileName(uploadFilePath)
};
var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);
var uploadFile = targetFolder.Files.Add(fileCreationInfo);
context.Load(uploadFile);
context.ExecuteQuery();
}
Usage
using (var ctx = new ClientContext(webUri))
{
ctx.Credentials = credentials;
UploadFile(ctx,"Documents/Orders",#"c:\upload\user guide.docx");
}
where Orders is a folder in Documents library
According to Uploading files using Client Object Model in SharePoint 2010:
The above code might fail throwing a (400) Bad Request error depending
on the file size.
Using File.SaveBinaryDirect method
File.SaveBinaryDirect method - uploads the specified file to a SharePoint site without requiring an ExecuteQuery() method call.
public static void UploadFile(ClientContext context, string folderUrl, string uploadFilePath)
{
using (var fs = new FileStream(uploadFilePath, FileMode.Open))
{
var fileName = Path.GetFileName(uploadFilePath);
var fileUrl = String.Format("{0}/{1}", folderUrl, fileName);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
}
}
Usage
using (var ctx = new ClientContext(webUri))
{
ctx.Credentials = credentials;
UploadFile(ctx,"/News/Documents/Orders",#"c:\upload\user guide.docx");
}
where Orders is a folder in Documents library located on web site News.
FolderUrl format: /<web url>/<list url>/<folder url>

Upload document to Sharepoint 2013 Online using webservices

I have a client who is implementing customer portals in Sharepoint 2013 Online. The current program distributes documents to the customers by mail. Now we have to upload the documents to the customer portal.
I try to use the copy webservice in sharepoint. I created a test project and added the webservice as Web Reference and wrote the following testcode:
static void Main(string[] args)
{
string baseUrl = "https://mycustomer.sharepoint.com/sites/";
string customer = "customerportalname";
string serviceUrl = "/_vti_bin/copy.asmx";
string destinationDirectory = "/folder/";
string fileName = "uploaded.xml";
string username = "username#outlook.com";
string password = "password";
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<fiets><onderdeel>voorwiel</onderdeel><onderdeel>achterwiel</onderdeel><onderdeel>trappers</onderdeel><onderdeel>stuur</onderdeel><onderdeel>frame</onderdeel></fiets>");
byte[] xmlByteArray;
using (MemoryStream memoryStream = new MemoryStream())
{
xmlDocument.Save(memoryStream);
xmlByteArray = memoryStream.ToArray();
}
string destinationUrl = string.Format("{0}{1}{2}{3}", baseUrl, customer, destinationDirectory, fileName);
string[] destinationUrlArray = new string[] { destinationUrl };
FieldInformation fieldInfo = new FieldInformation();
FieldInformation[] fields = { fieldInfo };
CopyResult[] resultsArray;
using (Copy copyService = new Copy())
{
copyService.PreAuthenticate = true;
copyService.Credentials = new NetworkCredential(username, password);
copyService.Url = string.Format("{0}{1}", baseUrl, serviceUrl);
copyService.Timeout = 600000;
uint documentId = copyService.CopyIntoItems(destinationUrl , destinationUrlArray, fields, xmlByteArray, out resultsArray);
}
}
When I execute the code I recieve the following error:
The request failed with the error message:
--
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
--
It looks like I'm not authenticated and get redirected. The credentials however are correct.
Does anyone have an idea? Thanks in advance!
UPDATE
To be able to connect to SharePoint 2013 Online you have to attach the Office 365 authentication cookies as explained in this post.
My problem however is that there is also an ADFS involved. How can I autheticate against the ADFS?
This error most probably occurs due to incorrect authentication mode.
Since SharePoint Online (SPO) uses claims-based authentication, NetworkCredential Class can not be utilized for authentication in SPO.
In order to perform the authentication against the ADFS in SPO you could utilize SharePointOnlineCredentials class from SharePoint Online Client Components SDK.
How to authenticate SharePoint Web Services in SharePoint Online (SPO)
The following example demonstrates how to retrieve authentication cookies:
private static CookieContainer GetAuthCookies(Uri webUri, string userName, string password)
{
var securePassword = new SecureString();
foreach (var c in password) { securePassword.AppendChar(c); }
var credentials = new SharePointOnlineCredentials(userName, securePassword);
var authCookie = credentials.GetAuthenticationCookie(webUri);
var cookieContainer = new CookieContainer();
cookieContainer.SetCookies(webUri, authCookie);
return cookieContainer;
}
Example
string sourceUrl = "https://contoso.sharepoint.com/Documents/SharePoint User Guide.docx";
string destinationUrl = "https://contoso.sharepoint.com/Documents/SharePoint User Guide 2013.docx";
FieldInformation[] fieldInfos;
CopyResult[] result;
byte[] fileContent;
using(var proxyCopy = new Copy())
{
proxyCopy.Url = webUri + "/_vti_bin/Copy.asmx";
proxyCopy.CookieContainer = GetAuthCookies(webUri, userName, password);
proxyCopy.GetItem(sourceUrl,out fieldInfos,out fileContent);
proxyCopy.CopyIntoItems(sourceUrl,new []{ destinationUrl}, fieldInfos, fileContent, out result);
}
References
Remote Authentication in SharePoint Online Using Claims-Based
Authentication
SharePoint Online Client Components SDK
In my case (on premise) i have that error. when i changed at iis SharePoint authentication for web application , and disable "Forms Authentication". Now, i canĀ“t enter to SharePoint by UI, but the Web Service works... So I have revert and I have been looking and...
[Paul stork] The Web Application for this site is running in Classic Mode rather than Claims mode. This can happen if you create the web app using Powershell or upgrade from 2010. You can use PowerShell to change it.
http://technet.microsoft.com/en-us/library/gg251985.aspx
I have tried the Web Service in another new application created by UI in Central Administration (in same farm) and it had worked. The problem was the web application.
To try:
http://sharepointyankee.com/2011/01/04/the-request-failed-with-the-error-message-object-moved-sharepoint-2010-web-services-fba/
Extend your mixed authentication web application, and create a zone just for Windows Authentication, then change the Web Reference URL in the properties of your web service, to use that extended URL and port. You should have no issues of this kind anymore.

Categories

Resources