Thursday, October 27, 2011

PeopleEditor To SPFieldUserValueCollection

OBJECTIVE
To programmatically copy people selected from an asp.net People Editor to a SPFieldUserValueCollection field.

SPECIFICATION
The People Editor can contain multiple people, and allow Users and Groups selection.

SOLUTION
// myPeopleEditor is a PeopleEditor object in my asp.net form.

..
Item[“MyUserField”] = GetPeople(myPeopleEditor, Web);
..


private SPFieldUserValueCollection GetPeople(PeopleEditor people, SPWeb web)
{
  SPFieldUserValueCollection values = new SPFieldUserValueCollection();
  if (people.ResolvedEntities.Count > 0)
  {
    for (int counter = 0; counter < people.ResolvedEntities.Count; counter++)
    {
        PickerEntity user = (PickerEntity)people.ResolvedEntities[counter];
        switch ((string)user.EntityData["PrincipalType"])
        {
          case "User":
            SPUser webUser = web.EnsureUser(user.Key);
            SPFieldUserValue userValue = new SPFieldUserValue(web, webUser.ID, webUser.Name);
            values.Add(userValue);
          break;
 
          case "SharePointGroup":
            SPGroup siteGroup = web.SiteGroups[user.EntityData["AccountName"].ToString()];
            SPFieldUserValue groupValue = new SPFieldUserValue(web, siteGroup.ID, siteGroup.Name);
            values.Add(groupValue);                       
          break;
        }
      }
    }
    return values;
  }

Thursday, September 29, 2011

ECMAScript – Get Current Web ID

OBJECTIVE
To programmatically obtain the Current Web ID, with JavaScript Client Object Model.

NEEDS EXAMPLE
One wants to open a Page inside a SharePoint popup, and pass in query string the current Web ID.

SOLUTION
In this example it retrieves one list by Title from the Root Web.

<input onclick="javascript:init();" type="button" value="Task Selector"/>
<SharePoint:ScriptLink ID="ScriptLink1" Name="sp.js" runat="server" OnDemand="true" Localizable="false" />

<script type="text/ecmascript">
    var options;
        function portal_openModalDialog(pageUrl) {
            options = SP.UI.$create_DialogOptions();
            options.width = 600;
            options.height = 400;
            options.url = pageUrl;
            options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
            SP.UI.ModalDialog.showModalDialog(options);
        } 

        function CloseCallback(result, target) {
            location.reload(true);
        }

        function init()
        {
            var context = new SP.ClientContext.get_current();
            this.Web = context.get_web();
            context.load(this.Web);
            context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
                Function.createDelegate(this, this.onFail));
        }

        function onSuccess(sender, args)
        {
            portal_openModalDialog("http://myserver/Pages/default.aspx?WebID=" + this.Web.get_id());
        }

        function onFail(sender, args) {
            alert('Failed:' + args.get_message());
        }
</script>

Friday, August 19, 2011

Delete Roles from Site Permission programmatically

OBJECTIVE
How to remove Roles for:  single user, all users, groups or everybody.

The following is a variable used in the code:
-          Web: the SPWeb object of the sub site you want to manage.

1)       REMOVE ALL ROLES
2)       REMOVE ALL ROLES ONLY FOR USERS
3)       REMOVE ALL ROLES ONLY FOR GROUPS
4)       REMOVE SINGLE USER ROLES
5)       REMOVE A SPECIFIC ROLE DEFINITION FOR EVERYBODY
6)       REMOVE A SPECIFIC ROLE DEFINITION FOR A USER

 1) REMOVE ALL ROLES 

SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
{
    SPRoleAssColn.Remove(i);
}

2) REMOVE ALL ROLES ONLY FOR USERS 

       SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
       for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
       {
             SPRoleAssignment roleAssignmentSingle = SPRoleAssColn[i];
              System.Type t = roleAssignmentSingle.Member.GetType();
              if(t.Name=="SPUser")
                SPRoleAssColn.Remove(i);
}

3) REMOVE ALL ROLES ONLY FOR GROUPS 

       SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
       for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
       {
             SPRoleAssignment roleAssignmentSingle = SPRoleAssColn[i];
              System.Type t = roleAssignmentSingle.Member.GetType();
              if(t.Name=="SPGroup")
                SPRoleAssColn.Remove(i);
}

4) REMOVE SINGLE USER ROLES:     

        private void RemoveUserRoles(SPUser user)
        {
            SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
            for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
            {
                SPRoleAssignment roleAssignmentSingle = SPRoleAssColn[i];
                SPPrincipal wUser = (SPPrincipal)user;
                if (roleAssignmentSingle.Member.ID == wUser.ID)
                {
                    SPRoleAssColn.Remove(i);
                }
            }
        }

5) REMOVE SPECIFIC ROLE DEFINITION FOR EVERYBODY:
Ex. Remove the Read permission from all the people or groups 

        private static void RemoveSpecificRole(SPRoleType Role, SPWeb Web)
        {
            SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
            for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
            {
                SPRoleAssignment roleAssignmentSingle = SPRoleAssColn[i];
                for (int j = roleAssignmentSingle.RoleDefinitionBindings.Count -1; j>=0; j--)
                {
                    SPRoleDefinition roleDefinitionSingle =               roleAssignmentSingle.RoleDefinitionBindings[j];
                    if (roleDefinitionSingle.Type == Role)
                    {
                        roleAssignmentSingle.RoleDefinitionBindings.Remove(roleDefinitionSingle);
                        roleAssignmentSingle.Update();
                    }
                }
            }
        }


6) REMOVE SPECIFIC ROLE DEFINITION FOR A USER:
Ex. Remove the Contribute permission to a specific user. 

        private static void RemoveSpecificRoleForUser(SPUser user, SPRoleType Role, SPWeb Web)
        {
            SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
            for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
            {
                SPRoleAssignment roleAssignmentSingle = SPRoleAssColn[i];
                SPPrincipal wUser = (SPPrincipal)user;
                if (roleAssignmentSingle.Member.ID == wUser.ID)
                {
                     for (int j = roleAssignmentSingle.RoleDefinitionBindings.Count; j>=0; j--)
                    {
                        SPRoleDefinition roleDefinitionSingle = roleAssignmentSingle.RoleDefinitionBindings[j];
                        if (roleDefinitionSingle.Type == Role)
                        {
                            roleAssignmentSingle.RoleDefinitionBindings.Remove(roleDefinitionSingle);
                            roleAssignmentSingle.Update();
                        }
                    }
                }
            }
        }

Friday, August 5, 2011

Add an existing site collection Group to sub site with modified Roles

OBJECTIVE

The site collection contains a group named “All Members” with “Contributor” privilege.
I want to add this group programmatically to a sub site and modify its roles from “Contributor” to “Read” without modifying the original group.

The following are the variables used in the code:
       -          site: the SPSite object of the site collection being used
-          web: the SPWeb object of the sub site you want to add the group to.

SOLUTION:
SPGroup group = site.RootWeb.SiteGroups["All Members"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
SPRoleDefinition roleDefinition = site.RootWeb.RoleDefinitions["Read"];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
if (!web.HasUniqueRoleAssignments)
     web.BreakRoleInheritance(true);
web.RoleAssignments.Add(roleAssignment);

---------------------------------------------------------------------------

Working with Group: quick review:
      1)       BREAK INHERITANCE  
         2)       ADD NEW GROUP TO SITE COLLECTION
         3)       ASSOCIATE THE NEW GROUP TO A WEB
         4)       ASSIGNMENT OF THE ROLES
         5)       ADD USERS TO THE GROUP
         6)       REMOVE ALL ROLES
     

1) BREAK INHERITANCE
if (!web.HasUniqueRoleAssignments)
            web.BreakRoleInheritance(true);

2) ADD NEW GROUP TO SITE COLLECTION:
web.SiteGroups.Add("MyNewGroup", web.AssociatedOwnerGroup, null, "MyNewGroup description");

3) ASSOCIATE THE NEW GROUP TO A WEB:
web.AssociatedGroups.Add(group);
web.Update();

4) ASSIGNMENT OF THE ROLES:
SPGroup group = web.SiteGroups["MyNewGroup"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
SPRoleDefinition roleDefinition = site.RootWeb.RoleDefinitions["Read"];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
web.RoleAssignments.Add(roleAssignment);

5) ADD USERS TO THE GROUP:
SPUser user = web.EnsureUser("domain\MyUser");
SPGroup group = web.Groups["MyNewGroup"];                       
if(user!=null && group!=null)
     group.AddUser(user);

6) REMOVE ALL ROLES:
SPRoleAssignmentCollection SPRoleAssColn = web.RoleAssignments;
for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
{
      SPRoleAssColn.Remove(i);
}    




Friday, May 6, 2011

ECMAScript - How to get lists

OBJECTIVE
To show different ways to retrieve lists:
  1)       RETRIVING CURRENT LIST
   2)       RETRIVING LIST BY ‘TITLE’
  3)       RETRIVING LIST BY ‘ID’
  4)       RETRIVING ALL LISTS
   5)       RETRIVING A SINGLE PROPERTY FROM LISTS


1) RETRIVING CURRENT LIST
When you are working with lists (ex by Ribbon Button), sometime it is necessary to know the current list by client side.
If you are working with the standard view, you can use it:

  var list = SP.ListOperation.Selection.getSelectedList();

Instead if you are working in datasheet, you may have some problems. At the following link it is suggested a workaround http://msdn.microsoft.com/en-us/library/ff410971.aspx.
 


2) RETRIVING LIST BY ‘TITLE’
In this example it retrieves one list by Title from the Root Web.


<script type="text/ecmascript">

    SP.SOD.executeOrDelayUntilScriptLoaded(initialize, 'SP.js');   

    function initialize() {
        var clientContext = new SP.ClientContext();
        var siteColl = clientContext.get_site();
        myweb = siteColl.get_rootWeb();
        this.list = myweb.get_lists().getByTitle('ListTitle'); //Edit the title
        clientContext.load(list);
        clientContext.executeQueryAsync(Function.createDelegate(this, GetList), Function.createDelegate(this, getFailed));
    }

    function GetList() {
            alert(list.get_title() + ': ' + list.get_id().toString());
    }
  
    function getFailed() {
        alert('Failed.');
    }
</script>



3) RETRIVING LIST BY ‘ID’
In this example it retrieves one list by Id from the Root Web.

<script type="text/ecmascript">

    SP.SOD.executeOrDelayUntilScriptLoaded(initialize, 'SP.js');

    function initialize() {
        var value = SP.ListOperation.Selection.getSelectedList(); 
        var clientContext = new SP.ClientContext();
        var siteColl = clientContext.get_site();
        this.myweb = siteColl.get_rootWeb();
        this.list = myweb.get_lists().getById('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'); //Edit the ID
        clientContext.load(list);
        clientContext.executeQueryAsync(Function.createDelegate(this, GetList), Function.createDelegate(this, getFailed));
    } 

    function GetList() {
        alert(list.get_title() + ': ' + list.get_id().toString());
    } 

    function getFailed() {
        alert('Failed.');
    } 

</script>
 


4) RETRIVING ALL LISTS
In this example it retrieves all the lists in the Root Web

<script type="text/ecmascript">
   
    SP.SOD.executeOrDelayUntilScriptLoaded(initialize, 'SP.js');   

    function initialize() {
        var clientContext = new SP.ClientContext();
        var siteColl = clientContext.get_site();
        myweb = siteColl.get_rootWeb();
        this.lists = myweb.get_lists();
        clientContext.load(lists);
        clientContext.executeQueryAsync(Function.createDelegate(this, GetLists), Function.createDelegate(this, getFailed));
    }

    function GetLists() {
        var listEnumerator = lists.getEnumerator();
        while (listEnumerator.moveNext()) {
            list = listEnumerator.get_current();
            alert(list.get_title());
        }
    }

    function getFailed() {
        alert('Failed.');
    }
</script>



5) RETRIVING A SINGLE PROPERTY FROM LISTS
When you retrieve a list or a collection of list, you can choice what properties you want.  In this example it retrieves the ID for all the lists in the root web.
<script type="text/ecmascript">
   
    SP.SOD.executeOrDelayUntilScriptLoaded(initialize, 'SP.js');   

    function initialize() {
        var clientContext = new SP.ClientContext();
        var siteColl = clientContext.get_site();
        myweb = siteColl.get_rootWeb();
        this.lists = myweb.get_lists();
        clientContext.load(lists, 'Include(Id)');
        clientContext.executeQueryAsync(Function.createDelegate(this, GetLists), Function.createDelegate(this, getFailed));
    }

    function GetLists() {
        var listEnumerator = lists.getEnumerator();
        while (listEnumerator.moveNext()) {
            list = listEnumerator.get_current();
            alert(list.get_id());
        }
    }
 
    function getFailed() {
        alert('Failed.');
    }  
</script>


Monday, May 2, 2011

Sandbox Solution Limitations: Workarounds.

1) Cannot use Visual Web Part    
      You can!
      Install the Visual Studio 2010 SharePoint Power Tools:         
     http://visualstudiogallery.msdn.microsoft.com/8e602a8c-6714-4549-9e95-f3700344b0d9/
     ant you will find a new "Visual Web Part (Sandboxed)" template.


 
2) Cannot deploy files on layouts folder
     You can use a Module to deploy files on your application, without using Document Library.


     You can read the files appending the Module URL to your site collection URL:
     http://[MyHostName]/[MySiteCollection]/MyFiles/js/jquery-1.4.4.min.js

3) Cannot use Application Pages with code behind
      You can deploy an application page using a Module and add a Sandboxed Web Part to use code behind.
       SharePoint offers a specific class name <WebPartPages:SPUserCodeWebPart > to archives this goal.
       At the following link you can find a good example:
       http://www.wictorwilen.se/Post/Custom-application-pages-in-the-SharePoint-2010-Sandbox.aspx

Thursday, April 28, 2011

Enable Ribbon button when one item only is selected and it is not folder

Objective:
To programmatically enable a ribbon button by JavaScript, when one item only is selected.

Solution:
Edit the element.xml file of the Ribbon button Custom Action.
In the CommandUIHandles section

<CommandUIHandlers>
        <CommandUIHandler
                Command="CommandName"
                CommandAction=""
                EnabledScript=" …  "/>
      </CommandUIHandlers>
</CommandUIHandlers>

Add the following JavaScript code in EnabledScript:

EnabledScript="javascript:
        function enable() {
        var items = SP.ListOperation.Selection.getSelectedItems();
        var itemCount = CountDictionary(items);
        return (itemCount==1 &amp;&amp; items[0].fsObjType == 0);
        }enable();

itemCount==1  is used to identify if one item only is selected

If this condition is TRUE it means that the “items” array contains the element 0.
So it is possible to test if is it a folder with the following:

 items[0].fsObjType == 0

If you write you JavaScript code in the Element.xml file, you need to encode the operator AND: &amp;&amp;