简体   繁体   English

设置项目权限

[英]Set Item Permissions

Folders work: 文件夹工作:

I now know how to set the permissions of a folder in a library: 我现在知道如何设置库中文件夹的权限:

public void ChangeItemPermissions()
{
    _SharePoint.ClientContext _ClientContext = new _SharePoint.ClientContext("https://sharepoint.oshirowanen.com/sites/oshirodev/");
    _ClientContext.Credentials = new NetworkCredential("user", "pass", "oshirowanen.com");

    _SharePoint.Principal user = _ClientContext.Web.EnsureUser(@"oshirowanen\tom");

    var _List = _ClientContext.Web.Lists.GetByTitle("Library1");
    var _Item = _List.LoadItemByUrl("/sites/oshirodev/Library1/Folder1");
    var roleDefinition = _ClientContext.Site.RootWeb.RoleDefinitions.GetByType(_SharePoint.RoleType.Reader);
    var roleBindings = new _SharePoint.RoleDefinitionBindingCollection(_ClientContext) { roleDefinition };
    _Item.BreakRoleInheritance(false,true);
    _Item.RoleAssignments.Add(user, roleBindings);

    _ClientContext.ExecuteQuery();
}

File attempt: 文件尝试:

I've tried adding the file name to this line: 我已经尝试将文件名添加到此行:

var _Item = _List.LoadItemByUrl("/sites/oshirodev/Library1/Folder1/File1.docx");

Notice the ( /File1.docx ) added to the end of the above line. 注意( /File1.docx )添加到上面一行的末尾。


Error received: 收到错误:

But that just gives an error: 但这只是一个错误:

System.NullReferenceException was unhandled
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=ItemPermissions
  StackTrace:
       at ItemPermissions.Form1.ChangeItemPermissions() in c:\Users\Oshirowanen\Documents\Visual Studio 2013\Projects\ItemPermissions\ItemPermissions\Form1.cs:line 46
       at ItemPermissions.Form1.button1_Click(Object sender, EventArgs e) in c:\Users\Oshirowanen\Documents\Visual Studio 2013\Projects\ItemPermissions\ItemPermissions\Form1.cs:line 345
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at ItemPermissions.Program.Main() in c:\Users\Oshirowanen\Documents\Visual Studio 2013\Projects\ItemPermissions\ItemPermissions\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

Relevant info: 相关信息:

This is a WinForm app running on a local machine, created with C#, using .NET 4.0. 这是一个在本地计算机上运行的WinForm应用程序,使用.NET 4.0使用C#创建。 SharePoint version is 2010. SharePoint版本是2010年。


The question: 问题:

How do I set the permissions for a specific file ? 如何设置特定文件的权限? As I already know how to set permissions for a specific folder . 我已经知道如何为特定文件夹设置权限。

I reviewed the 2010 CSOM documentation , and the method you are using LoadItemByUrl doesn't exist. 我查看了2010 CSOM文档 ,并且您使用LoadItemByUrl的方法不存在。 Is that an extension you wrote, perhaps this one ? 这是你写的扩展,也许是这个 If so then the problem must be in that extension, probably in the CAML query . 如果是,则问题必须在该扩展中,可能在CAML查询中

As a reference, this 2010 CSOM code worked ok against a SharePoint 2010 lab. 作为参考,此2010 CSOM代码可以在SharePoint 2010实验室中正常运行。 Note that it uses GetItemByID: 请注意,它使用GetItemByID:

        ClientContext _ClientContext = new ClientContext("http://team/sites/Team1/");
        _ClientContext.Credentials = new NetworkCredential("administrator", "*****", "corp");
        Principal user = _ClientContext.Web.EnsureUser(@"corp\administrator");
        var _List = _ClientContext.Web.Lists.GetByTitle("Shared Documents");
        var _Item = _List.GetItemById(23);
        var roleDefinition = _ClientContext.Site.RootWeb.RoleDefinitions.GetByType(RoleType.Reader);
        var roleBindings = new RoleDefinitionBindingCollection(_ClientContext) { roleDefinition };
        _Item.BreakRoleInheritance(false, true);
        _Item.RoleAssignments.Add(user, roleBindings);
        _ClientContext.ExecuteQuery();

I assume that andresm53 is right about you using the extension method he mentioned. 我假设andresm53使用他提到的扩展方法是对的。

To get this method to work on files you need to query by FileLeafRef (file name) and make sure that you add FileLeafRef to query ViewFields . 要使此方法处理文件,您需要通过FileLeafRef (文件名)进行查询,并确保添加FileLeafRef以查询ViewFields

/edit /编辑

One more very important thing, limit file query to exact folder with: 另一个非常重要的事情是,将文件查询限制为精确文件夹:

query.FolderServerRelativeUrl = System.IO.Path.GetDirectoryName(url).Replace("\\", "/");

Working code below: 工作代码如下:

void Main()
{
    ClientContext context = new ClientContext("https://sharepoint.oshirowanen.com/sites/oshirodev/");
    context.Credentials = new NetworkCredential("user", "pass", "oshirowanen.com");
    Principal user = context.Web.EnsureUser(@"oshirowanen\tom");
    ChangeItemPermissions(context, "/sites/oshirodev/Library1/Folder1/File1.docx", "Library1", user, RoleType.Reader);
}

// Define other methods and classes here
public static ListItem LoadItemByUrl(List list, string url)
{
    var context = list.Context;
    string ext = System.IO.Path.GetExtension(url);

    var query = new CamlQuery();
    if (string.IsNullOrEmpty(ext))
        query.ViewXml = String.Format("<View><RowLimit>1</RowLimit><Query><Where><Eq><FieldRef Name='FileRef'/><Value> Type='Url'>{0}</Value></Eq></Where></Query></View>", url);
    else
    {
        query.ViewXml = String.Format("<View><ViewFields><FieldRef Name=\"FileLeafRef\" /></ViewFields><Query><Where><Eq><FieldRef Name=\"FileLeafRef\" /><Value Type=\"Text\">{0}</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>", System.IO.Path.GetFileName(url));
        query.FolderServerRelativeUrl = System.IO.Path.GetDirectoryName(url).Replace("\\", "/");
    }

    var items = list.GetItems(query);
    context.Load(items);
    context.ExecuteQuery();
    return items.Count > 0 ? items[0] : null;
}

public void ChangeItemPermissions(ClientContext context, string url, string listName, Principal user, RoleType type)
{    
    var list = context.Web.Lists.GetByTitle(listName);
    var item = LoadItemByUrl(list, url);
    var roleDefinition = context.Site.RootWeb.RoleDefinitions.GetByType(type);
    var roleBindings = new RoleDefinitionBindingCollection(context) { roleDefinition };
    item.BreakRoleInheritance(false, true);
    item.RoleAssignments.Add(user, roleBindings);
    context.ExecuteQuery();
}

You aren't loading anything in your context. 您没有在上下文中加载任何内容。 You need to Load your context with "queries" to execute, if you execute withou loading, it doesn't do anything. 您需要使用“查询”加载上下文来执行,如果您执行加载,它不会执行任何操作。 This may need some slight changes, but the concept is correct. 这可能需要一些细微的变化,但这个概念是正确的。

var _List = _ClientContext.Web.Lists.GetByTitle("Library1");
var _Item = _List.LoadItemByUrl("/sites/oshirodev/Library1/Folder1");
_ClientContext.Load(_Item);
_ClientContenxt.ExecuteQuery(); 

var roleDefinition = _ClientContext.Site.RootWeb.RoleDefinitions.GetByType(_SharePoint.RoleType.Reader);
_ClientContext.Load(roleDefinition);
_ClientContenxt.ExecuteQuery();

var roleBindings = new _SharePoint.RoleDefinitionBindingCollection(_ClientContext) { roleDefinition };
_Item.BreakRoleInheritance(false,true);
_Item.RoleAssignments.Add(user, roleBindings);

_ClientContext.Load(_Item);
_ClientContext.ExecuteQuery();

Try this. 试试这个。

 static void Main()
        {
            string siteUrl = "Your site url";
            ClientContext clientContext = new ClientContext(siteUrl);

            var list = clientContext.Web.Lists.GetByTitle("JZhu");
            var items = list.GetItems(CamlQuery.CreateAllItemsQuery());
            clientContext.Load(items);
            clientContext.ExecuteQuery();

            clientContext.Load(clientContext.Web.SiteGroups);
            clientContext.ExecuteQuery();

            GroupCollection oSiteCollectionGroups= clientContext.Web.SiteGroups;
            foreach (Group grp in oSiteCollectionGroups)
            {
                Console.WriteLine(grp.Title);
                if (grp.Title == "My group")
                {
                    oGroup=gpr;
                    break;
                }
            }

            foreach (var item in items)
            {
                var folder = GetListItemFolder(item); //get Folder
                Console.WriteLine(folder.Name);
                if (folder.Name=="Folder 1" || folder.Name=="Folder 2")
                {
                    item.BreakRoleInheritance(false);
                    RoleDefinitionBindingCollection collRoleDefinitionBinding = new RoleDefinitionBindingCollection(clientContext);

                    //set role type
                    collRoleDefinitionBinding.Add(clientContext.Web.RoleDefinitions.GetByType(RoleType.Reader));
                    //oGroup - your group
                    item.RoleAssignments.Add(oGroup, collRoleDefinitionBinding);

                    clientContext.ExecuteQuery();
                }
            }
        }

        private static Folder GetListItemFolder(ListItem listItem)
        {
            var folderUrl = (string)listItem["FileDirRef"];
            var parentFolder = listItem.ParentList.ParentWeb.GetFolderByServerRelativeUrl(folderUrl);
            listItem.Context.Load(parentFolder);
            listItem.Context.ExecuteQuery();
            return parentFolder;
        }

I guess your problem is related to the path you're using: 我想你的问题与你正在使用的路径有关:

 _Item = _List.LoadItemByUrl("/sites/oshirodev/Library1/Folder1/File1.docx");

Try this 试试这个

 Uri filename = new Uri(@"http://server//oshirodev/Library1/Folder1/File1.docx");

 string server = filename.AbsoluteUri.Replace(filename.AbsolutePath, "");

 Microsoft.SharePoint.Client.ClientContext clientContext = new Microsoft.SharePoint.Client.ClientContext(server);

_ClientContext.Credentials = new NetworkCredential("user", "pass", "oshirowanen.com");

_SharePoint.Principal user = _ClientContext.Web.EnsureUser(@"oshirowanen\tom");

var roleDefinition = _ClientContext.Site.RootWeb.RoleDefinitions.GetByType(_SharePoint.RoleType.Reader);
var roleBindings = new _SharePoint.RoleDefinitionBindingCollection(_ClientContext) { roleDefinition };
_Item.BreakRoleInheritance(false,true);
_Item.RoleAssignments.Add(user, roleBindings);

_ClientContext.ExecuteQuery();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM