1

Here is my Event Receiver to redirected to my visual web part:

   public override void ItemAdding(SPItemEventProperties properties)
   {
       base.ItemAdding(properties);

       properties.Cancel = true;
       properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
       properties.RedirectUrl = "/SitePages/test_aspx.aspx";

   }

Hi this is my visual web part:

public partial class VisualWebPart1UserControl : UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

        SPSite site = new SPSite(SPContext.Current.Web.Url);
        SPWeb web = site.OpenWeb();
        SPUser currentUser = web.CurrentUser;
        SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
        //            CheckBoxList1 = new CheckBoxList();
        SPGroupCollection webGroups = currentUser.Groups;
        CheckBoxList1.DataSource = webGroups;
        CheckBoxList1.DataValueField = "ID";
        CheckBoxList1.DataTextField = "Name";
        CheckBoxList1.DataBind();

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        SPSite site = new SPSite(SPContext.Current.Web.Url);
        SPWeb web = site.OpenWeb();
        SPUser currentUser = web.CurrentUser;
        SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];

    //    SPListItem thisItem = properties.ListItem;
       // SPListItem employeeItem = docLib.GetItemById(ID);
        // Query the second list for the item
        SPQuery myQuery = new SPQuery();
        myQuery.Query = "<Where><Eq><FieldRef Name = \"ID\"/>" +
        "<Value Type = \"Text\">";

        // Get a collection of the second list items selected by the query and pick the first (0) value as it should only return one!
        SPListItemCollection secondlistItemCol = docLib.GetItems(myQuery);
        SPListItem secondItem = secondlistItemCol[0];

        SPGroupCollection webGroups = currentUser.Groups;
        CheckBoxList1.DataSource = webGroups;
        CheckBoxList1.DataValueField = "ID";
        CheckBoxList1.DataTextField = "Name";
        CheckBoxList1.DataBind();

        //Break the role inheritance from List and remove any RoleAssignments
        secondItem.BreakRoleInheritance(false);
        while (secondItem.RoleAssignments.Count > 0)
        {
            secondItem.RoleAssignments.Remove(0);
        }

        foreach (ListItem li in CheckBoxList1.Items)
        {
           if (li.Selected)
           {
                // 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 = docLib.RoleAssignments.GetAssignmentByPrincipal(principalGroup);

                secondItem.RoleAssignments.Add(roleAssignment);
            }
        }
    }
}

In a visual web part i'm getting list of group of current user. The user selects the necessary groups and presses a button save. After that assigns the rights to documents according to selected groups. How do I get the selected groups to assign permissions to a document? And how do I assign the rights to the just created document? Please help me. If there are examples show please.

0

2 Answers 2

1

New Event Receiver: ` using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; using System.Web; using System.Security.Permissions; using Microsoft.SharePoint.Security; using Microsoft.SharePoint.Utilities; using Microsoft.SharePoint.Workflow;

namespace ItemAdding.EventReceiver1 { /// /// События элемента списка /// public class EventReceiver1 : SPItemEventReceiver {

   private HttpContext _context;
   public EventReceiver1 ()
  {
   _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 + "/SitePages/test_aspx.aspx?ID=" + fileUploded.UniqueId;
   }

}

} ` And new visual web form:

try { SPWeb web = SPContext.Current.Web; 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)); } catch (Exception ex) { }

But when creating a document, event handler throws an error in a string: HttpPostedFile file = _context.Request.Files[0]; error: "In an instance of Object reference not set to an object." What could it be? Help please.

0

I presume that your looking for somthing like this:

using (SPSite site = new SPSite(siteCollection))
{  
     using (SPWeb web = site.OpenWeb(siteName))  
     {    
         SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists[libraryName];    
         //Get folder    
         SPListItem item = docLib.Folders[1];    
         if (!item.HasUniqueRoleAssignments)     
              item.BreakRoleInheritance(true);    
              SPRoleAssignment roleAssignment = new SPRoleAssignment(group);          
              SPRoleDefinition roleDefination = web.RoleDefinitions["Contribute"];    
              roleAssignment.RoleDefinitionBindings.Add(roleDefination);    
              item.RoleAssignments.Add(roleAssignment);    
              item.Update();  
      }
}

taken from here:

http://sridharu.blogspot.co.uk/2008/12/sharepoint-assigning-permission.html#!/2008/12/sharepoint-assigning-permission.html

also on checking permissions

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spdocumentlibrary.doesuserhavepermissions.aspx

and another tut

http://blog.sharedove.com/adisjugo/index.php/2011/06/11/managing-user-roles-and-permissions-through-sharepoint-object-model-in-sharepoint-2010/

hope this helps :)

2
  • But this code to assign rights to a folder, but I need to assign rights to just created the document. How do I do that?
    – alien_ru
    Dec 24, 2012 at 11:56
  • i think this is more inline what your looking for: mindfiresolutions.com/… you can try this also, you need to get the document in the list (splist) find which document and assign its permission social.msdn.microsoft.com/Forums/en-US/…
    – Ali Jafer
    Dec 24, 2012 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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