2017-05-23 25 views
13

Teczki pracy:Set Uprawnienia Pozycja

Teraz wiem, jak ustawić uprawnienia folderu w bibliotece:

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(); 
} 

próba Plik:

I Próbowałem dodać nazwę pliku do tej linii:

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

Zawiadomienie (/File1.docx) dodanego do końca powyżej linii.


Błąd otrzymali:

Ale to właśnie daje błąd:

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: 

Stosowna informacja:

Jest to aplikacja WinForm działa na lokalna maszyna, cre z użyciem C#, przy użyciu .NET 4.0. wersja SharePoint jest 2010.


Pytanie:

Jak ustawić uprawnienia dla określonej pliku? Jak już wiem, jak ustawić uprawnienia dla określonego folderu .

Odpowiedz

2

Zakładam, że andresm53 ma rację używasz metodę rozszerzenia wspominał.

Aby uzyskać tę metodę pracy z plikami, należy wysłać zapytanie przez FileLeafRef (nazwa pliku) i upewnić się, że dodano FileLeafRef do zapytania ViewFields.

/edit

Jeszcze jedna bardzo ważna rzecz, zapytanie plik limitu dokładnym folderze z:

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

kodeksu pracy poniżej:

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(); 
} 
+0

Dodałem kolejną nagrodę właśnie za tę odpowiedź, ponieważ nie mogłem zaakceptować odpowiedzi zeszłego tygodnia z powodu nieoczekiwanego braku dostępu do komputera. Ta odpowiedź działa świetnie. Dzięki za pomoc! – oshirowanen

+0

chętnie Ci pomożemy i dziękuję! – tinamou

1

Nie ładujesz niczego w swoim kontekście. Musisz załadować kontekst za pomocą "zapytań", aby wykonać, jeśli wykonasz ładowanie, nie robi nic. Może to wymagać pewnych drobnych zmian, ale koncepcja jest prawidłowa.

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(); 
+0

Właśnie próbowałem tego, ale wciąż ten sam błąd wiadomość, jeśli dołączę plik 'File1.docx'. – oshirowanen

+0

to pomaga? http://www.morgantechspace.com/2016/04/set-list-item-level-permission-using-csom-c-sharp.html – andresm53

+0

@ andresm53, Próbowałem już tego kodu, ale myślę, że jest to nowsza wersja sharepoint. Daje mi 2 błędy "nie można przekonwertować lambda pxpression" i "nie zawiera definicji dla SiteUsers". Korzystam z SharePoint 2010. – oshirowanen

4

Sprawdziliśmy 2010 CSOM documentation, a metoda używasz LoadItemByUrl nie istnieje. Czy to jest rozszerzenie, które napisałeś, być może this one? Jeśli tak, problem musi znajdować się w tym rozszerzeniu, prawdopodobnie w CAML query.

Jako odniesienie, ten kod CSOM z 2010 r. Działał dobrze przeciwko laboratorium SharePoint 2010. Zauważ, że używa 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(); 
+0

Niestety, nie miałem dostępu do komputera w zeszłym tygodniu z powodu nieprzewidzianych okoliczności. Jak określić plik zamiast GetItemById? – oshirowanen

0

Spróbuj tego.

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; 
     } 
0

Chyba problem jest związany z toru, którego używasz:

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

Spróbuj

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();