Linking to auto-join Group in SharePoint

Another question from a forum user:

"I am trying to create a link that will reproduce the same functionality that exists for the "Join Group" menu option when working with a SharePoint security Group.  I want to allow members to be able to Request Membership to a Specific SharePoint Group.  The group is set up to auto-accept.  The administrators of the site\group send out e-mails to members of the group.  For that reason we do not include everyone in the group by default.  But if they request access, they should be auto-approved.  Rather than trying to explain to users how to navigate to the Group Page where the "Action"-> "Join Group" menu option is, I would like to create a link from the home page to re-create the same functionality.

Any ideas? "

Why of course!

To understand how the link works we need to dig a bit. In contrast with regular Action links, the Join Group is not a CustomAction, which would have been too simple. Rather, the Join Group and Leave Group links are created only in the people.aspx page itself.

On opening that file we quickly find (search for Join or Leave group in the source) that the functionality is a JavaScript function call to JoinLeaveGroupClick(). That function in turn fires, through PostBack, an event receiver for the button. So we need to dig into the page code to find more.

.Net reflector to the rescue!

The ASPX page reveals that the page inherits the Microsoft.SharePoint.ApplicationPages.PeoplePage class. Using .Net reflector we open the Microsoft.SharePoint.ApplicationPages dll, usually located in [12]\CONFIG\BIN\Microsoft.SharePoint.ApplicationPages.dll. Browsing to the PeoplePage class we find the method that is fired:

BtnJoinLeaveGroup_Click

Click on that method reveals the following code:

protected void BtnJoinLeaveGroup_Click(object sender, EventArgs e)
{
    string str;
    if (!this.CurrentGroup.AutoAcceptRequestToJoinLeave)
    {
        str = "reqgroup.aspx?Group=" + SPHttpUtility.UrlKeyValueEncode(this.CurrentGroup.Name);
    }
    else
    {
        str = "reqgroupconfirm.aspx?Action=";
        if (!this.CurrentGroup.ExplicitlyContainsCurrentUser)
        {
            this.CurrentGroup.AddUser(base.Web.CurrentUser);
            str = str + "Join&";
        }
        else
        {
            this.CurrentGroup.RemoveUser(base.Web.CurrentUser);
            str = str + "Leave&";
        }
        str = str + SPHttpUtility.UrlKeyValueEncode("Group", this.CurrentGroup.Name);
    }
    SPUtility.Redirect(str + "&" + SPHttpUtility.UrlKeyValueEncode("Source", SPHttpUtility.UrlPathEncode(base.CurrentRequestUrlAndQuery, false)), SPRedirectFlags.RelativeToLayoutsPage, this.Context);
}

From this we see that there is no Url that is used to add a user, but rather a method call to the SPGroup.Adduser method. Doh! No simple linking possible.

Or is it…?

To mimic the functionality we need to add a new page to hold the code for adding a user to a group. Since we have reflected the dll we know a bit about how that code should look as well, so let’s get down to business.

Creating a page to add users automatically

Start by creating a regular SharePoint application page using your favorite authoring tool. Since all we want to do is to add a user to a group, we just need to override the OnLoad method. Add the following to your .aspx file:

<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@ Page Language="C#" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" MasterPageFile="~/_layouts/application.master"      %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Import Namespace="Microsoft.SharePoint" %>

Of course, this doesn’t actually do anything, so we need to modify the overridden method. Substitute base.Onload(e); with this (Comments inline to explain what is going on):

protected override void OnLoad(EventArgs e)
{
    SPWeb web = SPContext.Current.Web;
    SPGroup currentGroup;
    // Get group id from query string
    string groupName = this.Page.Request["GroupName"];
    // Find Url to redirect user after addition
    string referringPage = "";
    if (this.Page.Request.UrlReferrer != null)
    {
        referringPage = this.Page.Request.UrlReferrer.ToString();
    }
    else
    {
        // Redirect to root url if direct link
        // You might want to modify this behavior
        referringPage = web.ServerRelativeUrl;
    }
    // Get reference to current web and group
    try
    {
        currentGroup = web.Groups[groupName];
    }
    catch (Exception ex)
    {
        throw new SPException(ex.Message);
    }
    // Add current user to group. Must allow unsafe updates since we are doing this through GET
    web.AllowUnsafeUpdates = true;
    currentGroup.AddUser(web.CurrentUser);
    web.AllowUnsafeUpdates = false;
    // Redirect user back to previous page.
    this.Page.Response.Redirect(referringPage);

}

Right. That should handle our code, so just save the file to the [12]\LAYOUTS directory, and add a link to test. You link should look something like this:

CustomAddUserToGroup.aspx?GroupName=MySite%20Members

Note that an automatic adding to a group, such as this, requires that you have both set the "Allow reque
sts to join/leave this group? " and "Auto-accept requests?" to Yes. You can do this on the Group Settings page.

You might also want to improve on the code, add better error and exception handling, modifying the functionality of redirects, etc. but I will leave that as an exercise to you.

Let me know if you have problems.

.b

Tags: , , ,

Post Author

This post was written by who has written 301 posts on Furuknap's SharePoint Corner.

15 Responses to “Linking to auto-join Group in SharePoint”

  1. Phil December 2, 2008 at 6:06 pm #

    Unfortunately my users seem to get a “Access Denied” message when getting to the AddUser code. :(

  2. Phil December 2, 2008 at 11:33 pm #

    The line

    currentGroup = web.Groups[groupName];

    should be changed to web.SiteGroups in order for the user to be added to a group that does not exist within the current site context. This seemed to fix my issue.

  3. Bjørn Furuknap December 5, 2008 at 8:38 pm #

    Thanks for the tip.

    In order for the SPGroup.AddUser to work you need to have the group automatically accept new requests.

    As you correctly point out, if the group is not the current web, ie site, you must instead find the correct SPGroup using the SiteGroups collection.

    This is very often the case with subsites where you have opted on site creation to inherit permissions from the parent site. In those cases the only groups available to the child site are those of the parent, which would be stored in the SiteGroups collection.

    Thanks again, great tip!

    .b

  4. Stas Sharov December 10, 2008 at 9:06 am #

    When I’ve made this aspx-page there was an error “cannot find a specified group”. I don’t know why. I unsuccessfully tried to return in catch-block specified group name: SharePoint returned “unknown error”. So I canceled changes in code but it doesn’t took effect – “unknown error” again! Why? Even after deleting aspx page from layouts directory or creating new aspx page with full copy of people.aspx file “unknown error” occured. IIS has allways restarted

  5. Kyle August 5, 2009 at 1:33 am #

    YOU DA MAN!!!!!

  6. Anonymous September 10, 2009 at 7:32 pm #

    It's just what I need. I use the Sharepoint but I'm not good programmer ;-) . I use Sharepoint Designer to make workflow, this might serve me to create my page CustomAddUserToGroup.aspx, in which directory , change the code.?
    Thank you.

  7. Anonymous September 10, 2009 at 7:37 pm #

    It's just what I need. I use the Sharepoint but I'm not good programmer ;-) . I use Sharepoint Designer to make workflow, this might serve me to create my page CustomAddUserToGroup.aspx, in which directory , change the code.?
    Thank you.

  8. Ruslan J December 1, 2009 at 8:04 pm #

    I also created a second page CustomRemoveUserFromGroup.aspx and changed the code to currentGroup.RemoveUser and it works great as well, thanks for the tip!

  9. Rajarajeswaran.S February 11, 2010 at 1:43 pm #

    Hi

    I am getting error "The parameter name cannot be empty or bigger than 255 characters " while using this code. Please let me know if anyone came across this issue.

    Thanks
    Raja

  10. Kyla Ensor February 24, 2010 at 5:43 pm #

    Could you provide the full sample code? I'm unable to replicate your result from the above… Thanks.

  11. Amir November 2, 2010 at 10:54 am #

    This is very helpful! Thank you!

  12. Kris November 29, 2011 at 5:33 pm #

    Hi I cannot find where you would put this code in the ASPX page, it doesn’t explain it very clearly, can anyone help, it is much appreciated.
    Kris

  13. Bjørn Furuknap
    Twitter:
    November 29, 2011 at 6:31 pm #

    Kris,

    I’m not sure what you mean by ‘where to put the code’. Are you uncertain where to put the onload override? If so, I think you may want to start at something simpler, as this is ASP.NET 101.

    .b

  14. Kris November 30, 2011 at 10:03 am #

    Bjorn,
    I am wishing to create a link where users can join / leave a notification group, I have set up in sharepoint designer a workflow to trigger when a new event occurs, I want users to be able to leave the notification group if they no long want to be informed, or likewise join the notification group on the events page.

    My scenario is that when an event is created in a calendar an email is sent to the notification group, within this email there is an option to stop notification etc.
    A the moment the user would have to be redirected to said group, click action, leave group.
    I’ve set the notification group to auto accept / leave the group so it would be ideal just to ‘click’ the link.

    Can you help :-)
    p.s I am using sharepoint designer, I do have Visual Studio 2008 but not sure how to use this with a sharepoint site

    • Bjørn Furuknap
      Twitter:
      December 7, 2011 at 7:41 pm #

      For this solution to work, you definitely want to go with Visual Studio…

      .b

Leave a Reply

  • RSS
  • Facebook
  • Twitter