"RunWithElevatedPrivileges" in sharepoint - c#

"RunWithElevatedPrivileges": Programmatically in C# it doesn't help me to allow users without manage List permission to upload file to sharepoint list items. My code is:
SPSecurity.RunWithElevatedPrivileges(delegate
{
SPWeb web = SPContext.Current.Site;
// my logic to upload file and edit list item attachments.
});
Complete code
protected void btn_Upload_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(#"C:\Upload.txt", true);
try
{
if (this.FileUpload1.HasFile)
{
string siteURL = SPContext.Current.Web.Url.ToString();
if (Request["Items"] != null && Request["ListId"] != null)
{
string SelectedItems = Convert.ToString(Request["Items"]);
string[] lstJobsIds = SelectedItems.Split(new string[] { "|" }, StringSplitOptions.None);
SPList list = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//SPSite site = SPContext.Current.Site;
using (SPSite site = new SPSite("http://sitrURL"))
{
using (SPWeb web = site.OpenWeb())
{
// Fetch the List
//list = web.Lists["ListName"];
sw.WriteLine("WEb is :" + web);
list = web.Lists["ListName"];
if (lstJobsIds.Length > 0)
{
////site.AllowUnsafeUpdates = true;
////web.AllowUnsafeUpdates = true;
for (int i = 0; i < lstJobsIds.Length; i++)
{
// Get the List item
if (lstJobsIds[i] != null && lstJobsIds[i] != string.Empty)
{
sw.WriteLine(lstJobsIds[i]);
SPListItem listItem = list.GetItemById(int.Parse(lstJobsIds[i]));
// Get the Attachment collection
SPAttachmentCollection attachmentCollection = listItem.Attachments;
Stream attachmentStream;
Byte[] attachmentContent;
sw.WriteLine(this.FileUpload1.PostedFile);
sw.WriteLine(this.FileUpload1.FileName);
attachmentStream = this.FileUpload1.PostedFile.InputStream;
attachmentContent = new Byte[attachmentStream.Length];
attachmentStream.Read(attachmentContent, 0, (int)attachmentStream.Length);
attachmentStream.Close();
attachmentStream.Dispose();
// Add the file to the attachment collection
attachmentCollection.Add(this.FileUpload1.FileName, attachmentContent);
// Update th list item
listItem.Update();
web.AllowUnsafeUpdates = true;
}
}
//web.AllowUnsafeUpdates = false;
//site.AllowUnsafeUpdates = false;
}
sw.Close();
}
}
});
}
}
}
catch (Exception ex)
{
sw.WriteLine(ex);
sw.Close();
}
}
Now When user click on button to upload file he gets HTTP Error 403 Forbidden.
So,how to allow users With limit permission to execute my custom function normally?

Your code is wrong. Always create and dispose off the objects within the RunWithElevatedPrivileges delegate. So you should create new instance of SPweb inside the RunWithElevatedPrivileges block by using 'new' keyword.
Example:
private void yourFunction()
{
SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedSite = new SPSite(site.ID))
{
using (SPWeb ElevatedWeb = ElevatedSite.OpenWeb(web.ID))
{
// Code Using the SPWeb Object Goes Here
}
}
});
}

Sometimes in custom SharePoint solutions we need to execute custom code using System Account privileges than the current logged in user which may not have sufficient rights to execute custom code. In these situations we use RunWithElevatedPrivileges() method to delegate System Account rights to current logged in user.
In case current user does not have appropriate permissions to execute custom code then he will get “Access Denied” error. To bypass “Access Denied” error we use RunWithElevatedPrivileges() method.
Click on below link for more detailed answer
http://sharepointbag.com/latest/code-snippets/sharepoint/security/5/how-to-use-run-with-elevated-privileges-(rwep)-in-sharepoint/

Related

Access SharePoint List using a pair of email id / password without using a browser login in C#

I am trying to access a SharePoint List using email id and password, without using a browser login inside Microsoft Bot framework code in C#.
Although I can fetch a few files like ".csv", ".js" , I am unable to access the SharePoint Calendar.
If anyone has encountered similar issues before, please help.
Code to access SharePoint:
using (ClientContext context = new ClientContext(SERVICE_URL))
{
SecureString securePassword = new SecureString();
for (int i = 0; i<HASH_CODE.Length; i++)
{
securePassword.AppendChar(HASH_CODE[i]);
}
SharePointOnlineCredentials creds = new SharePointOnlineCredentials(USER, securePassword);
context.Credentials = creds;
context.Load(context.Web.Lists);
Web site = context.Web;
ListCollection listColl = site.Lists;
FolderCollection collFolder = site.Folders;
context.Load(collFolder);
context.ExecuteQuery();
foreach (Folder folder in collFolder)
{
context.Load(folder.Files);
context.ExecuteQuery();
FileCollection fileCol = folder.Files;
foreach (var file in folder.Files)
{
if (file.Name == "Calendar.aspx")
{
File attachment = file;
string filename = attachment.Name;
var serverFilePath = attachment.ServerRelativeUrl;
DownloadIt(serverFilePath, path, context, filename);
}
}
context.ExecuteQuery();
}
}
}

Programatically create an IIS website on button click [duplicate]

We have been able to create a web site. We did this using the information in this link:
https://msdn.microsoft.com/en-us/library/ms525598.aspx
However, we would like to use a port number other that port 80. How do we do this?
We are using IIS 6
If you're using IIS 7, there is a new managed API called Microsoft.Web.Administration
An example from the above blog post:
ServerManager iisManager = new ServerManager();
iisManager.Sites.Add("NewSite", "http", "*:8080:", "d:\\MySite");
iisManager.CommitChanges();
If you're using IIS 6 and want to do this, it's more complex unfortunately.
You will have to create a web service on every server, a web service that handles the creation of a website because direct user impersonation over the network won't work properly (If I recall this correctly).
You will have to use Interop Services and do something similar to this (This example uses two objects, server and site, which are instances of custom classes that store a server's and site's configuration):
string metabasePath = "IIS://" + server.ComputerName + "/W3SVC";
DirectoryEntry w3svc = new DirectoryEntry(metabasePath, server.Username, server.Password);
string serverBindings = ":80:" + site.HostName;
string homeDirectory = server.WWWRootPath + "\\" + site.FolderName;
object[] newSite = new object[] { site.Name, new object[] { serverBindings }, homeDirectory };
object websiteId = (object)w3svc.Invoke("CreateNewSite", newSite);
// Returns the Website ID from the Metabase
int id = (int)websiteId;
See more here
Heres the solution.
Blog article : How to add new website in IIS 7
On Button click :
try
{
ServerManager serverMgr = new ServerManager();
string strWebsitename = txtwebsitename.Text; // abc
string strApplicationPool = "DefaultAppPool"; // set your deafultpool :4.0 in IIS
string strhostname = txthostname.Text; //abc.com
string stripaddress = txtipaddress.Text;// ip address
string bindinginfo = stripaddress + ":80:" + strhostname;
//check if website name already exists in IIS
Boolean bWebsite = IsWebsiteExists(strWebsitename);
if (!bWebsite)
{
Site mySite = serverMgr.Sites.Add(strWebsitename.ToString(), "http", bindinginfo, "C:\\inetpub\\wwwroot\\yourWebsite");
mySite.ApplicationDefaults.ApplicationPoolName = strApplicationPool;
mySite.TraceFailedRequestsLogging.Enabled = true;
mySite.TraceFailedRequestsLogging.Directory = "C:\\inetpub\\customfolder\\site";
serverMgr.CommitChanges();
lblmsg.Text = "New website " + strWebsitename + " added sucessfully";
}
else
{
lblmsg.Text = "Name should be unique, " + strWebsitename + " is already exists. ";
}
}
catch (Exception ae)
{
Response.Redirect(ae.Message);
}
Looping over sites whether name already exists
public bool IsWebsiteExists(string strWebsitename)
{
Boolean flagset = false;
SiteCollection sitecollection = serverMgr.Sites;
foreach (Site site in sitecollection)
{
if (site.Name == strWebsitename.ToString())
{
flagset = true;
break;
}
else
{
flagset = false;
}
}
return flagset;
}
Try the following Code to Know the unUsed PortNo
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
// Find unused ID PortNo for new web site
bool found_valid_port_no = false;
int random_port_no = 1;
do
{
bool regenerate_port_no = false;
System.Random random_generator = new Random();
random_port_no = random_generator.Next(9000,15000);
foreach (DirectoryEntry e in root.Children)
{
if (e.SchemaClassName == "IIsWebServer")
{
int site_id = Convert.ToInt32(e.Name);
//For each detected ID find the port Number
DirectoryEntry vRoot = new DirectoryEntry("IIS://localhost/W3SVC/" + site_id);
PropertyValueCollection pvcServerBindings = vRoot.Properties["serverbindings"];
String bindings = pvcServerBindings.Value.ToString().Replace(":", "");
int port_no = Convert.ToInt32(bindings);
if (port_no == random_port_no)
{
regenerate_port_no = true;
break;
}
}
}
found_valid_port_no = !regenerate_port_no;
} while (!found_valid_port_no);
int newportId = random_port_no;
I have gone though all answer here and also tested. Here is the most clean smarter version of answer for this question. However this still cant work on IIS 6.0. so IIS 8.0 or above is required.
string domainName = "";
string appPoolName = "";
string webFiles = "C:\\Users\\John\\Desktop\\New Folder";
if (IsWebsiteExists(domainName) == false)
{
ServerManager iisManager = new ServerManager();
iisManager.Sites.Add(domainName, "http", "*:8080:", webFiles);
iisManager.ApplicationDefaults.ApplicationPoolName = appPoolName;
iisManager.CommitChanges();
}
else
{
Console.WriteLine("Name Exists already");
}
public static bool IsWebsiteExists(string strWebsitename)
{
ServerManager serverMgr = new ServerManager();
Boolean flagset = false;
SiteCollection sitecollection = serverMgr.Sites;
flagset = sitecollection.Any(x => x.Name == strWebsitename);
return flagset;
}
This simplified method will create a site with default binding settings, and also create the application pool if needed:
public void addIISApplication(string siteName, string physicalPath, int port, string appPoolName)
{
using (var serverMgr = new ServerManager())
{
var sitecollection = serverMgr.Sites;
if (!sitecollection.Any(x => x.Name.ToLower() == siteName.ToLower()))
{
var appPools = serverMgr.ApplicationPools;
if (!appPools.Any(x => x.Name.ToLower() == appPoolName.ToLower()))
{
serverMgr.ApplicationPools.Add(appPoolName);
}
var mySite = serverMgr.Sites.Add(siteName, physicalPath, port);
mySite.ApplicationDefaults.ApplicationPoolName = appPoolName;
serverMgr.CommitChanges();
}
}
}
In properties of site select "Web Site" tab and specify TCP Port.
In studio to debug purpose specify http://localhost:<port>/<site> at tab Web for "Use Local IIS Web Server"

How to do authentication onedrive for Business and upload a file (WinForms)

Im trying to make a app which uploads the files with the C# code I write to Microsoft Office 365 OneDrive for Business.
I tried several things to get the refresh token and access token.
But I could not find the way how to implement this on the web.
I tried to use this blog explenation on how to authenticate with REST.
This is what I have got so far:
private void btnAuthenticate_Click(object sender, EventArgs e)
{
webBrowser1.Navigate(GetAuthorizationUrl());
}
private string GetAuthorizationUrl()
{
// Create a request for an authorization code.
string url = string.Format(" {0}common/oauth2/authorize?&response_type=code&client_id={1}&resource={2}&redirect_uri={3}&state={4}",
_authorizationEndpoint,
_clientId,
_resource,
_redirectURI,
_state);
return url;
}
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
if (e.Url.AbsoluteUri.Contains("code="))
{
var splited = e.Url.AbsoluteUri.Split(new char[] { '=', '&' });
_authorizationInformation.Code = splited[1];
_authorizationInformation.SessionState = splited[3];
if (_authorizationInformation.SessionState.Equals(_state))
{
GetTokenInformation(_authorizationInformation);
}
}
}
private TokenInformation GetTokenInformation(AuthorizationInformation authInformation)
{
try
{
var response = Post(HttpUtility.UrlEncode(_tokenEndpoint), new NameValueCollection(){
{ "grant_type", "authorization_code" },
{ "code", authInformation.Code },
{ "redirect_uri", _redirectURI },
{ "client_id", _clientId },
{ "client_secret", _clientSecret },
});
Stream responseStream = new MemoryStream(response);
using (var reader = new StreamReader(responseStream))
{
var json = reader.ReadToEnd();
_tokenInformation = JsonConvert.DeserializeObject<TokenInformation>(json);
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "Error" + exception.HResult.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
In the method GetTokenInformation the response is always empty 0 bytes.
**First question: How do I correctly authenticate with OAuth to onedrive pro?**
**Second question: When I got the accesstoken how do I upload a file?**
As I know, you can not use OAuth authentication for SharePoint online in Windows client applications(including Windows Form applications). This MSDN article shows the OAuth flow for SharePoint online: you need a server URL as the app’s registered redirect URI, but Windows Forms application doesn't have that.
Another way to do it is to use SharePoint client object model, the code below shows how to access the OneDrive:
string username = "xxx#xxx.onmicrosoft.com";
String pwd = "xxx#";
ClientContext context = new ClientContext("https://xxx-my.sharepoint.com/personal/xxx_xxxinc_onmicrosoft_com/");
SecureString password = new SecureString();
foreach (char c in pwd.ToCharArray())
{
password.AppendChar(c); }
context.Credentials = new SharePointOnlineCredentials(username, password);
//login in to SharePoint online
context.ExecuteQuery();
//OneDrive is acctually a Document list
List docs = context.Web.Lists.GetByTitle("Documents");
context.ExecuteQuery();
CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
ListItemCollection items = docs.GetItems(query);
// Retrieve all items the document list
context.Load(items);
context.ExecuteQuery();
foreach (ListItem listItem in items)
{
Console.WriteLine(listItem["Title"]);
}
Also, you can use REST Apis, this article Access OneDrive for Business using the SharePoint 2013 APIs explains how to use REST to do it.

How to download/upload files from/to SharePoint 2013 using CSOM?

I am developing a Win8 (WinRT, C#, XAML) client application (CSOM) that needs to download/upload files from/to SharePoint 2013.
How do I do the Download/Upload?
Upload a file
Upload a file to a SharePoint site (including SharePoint Online) using File.SaveBinaryDirect Method:
using (var clientContext = new ClientContext(url))
{
using (var fs = new FileStream(fileName, FileMode.Open))
{
var fi = new FileInfo(fileName);
var list = clientContext.Web.Lists.GetByTitle(listTitle);
clientContext.Load(list.RootFolder);
clientContext.ExecuteQuery();
var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, fs, true);
}
}
Download file
Download file from a SharePoint site (including SharePoint Online) using File.OpenBinaryDirect Method:
using (var clientContext = new ClientContext(url))
{
var list = clientContext.Web.Lists.GetByTitle(listTitle);
var listItem = list.GetItemById(listItemId);
clientContext.Load(list);
clientContext.Load(listItem, i => i.File);
clientContext.ExecuteQuery();
var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
var fileName = Path.Combine(filePath,(string)listItem.File.Name);
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}
}
This article describes various options for accessing SharePoint content. You have a choice between REST and CSOM. I'd try CSOM if possible. File upload / download specifically is nicely described in this article.
Overall notes:
//First construct client context, the object which will be responsible for
//communication with SharePoint:
var context = new ClientContext(#"http://site.absolute.url")
//then get a hold of the list item you want to download, for example
var list = context.Web.Lists.GetByTitle("Pipeline");
var query = CamlQuery.CreateAllItemsQuery(10000);
var result = list.GetItems(query);
//note that data has not been loaded yet. In order to load the data
//you need to tell SharePoint client what you want to download:
context.Load(result, items=>items.Include(
item => item["Title"],
item => item["FileRef"]
));
//now you get the data
context.ExecuteQuery();
//here you have list items, but not their content (files). To download file
//you'll have to do something like this:
var item = items.First();
//get the URL of the file you want:
var fileRef = item["FileRef"];
//get the file contents:
FileInformation fileInfo = File.OpenBinaryDirect(context, fileRef.ToString());
using (var memory = new MemoryStream())
{
byte[] buffer = new byte[1024 * 64];
int nread = 0;
while ((nread = fileInfo.Stream.Read(buffer, 0, buffer.Length)) > 0)
{
memory.Write(buffer, 0, nread);
}
memory.Seek(0, SeekOrigin.Begin);
// ... here you have the contents of your file in memory,
// do whatever you want
}
Avoid working with the stream directly, read it into the memory first. Network-bound streams are not necessarily supporting stream operations, not to mention performance. So, if you are reading a pic from that stream or parsing a document, you may end up with some unexpected behavior.
On a side note, I have a related question re: performance of this code above, as you are taking some penalty with every file request. See here. And yes, you need 4.5 full .NET profile for this.
File.OpenBinaryDirect may cause exception when you are using Oauth accestoken
Explained in This Article
Code should be written as below to avoid exceptions
Uri filename = new Uri(filepath);
string server = filename.AbsoluteUri.Replace(filename.AbsolutePath,
"");
string serverrelative = filename.AbsolutePath;
Microsoft.SharePoint.Client.File file =
this.ClientContext.Web.GetFileByServerRelativeUrl(serverrelative);
this.ClientContext.Load(file);
ClientResult<Stream> streamResult = file.OpenBinaryStream();
this.ClientContext.ExecuteQuery();
return streamResult.Value;
A little late this comment but I will leave here my results working with the library of SharePoin Online and it is very easy to use and implement in your project, just go to the NuGet administrator of .Net and Add Microsoft.SharePoint.CSOM to your project .
[https://developer.microsoft.com/en-us/office/blogs/new-sharepoint-csom-version-released-for-office-365-may-2017/][1]
The following code snippet will help you connect your credentials to your SharePoint site, you can also read and download files from a specific site and folder.
using System;
using System.IO;
using System.Linq;
using System.Web;
using Microsoft.SharePoint.Client;
using System.Security;
using ClientOM = Microsoft.SharePoint.Client;
namespace MvcApplication.Models.Home
{
public class SharepointModel
{
public ClientContext clientContext { get; set; }
private string ServerSiteUrl = "https://somecompany.sharepoint.com/sites/ITVillahermosa";
private string LibraryUrl = "Shared Documents/Invoices/";
private string UserName = "someone.surname#somecompany.com";
private string Password = "********";
private Web WebClient { get; set; }
public SharepointModel()
{
this.Connect();
}
public void Connect()
{
try
{
using (clientContext = new ClientContext(ServerSiteUrl))
{
var securePassword = new SecureString();
foreach (char c in Password)
{
securePassword.AppendChar(c);
}
clientContext.Credentials = new SharePointOnlineCredentials(UserName, securePassword);
WebClient = clientContext.Web;
}
}
catch (Exception ex)
{
throw (ex);
}
}
public string UploadMultiFiles(HttpRequestBase Request, HttpServerUtilityBase Server)
{
try
{
HttpPostedFileBase file = null;
for (int f = 0; f < Request.Files.Count; f++)
{
file = Request.Files[f] as HttpPostedFileBase;
string[] SubFolders = LibraryUrl.Split('/');
string filename = System.IO.Path.GetFileName(file.FileName);
var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/uploads"), filename);
file.SaveAs(path);
clientContext.Load(WebClient, website => website.Lists, website => website.ServerRelativeUrl);
clientContext.ExecuteQuery();
//https://somecompany.sharepoint.com/sites/ITVillahermosa/Shared Documents/
List documentsList = clientContext.Web.Lists.GetByTitle("Documents"); //Shared Documents -> Documents
clientContext.Load(documentsList, i => i.RootFolder.Folders, i => i.RootFolder);
clientContext.ExecuteQuery();
string SubFolderName = SubFolders[1];//Get SubFolder 'Invoice'
var folderToBindTo = documentsList.RootFolder.Folders;
var folderToUpload = folderToBindTo.Where(i => i.Name == SubFolderName).First();
var fileCreationInformation = new FileCreationInformation();
//Assign to content byte[] i.e. documentStream
fileCreationInformation.Content = System.IO.File.ReadAllBytes(path);
//Allow owerwrite of document
fileCreationInformation.Overwrite = true;
//Upload URL
fileCreationInformation.Url = ServerSiteUrl + LibraryUrl + filename;
Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);
//Update the metadata for a field having name "DocType"
uploadFile.ListItemAllFields["Title"] = "UploadedCSOM";
uploadFile.ListItemAllFields.Update();
clientContext.ExecuteQuery();
}
return "";
}
catch (Exception ex)
{
throw (ex);
}
}
public string DownloadFiles()
{
try
{
string tempLocation = #"c:\Downloads\Sharepoint\";
System.IO.DirectoryInfo di = new DirectoryInfo(tempLocation);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
FileCollection files = WebClient.GetFolderByServerRelativeUrl(this.LibraryUrl).Files;
clientContext.Load(files);
clientContext.ExecuteQuery();
if (clientContext.HasPendingRequest)
clientContext.ExecuteQuery();
foreach (ClientOM.File file in files)
{
FileInformation fileInfo = ClientOM.File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl);
clientContext.ExecuteQuery();
var filePath = tempLocation + file.Name;
using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
{
fileInfo.Stream.CopyTo(fileStream);
}
}
return "";
}
catch (Exception ex)
{
throw (ex);
}
}
}
}
Then to invoke the functions from the controller in this case MVC ASP.NET is done in the following way.
using MvcApplication.Models.Home;
using System;
using System.Web.Mvc;
namespace MvcApplication.Controllers
{
public class SharepointController : MvcBoostraBaseController
{
[HttpPost]
public ActionResult Upload(FormCollection form)
{
try
{
SharepointModel sharepointModel = new SharepointModel();
return Json(sharepointModel.UploadMultiFiles(Request, Server), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return ThrowJSONError(ex);
}
}
public ActionResult Download(string ServerUrl, string RelativeUrl)
{
try
{
SharepointModel sharepointModel = new SharepointModel();
return Json(sharepointModel.DownloadFiles(), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return ThrowJSONError(ex);
}
}
}
}
If you need this source code you can visit my github repository
https://github.com/israelz11/MvcBoostrapTestSharePoint/
Private Sub DownloadFile(relativeUrl As String, destinationPath As String, name As String)
Try
destinationPath = Replace(destinationPath + "\" + name, "\\", "\")
Dim fi As FileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(Me.context, relativeUrl)
Dim down As Stream = System.IO.File.Create(destinationPath)
Dim a As Integer = fi.Stream.ReadByte()
While a <> -1
down.WriteByte(CType(a, Byte))
a = fi.Stream.ReadByte()
End While
Catch ex As Exception
ToLog(Type.ERROR, ex.Message)
End Try
End Sub
Though this is an old post and have many answers, but here I have my version of code to upload the file to sharepoint 2013 using CSOM(c#)
I hope if you are working with downloading and uploading files then you know how to create Clientcontext object and Web object
/* Assuming you have created ClientContext object and Web object*/
string listTitle = "List title where you want your file to upload";
string filePath = "your file physical path";
List oList = web.Lists.GetByTitle(listTitle);
clientContext.Load(oList.RootFolder);//to load the folder where you will upload the file
FileCreationInformation fileInfo = new FileCreationInformation();
fileInfo.Overwrite = true;
fileInfo.Content = System.IO.File.ReadAllBytes(filePath);
fileInfo.Url = fileName;
File fileToUpload = fileCollection.Add(fileInfo);
clientContext.ExecuteQuery();
fileToUpload.CheckIn("your checkin comment", CheckinType.MajorCheckIn);
if (oList.EnableMinorVersions)
{
fileToUpload.Publish("your publish comment");
clientContext.ExecuteQuery();
}
if (oList.EnableModeration)
{
fileToUpload.Approve("your approve comment");
}
clientContext.ExecuteQuery();
And here is the code for download
List oList = web.Lists.GetByTitle("ListNameWhereFileExist");
clientContext.Load(oList);
clientContext.Load(oList.RootFolder);
clientContext.Load(oList.RootFolder.Files);
clientContext.ExecuteQuery();
FileCollection fileCollection = oList.RootFolder.Files;
File SP_file = fileCollection.GetByUrl("fileNameToDownloadWithExtension");
clientContext.Load(SP_file);
clientContext.ExecuteQuery();
var Local_stream = System.IO.File.Open("c:/testing/" + SP_file.Name, System.IO.FileMode.CreateNew);
var fileInformation = File.OpenBinaryDirect(clientContext, SP_file.ServerRelativeUrl);
var Sp_Stream = fileInformation.Stream;
Sp_Stream.CopyTo(Local_stream);
Still there are different ways I believe that can be used to upload and download.
Just a suggestion SharePoint 2013 online & on-prem file encoding is UTF-8 BOM.
Make sure your file is UTF-8 BOM, otherwise your uploaded html and scripts may not rendered correctly in browser.
I would suggest reading some Microsoft documentation on what you can do with CSOM. This might be one example of what you are looking for, but there is a huge API documented in msdn.
// Starting with ClientContext, the constructor requires a URL to the
// server running SharePoint.
ClientContext context = new ClientContext("http://SiteUrl");
// Assume that the web has a list named "Announcements".
List announcementsList = context.Web.Lists.GetByTitle("Announcements");
// Assume there is a list item with ID=1.
ListItem listItem = announcementsList.Items.GetById(1);
// Write a new value to the Body field of the Announcement item.
listItem["Body"] = "This is my new value!!";
listItem.Update();
context.ExecuteQuery();
From: http://msdn.microsoft.com/en-us/library/fp179912.aspx

SharePoint 2010 Client Object Model Add Sharepoint user/group to every document library folder programatically

I have the code below that I cobbled together via various pieces found via google search etc.
The code works like a champ to provide a treeview of the various libraries and folders within them.
Recently we had an important user accidentally removed from the system and when that happened, it was also removed from every library & folder it was it (which was every single one).. (we have broken the permissions for every folder and do not inherit permissions at library or folder levels)
I figured this app code goes recursively through all the libraries and folders on the site... I could just add a bit of code to add the user to each folder with it.
My problem is that every example/suggestion I've found so far has Folder.item.blahblahblah
but I have no method called "item" in my folder object(s)
Any hints or outright step-by-step fixes for my code below to do what I need?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;
using System.Net;
namespace red
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "It Begins...\r\n";
string SitenameDev = #"https://portal/sites/devv/team";
string SitenameProd = #"https://portal/sites/";
ClientContext clientcontext = new ClientContext(SitenameProd);
clientcontext.Credentials = new NetworkCredential("sitecollectionadminacct", "pswd", "Domain");
//Load Libraries from SharePoint
clientcontext.Load(clientcontext.Web.Lists);
clientcontext.ExecuteQuery();
foreach (List list in clientcontext.Web.Lists)
{
try
{
if (list.BaseType.ToString() == "DocumentLibrary" && !list.IsApplicationList && list.Title != "Form Templates" && list.Title != "Customized Reports" && list.Title != "Site Collection Documents" && list.Title != "Site Collection Images" && list.Title != "Images")
{
clientcontext.Load(list);
clientcontext.ExecuteQuery();
clientcontext.Load(list.RootFolder);
clientcontext.Load(list.RootFolder.Folders);
clientcontext.Load(list.RoleAssignments);
clientcontext.ExecuteQuery();
TreeViewLibraries.ShowLines = true;
TreeNode LibraryNode = new TreeNode(list.Title);
//MessageBox.Show(LibraryNode.Name);
TreeViewLibraries.Nodes.Add(LibraryNode);
if (!list.Title.StartsWith("Nothing here"))
{
foreach (Folder SubFolder in list.RootFolder.Folders)
{
if (SubFolder.Name != "Forms")
{
TreeNode MainNode = new TreeNode(SubFolder.Name);
LibraryNode.Nodes.Add(MainNode);
FillTreeViewNodes(SubFolder, MainNode, clientcontext);
}
}
}
}
}
catch (Exception eee)
{
}
}
}
//Recursive Function
public void FillTreeViewNodes(Folder SubFolder, TreeNode MainNode, ClientContext clientcontext)
{
clientcontext.Load(SubFolder.Folders);
clientcontext.ExecuteQuery();
foreach (Folder Fol in SubFolder.Folders)
{
TreeNode SubNode = new TreeNode(Fol.Name);
MainNode.Nodes.Add(SubNode);
FillTreeViewNodes(Fol, SubNode, clientcontext);
//ListItem Fole = new ListItem();
}
}
private void TreeViewLibraries_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
{
MessageBox.Show("Node: " + e.Node.Text);
try
{
MessageBox.Show("Parent: " + e.Node.Parent.Text);
}
catch (System.NullReferenceException)
{
MessageBox.Show("Parent: " + "None!");
}
}
}
}
Microsoft.SharePoint.Client.ClientContext clientContext = new Microsoft.SharePoint.Client.ClientContext("URL");
var user = (Microsoft.SharePoint.Client.Principal)clientContext.Web.EnsureUser("domain\user");
Microsoft.SharePoint.Client.CamlQuery caml = new Microsoft.SharePoint.Client.CamlQuery();
caml.ViewXml = //CAML QUERY HERE...
caml.FolderServerRelativeUrl = //relative path here...
items = objList.GetItems(caml);
clientContext.Load(items);
clientContext.Credentials = new NetworkCredential(username, password,domain);
clientContext.ExecuteQuery();
item = items[0];
item.BreakRoleInheritance(true, true);
clientContext.ExecuteQuery();
// You may choose the asscess right here
var reader = clientContext.Web.RoleDefinitions.GetByType(Microsoft.SharePoint.Client.RoleType.Reader);
var collRdb = new Microsoft.SharePoint.Client.RoleDefinitionBindingCollection(clientContext) { reader };
item.RoleAssignments.Add(user, collRdb);
clientContext.ExecuteQuery();

Categories