Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

Good day! I have an event handler that, when you add a document to the library redirects the user to a web form with the parameters of the document. In the web form, it displays the current user in the form of Checkboxlist. The user selects the appropriate group, and he presses the Save button. Following are assigned permissions to the document according to the selected group. The problem is that the resolution of the document is not assigned according to selected groups. Here's the handler code:

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Web;
using System.IO;
namespace SharePointProject3.EventReceiver2
{
    /// <summary>
    /// События элемента списка
    /// </summary>
    public class EventReceiver2 : SPItemEventReceiver
    {
    private HttpContext _context;
    public EventReceiver2()
    {
        _context = HttpContext.Current;
    }
    public override void ItemAdding(SPItemEventProperties properties)
    {
        //Временно отключаем срабатывание обработчика
        EventFiringEnabled = false;
        //Получаем файл из HttpContext
            HttpPostedFile file = _context.Request.Files[0];
            Stream fileStream = file.InputStream;
            byte[] fileByte = new byte[file.ContentLength];
            fileStream.Read(fileByte, 0, file.ContentLength);
            //Загружаем файл в библиотеку документов
            SPFile fileUploded = properties.Web.Files.Add(properties.AfterUrl, fileByte);
            //Включаем обработчик обратно
            EventFiringEnabled = true;
            //Отменяем добавление файла, которое делал пользователь
            properties.Cancel = true;
            properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
            //Деламе редирект
            properties.RedirectUrl = properties.Web.Url + "/test_perm/default.aspx?ID=" + fileUploded.UniqueId;
        }
    }

    }

And here's the code of the Web Part:

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;
using Microsoft.SharePoint.Utilities;
namespace CustomGroupAssignment.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite("http://kviten:83/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPUser currentUser = web.CurrentUser;
                    SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
                    SPGroupCollection webGroups = currentUser.Groups;
                    CheckBoxList1.DataSource = webGroups;
                    CheckBoxList1.DataValueField = "ID";
                    CheckBoxList1.DataTextField = "Name";
                    CheckBoxList1.DataBind();
                    foreach (ListItem li in CheckBoxList1.Items)
                    {
                        li.Selected = true;
                    }
                    try
                    {
                        string itemID = Page.Request.Params["ID"];
                        SPDocumentLibrary doclib = (SPDocumentLibrary)web.GetList(SPUrlUtility.CombineUrl(web.Url, "/DocLib2/Forms/AllItems.aspx"));
                        SPListItem item = doclib.GetItemByUniqueId(new Guid(itemID));
                     }
                    catch (Exception ex)
                    {
                        //Выводим ошибку
                    }

                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite("http://kviten:83/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPUser currentUser = web.CurrentUser;
                    SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
                      try
                    {
                        string itemID = Page.Request.Params["ID"];
                        SPDocumentLibrary doclib = (SPDocumentLibrary)web.GetList(SPUrlUtility.CombineUrl(web.Url, "/Test_Doc_Lib/"));
                        SPListItem item = doclib.GetItemByUniqueId(new Guid(itemID));
                        //Break the role inheritance from List and remove any RoleAssignments
                        //item.BreakRoleInheritance(false);
                        //while (item.RoleAssignments.Count > 0)
                        //{
                        //    item.RoleAssignments.Remove(0);
                        //}
                        if (!item.HasUniqueRoleAssignments)
                        {
                            item.ResetRoleInheritance();
                            item.Update();
                            item.BreakRoleInheritance(false);
                            item.Update();
                        }
                            foreach (ListItem li in CheckBoxList1.Items)
                        {
                            if (li.Selected) //Response.Write("- " + li.Text + "<br/>");
                            {
                                // Give permissions to a specific group
                                SPGroup group = web.Groups.GetByID(Convert.ToInt32(li.Value));
                                SPPrincipal principalGroup = group;
                                SPRoleAssignment roleassignment_group = new SPRoleAssignment(group);
                                SPRoleAssignment roleAssignment = item.RoleAssignments.GetAssignmentByPrincipal(principalGroup);
                                item.RoleAssignments.Add(roleAssignment);
                                item.Update();
                            }
                        }
                   }

                   catch (Exception ex)
                   {
                        //Выводим ошибку
                    }
                    Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                    Context.Response.Flush();
                    Context.Response.End();
                }
            }
        }
            protected void btnCancel_Click(object sender, EventArgs e)
        {
            Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
            Context.Response.Flush();
            Context.Response.End();
         }
    }
}

I can not understand why I cannot assign permissions to the document! Help please!

share|improve this question
    
I see you call item.update() many times. In the past I have had issues that an item could not update due to the fact it was already busy updating. Try moving item.update to the last line of you 'Try'. Chances are that there is more to your issue but that's all I see. Good luck! –  user13186 Dec 28 '12 at 16:05
add comment

4 Answers

up vote 0 down vote accepted

The right solution for a web part:

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;
using Microsoft.SharePoint.Utilities;
namespace CustomGroupAssignment.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
           protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) { 
            using (SPSite site = new SPSite("http://kviten:83/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPUser currentUser = web.CurrentUser;
                    SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
                    SPGroupCollection webGroups = currentUser.Groups;
                    CheckBoxList1.DataSource = webGroups;
                    CheckBoxList1.DataValueField = "ID";
                    CheckBoxList1.DataTextField = "Name";
                    CheckBoxList1.DataBind();
                    foreach (ListItem li in CheckBoxList1.Items)
                    {
                        li.Selected = true;
                    }
                    try
                    {
                        string itemID = Page.Request.Params["ID"];
                        SPDocumentLibrary doclib = (SPDocumentLibrary)web.GetList(SPUrlUtility.CombineUrl(web.Url, "/DocLib2/Forms/AllItems.aspx"));
                        SPListItem item = doclib.GetItemByUniqueId(new Guid(itemID));
                    }
                    catch (Exception ex)
                    {
                        //Выводим ошибку
                    }
                }
                }
            }
        }

           protected void Button1_Click(object sender, EventArgs e)
           {
               using (SPSite site = new SPSite("http://kviten:83/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPUser currentUser = web.CurrentUser;
                    SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
                        string itemID = Page.Request.Params["ID"];
                        SPDocumentLibrary doclib = (SPDocumentLibrary)web.GetList(SPUrlUtility.CombineUrl(web.Url, "/Test_Doc_Lib/"));
                        SPListItem item = doclib.GetItemByUniqueId(new Guid(itemID));
               foreach (ListItem li in CheckBoxList1.Items)
               {
                   if (li.Selected) //Response.Write("- " + li.Text + "<br/>");
                   {
                                if (!item.HasUniqueRoleAssignments)
                                {
                                    item.ResetRoleInheritance();
                                    item.Update();
                                }
                                item.BreakRoleInheritance(false);
                                item.Update();
                                SPGroup group = web.Groups.GetByID(Convert.ToInt32(li.Value));
                                SPPrincipal principalGroup = (SPPrincipal)group;
                                //SPRoleAssignment roleassignment_group = new SPRoleAssignment(principalGroup);
                                SPRoleAssignment roleAssignment = item.Web.RoleAssignments.GetAssignmentByPrincipal(principalGroup);
                                item.RoleAssignments.Add(roleAssignment);
                                item.Update();
                               // var roleAssignment = new SPRoleAssignment(principalGroup);
                              //  item.RoleAssignments.Add(roleAssignment);
                               // item.Update();
                                }
                        }
               Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
               Context.Response.Flush();
               Context.Response.End();
                   }
               }
           }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
            Context.Response.Flush();
            Context.Response.End();
        }
    }
}
share|improve this answer
add comment

If you use the / / Response.Write ("-" + li.Text + "<br/>"); which commented out, we can see that the checkboxes are not selected and not displayed. item.ResetRoleInheritance(); executed and permission assigned to only the current user with no groups. In what could be the reason?

share|improve this answer
add comment

As sujested by timetoshine, you could use spsecurity but it is possible that even wouldnt work. If needs be that you need a system account privlages for the task you could use impersonation. spsecurity runs under the app ppol account where impersonation will run into any account you chose, in the link im using the system account as it will do what you want if the runwithelevatedpriv doesnt work :)

also just a side note, your creating two spsites and spwebs that are running differently to each other, so instead of creating new ones you could set on global spweb and spsite and call them respectively, so on your page load event its using the same spweb and spsite as the button event :)

SharePoint -access to path is denied

share|improve this answer
add comment

You should try putting your code within SPSecurity.RunWithElevatedPrivileges and also try web.AllowUnsafeUpdated = true; but set it to false once your code finishes execution.

I assume your not getting any kind of error neither in event receiver or ULS logs then it could be user who trying to change permissions doesn't actually has permission to change the permission if I make any sense :).

Hope it helps.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.