development – How to update one drive file using SharePoint CSOM C# code programmatically?

I am looking for a way to update the one drive file or document using some SharePoint CSOM code. So can we achieve this using CSOM or some C# code?

I have even tried to load one drive site collection URL using the below code but I am not able to find the actual list from where I can access the stored files from one drive.

One Drive Site URL : https://{tenant}.my.sharepoint.com/personal/pravin_{tenant}_com

using (ClientContext clientcontext = new ClientContext(ConfigurationManager.AppSettings("SiteUrl")))
{
                Web web = clientcontext.Web;
                clientcontext.Load(clientcontext.Web.Lists);
                clientcontext.ExecuteQuery();

                foreach (List list in clientcontext.Web.Lists)
                {
                       var items = list.GetItems(CamlQuery.CreateAllItemsQuery());
                       clientcontext.Load(items);
                       clientcontext.ExecuteQuery();

                       foreach (var docItem in items)
                       {
                          //Here, I want to update the one drive file and upload it again using some sort of code.
                       }
                }
}

Please suggest the code or other ways using which we can update the one drive files programmatically.

Please help. Thanks in Advance.

csom – Fine grained permissions applied to SharePoint Online App-Auth?

We have written an application that access SharePoint CSOM apis to do the following:

  1. Get sharepoint users and groups in a site collection.
  2. Get sites in a site colleciton
  3. Get lists in a site collection
  4. Get role assignments/definitions
  5. Get list items in a site collection.
  6. Get changes since a given time in a site collection.

When we access SharePoint online using app-auth (oauth or azure private key), we are forced to give Full admin access to the app in order to do these things.

But when we user a normal service account (username/password) we have access to the fine-grained permissions as you would expect. We do this by creating a custom SharePoint permission level and give it

  • View Items – View items in lists and documents in document libraries.
  • Open Items – View the source of documents with server-side file handlers.
  • View Versions – View past versions of a list item or document.
  • View Application Pages – View forms, views, and application pages. Enumerate lists. Site Permissions
  • View Web Analytics Data – View reports on Web site usage.
  • Browse Directories – Enumerate files and folders in a Web site using SharePoint Designer and Web DAV interfaces.
  • View Pages – View pages in a Web site.
  • numerate Permissions – Enumerate permissions on the Web site, list, folder, document, or list item.
  • Browse User Information – View information about users of the Web site.
  • Use Remote Interfaces – Use SOAP, Web DAV, the Client Object Model or SharePoint Designer interfaces to access the Web site.
  • Open – Allows users to open a Web site, list, or folder in order to access items inside that container.

Is Microsoft ever going to fix this so that app-auth can be given fine grained permission?

csom – Can a user who is not a SharePoint Online administrator create a site collection with a template other than communication site or team site?

I have a user who I do not want to promote to a SharePoint Administrator, but I do want to allow them (because they are a developer) to create site collections with the template DEV#0 without having to go through me or my account I know I can set up an application that allows them to do this by using the permissions of the application, but before I do this, I just wanted to confirm that there is no way for a user to do this in SharePoint Online.

  • I can’t use SPO Powershell because they do not have access to the admin center.
  • I can’t use New-PnPTenantSite because they do not have access to the admin center.
  • I tried using the SharePoint Rest API, and here was the code I tried under their account from the JavaScript console at https://tenant.sharepoint.com/_layouts/15/sharepoint.aspx (I used JavaScript fetch for this test):

Request:

fetch("https://tenant.sharepoint.com/_api/SPSiteManager/Create", {
"headers": {
"accept": "application/json;odata=verbose",
"accept-language": "en-US,en;q=0.9",
"content-type": "application/json;odata=verbose",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requestdigest": "Request_Digest_Here"
},
"body": "{"request":{"__metadata":{"type":"Microsoft.SharePoint.Portal.SPSiteCreationRequest"},"WebTemplate":"DEV#0","Title":"Test dev site","Url":"https://tenant.sharepoint.com/sites/devsite1","Description":"","Classification":"","Lcid":1033,"ShareByEmailEnabled":false,"WebTemplateExtensionId":"00000000-0000-0000-0000-000000000000","HubSiteId":"00000000-0000-0000-0000-000000000000"}}",
"method": "POST",
"mode": "cors",
"credentials": "include"
});

Response:

{"error":{"code":"-2147024809, System.ArgumentException","message":{"lang":"en-US","value":"siteTemplaternParameter name: Performing this operation on a site with this template is not allowed."}}}
  • I can’t use CSOM because I can’t create a Tenant object to use the Tenant.CreateSite method without the account being a SharePoint administrator.
  • Correct me if I’m wrong, but I don’t think there is a way to create a site collection in JSOM.
  • Is it possible to use WSDL/SharePoint SOAP API?

Am I missing any methods? Is it possible to use the SOAP API or JSOM? Can I resolve the error in the REST API? Or is this just not possible?

csom – SharePoint On Prem High Trust 401 fun

This has been done to death but I have gone past madness. I just want to execute CSOM as the logged on user.

using (ClientContext clientContext = new ClientContext(SharepointURL))
{
   clientContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 
   //works but returns the app pool identity 
   clientContext.ExecuteQuery(); //executes whatever i want
}

The following using the app user’s details returns authentication mode Anonymous:

using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(spUrl, HttpContext.Request.LogonUserIdentity))
{
   clientContext.ExecuteQuery(); --user is site collection admin but gets 401 every time. 
}

What am I missing? simple out of the box SharePoint 2016 NTLM/Negotiate in IIS.

Creating new project with mandatory custom lookup fields via CSOM

I have to create new project with required custom lookup fields via CSOM and I have got the CustomFieldRequiredValueNotProvided exception. Here is my code. What am I doing wrong?


using (ProjectContext projectContext = new ProjectContext(url))
{

        projectContext.Credentials = manager.GetNetworkCredential();
        projectContext.Load(projectContext.EnterpriseProjectTypes);
        projectContext.ExecuteQuery();

        projectContext.Load(projectContext.LookupTables);
        projectContext.ExecuteQuery();
        var lookupTables = projectContext.LookupTables.ToList();

        projectContext.Load(projectContext.CustomFields);
        projectContext.ExecuteQuery();
        var customFields = projectContext.CustomFields.ToList();

        var customFieldDepartment = customFields.Where(x => x.Name == "cfName1").First();
        var customFieldCustomer = customFields.Where(x => x.Name == "cfName2").First();

        LookupTable lookupTableDepartments = projectContext.LookupTables.First(x => x.Name == "ltName1");
        projectContext.Load(lookupTableDepartments.Entries);
        projectContext.ExecuteQuery();

        LookupTable lookupTableCustomers = projectContext.LookupTables.First(x => x.Name == "ltName2");
        projectContext.Load(lookupTableCustomers.Entries);
        projectContext.ExecuteQuery();

        var department = lookupTableDepartments.Entries.ToList().First();
        var customer = lookupTableCustomers.Entries.ToList().First();

        var enterpriseProjectType = projectContext.EnterpriseProjectTypes.Where(x => x.Name == "eptName").First();

        var project = projectContext.Projects.Add(new ProjectCreationInformation
        {
                Id = Guid.NewGuid(),
                Name = "CSOM Project name",
                EnterpriseProjectTypeId = enterpriseProjectType.Id,
                Start = DateTime.Now
        });

        string departmentInternalName = customFieldDepartment.InternalName;
        string customerInternalName = customFieldCustomer.InternalName;
        string departmentInternalValue = department.InternalName;
        string customerInternalValue = customer.InternalName;

        project(departmentInternalName) = new string() { departmentInternalName };
        project(customerInternalName) = new string() { customerInternalValue };

        var job = projectContext.Projects.Update();
        var jobState = projectContext.WaitForQueue(job, 60);
}

csom – How to apply site-design in SharePoint Online?

Using CSOM, you can use tenant.applySiteDesign(). You need to pass the web URL and site design ID to this method.

Syntax:

public ClientObjectList<TenantSiteScriptActionResult> ApplySiteDesign(
    string webUrl,
    Guid siteDesignId
)

Official documentation can be found here:

Tenant.ApplySiteDesign method

Also, you can get complete code at: The Ultimate Guide to SharePoint Site Designs and Site Scripts

sharepoint online – Access Denied – GetWebhookSubscriptions CSOM

Team,

I am trying to subscribe webhook for all the lists in all O365 SharePoint sites.
Able to subscribe most of the sites, but in few sites i am getting access denied error.
I have site collection admin privilege in all the sites.

code:

            List lst = _ctx.Web.Lists.GetByTitle(ListTitle);
            _ctx.Load(lst);
            await _ctx.ExecuteQueryAsync();
            if (lst != null)
            {
                var subscription = lst.GetWebhookSubscriptions(); // getting error in this line
                ....

             }

Error:

   {"odata.error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Access denied. You do not have permission to perform this action or access this resource."}}}

May I know what could be the issue?

development – Log into SharePoint tenant through CSOM with MFA enabled

I need to log into a SharePoint tenant using an admin account that uses MFA.

This is the code.


public static ClientContext GetAdminClient(string tenantUrl)
{
    var authManager = new OfficeDevPnP.Core.AuthenticationManager();
    return authManager.GetWebLoginClientContext(tenantUrl); 
}

The login window does pop up for a second, but closes again immediately. I assume that it uses the cookie for my regular user (without SharePoint administration rights). The following requests that need tenant scope obviously do not work.

How can I clear the token cache so I can log in with the correct user? In the PnP PowerShell I had the same problem with -UseWebLogin, but there I can actually use the ClearTokenCache parameter and then it works. I have not yet found a similar option here, and PowerShell is not an option.

development – Download a specific file from SharePoint (CSOM) using C#

I’m developing a C# based application that requires to download, checkout, upload, check in on a specific file from/to Sharepoint with CSOM. So I have two questions here:

Firstly, on download, is there others way to download a specific named file under folder “Document” instead of searching through GetItemByID(). Please refer to code below:

string siteUrl = @"http://test.com/sites/company/";

ClientContext ctx = new ClientContext(siteUrl);
ctx.Credentials = new NetworkCredential("username", "password" , "domain");            
ctx.AuthenticationMode = ClientAuthenticationMode.Default;

var list = ctx.Web.Lists.GetByTitle("Document");
var listItem = list.GetItemById();

ctx.Load(list);
ctx.Load(listItem, i => i.File);
ctx.ExecuteQuery();

var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef);
var fileName = Path.Combine("C:\", (string)listItem.File.Name);

using (var fileStream = System.IO.File.Create(fileName))
{
    fileInfo.Stream.CopyTo(fileStream);
}

Secondly, in regards to the workflow (download, modify, check out, upload, check in), is this feasible of doing?

Thanks in advance.