Wednesday, February 10, 2010

0210: SP User

1.Obtaining and Displaying Users of a Site

SPSite site = new SPSite(siteUrl);
SPWeb web = site.AllWebs[webName];

foreach (SPGroup group in web.SiteGroups)
{
// Step 4: Get list of all users in this
// and add to data table
foreach (SPUser user in group.Users)
{
foreach (SPRole role in SPUser.Roles)
{

 

2.Adding Users to a Site by Using the Object Model

//Step 3a: Get handle to specified site collection and web site
SPSite site = new SPSite(args[0]);
SPWeb web = site.AllWebs[args[1]];
//Step 3b: Add the user to the specified site group
web.SiteGroups[args[6]].AddUser(args[

 

3. Adding Users and Groups to a Site by Using the
Web Services

 

http://[SharePoint server]/_vti_bin/UserGroup.asmx

 

UserGroupService.UserGroup objUserGroup =
new UserGroupService.UserGroup();

4.Adding Groups to a Site by Using the Object Model

 

SPSite site = new SPSite(args[0]);
SPWeb web = site.AllWebs[args[1]];

web.SiteGroups.Add(args[2], web.SiteUsers[args[
web.SiteUsers[args[4]], args[5]);

5.Adding Roles to a Web Site by Using the Object
Mode

 

SPSite site = new SPSite(r.SiteUr);
SPWeb web = site.AllWebs[r.WebName];
web.AllowUnsafeUpdates = true;

SPRoleDefinitionCollection roles = web.RoleDefinitions;
//Step 4: Create a new role using information passed in
SPRoleDefinition role = new SPRoleDefinition();

roles.Add(role)

 

6.Adding Roles to a Web Site by Using the Web Services

http://[server name]/_vti_bin/usergroup.asmx

UserGroupService.UserGroup objUserGroup =
new UserGroupService.UserGroup();

//Get permissionflag by rolename

// Step 1: Default to NO permissions
ulong permissionFlags = (ulong)SPBasePermissions.EmptyMask;
// Step 2: Get list of all current roles for this web site
XmlNode xnRoles = objUserGroup.GetRoleCollectionFromWeb();
// Step 3: Even though we're using the web service to update
// the roles collection, we can use the built-in enum
// type to get the numeric values of the various base
// permissions.
SPBasePermissions enumBasePermissions =
new SPBasePermissions();
string[] arrBasePermissionNames =
System.Enum.GetNames(enumBasePermissions.GetType());
ulong[] arrBasePermissionValues =
(ulong[])System.Enum.GetValues(enumBasePermissions.GetType());
// Step 4: Loop through all current roles in target site
// finding the role for which we want to duplicate permission
// flags.

foreach (XmlNode xnRole in xnRoles.FirstChild.ChildNodes)
{
if (xnRole.Attributes["Name"].Value.ToString().ToLower()
== strRoleName.ToLower())
{
// Turn the comma-delimited list of base permission
// names into an array so we can iterate through them
string[] arrPermission =
xnRole.Attributes["BasePermissions"].Value.ToString().Split(',');
// Iterate through the complete list of base permissions to
// find the entry that matches the base permission
// from our template role
for (int i = 0; i < arrPermission.Length; i++)
for (int j = 0; j < arrBasePermissionNames.Length; j++)
// When we've found our base permission, "OR" its
// numeric value with that of any other base
// permissions to create the complete set of values
if (arrPermission[i].Trim() ==
arrBasePermissionNames[j])
permissionFlags = permissionFlags |
arrBasePermissionValues[j];
}
}
return permissionFlags;
}

 

 

 

//Add role

 

objUserGroup.AddRoleDef(txtRoleName.Text,
txtRoleDefinition.Text, permissionFlags);

 

7.Adding Users to Active Directory with a created web service

 

public class Service : System.Web.Services.WebService
{
    //The LDAP connection string needs to match the domain you'll
    //be adding users to. For example, the below connection string
    //applies to a domain called 'test.domain', and will save new
    //user accounts in the 'NewUsers' organizational unit folder.
    const string LDAP_CONNECTION_STRING = "LDAP://OU=NewUsers,DC=test,DC=domain";
    //AD sets account flags by "AND'ing" together various numeric
    //values stored in HEX. The following are the base-10
    //integer representations of the HEX values for the flags we
    //want to set.
    const int AD_ENABLED = 512;
    const int AD_DISABLED = 514;
    const int AD_NEVER_EXPIRE = 65536;
    [WebMethod()]
    public DataTable AddUserToAD(string strAlias, string strName, string strCompany, string strEmail, string strPhone, string strNotes)
    {
        string strMsg = "";
        //Step 1: Verify that alias was provided
        if (strAlias == "") {
            strMsg = strMsg + "Valid user alias required";
        }
        else {
            //Step 2: Instantiate a Directory Entry Object to represent the "Extranet" folder
            DirectoryEntry adUserFolder = new DirectoryEntry(LDAP_CONNECTION_STRING);
            DirectoryEntry newADUser = new DirectoryEntry();
            DirectoryEntry existingADUser = new DirectoryEntry();
            //Step 3: Check to make sure the folder is a "organizational unit" object
            try {
                if (adUserFolder.SchemaEntry.Name == "organizationalUnit") {
                    //Create a directory entry to represent the new user
                    newADUser = adUserFolder.Children.Add("CN=" + strAlias, "User");
                    //If already a user with this alias, set the fields to data for
                    //this user and return message
                    if (DirectoryEntry.Exists(newADUser.Path)) {
                        existingADUser = adUserFolder.Children.Find("CN=" + strAlias, "User");
                        strName = (string)existingADUser.Properties["displayName"].Value;
                        strCompany = (string)existingADUser.Properties["company"].Value;
                        strNotes = (string)existingADUser.Properties["mail"].Value;
                        strPhone = (string)existingADUser.Properties["telephoneNumber"].Value;
                        strNotes = (string)existingADUser.Properties["comment"].Value;
                        strMsg = "User '" + strAlias + "' already exists in Active Directory";
                    }
                    else {
                        //Step 4: Save caller-supplied properties
                        newADUser.Properties["sAMAccountName"].Add(strAlias + "");
                        newADUser.Properties["displayName"].Add(strName + "");
                        newADUser.Properties["company"].Add(strCompany + "");
                        newADUser.Properties["mail"].Add(strEmail + "");
                        newADUser.Properties["telephoneNumber"].Add(strPhone + "");
                        newADUser.Properties["comment"].Add(strNotes + "");
                        newADUser.Properties["info"].Value = "New SharePoint User";
                        newADUser.CommitChanges();
                        //Step 5: Set the password using the "Invoke" method.
                        newADUser.Invoke("setPassword", "P@ssW0rd");
                        //Step 6: Enable the user, set account to never expire
                        newADUser.Properties["userAccountControl"].Value = AD_NEVER_EXPIRE + AD_ENABLED;
                        newADUser.CommitChanges();
                        strMsg = "User '" + strAlias + "' successfully added to Active Directory";
                    }
                }
            }
            catch (Exception ex) {
                //Step 7: return error message
                strMsg = "User '" + strName + "' could not be added to Active Directory due to the following error: " + ex.Message;
            }
        }
        //Step 8: Construct a dataset to return values
        DataTable dtReturn = new DataTable("result");
        dtReturn.Columns.Add("Alias");
        dtReturn.Columns.Add("Name");
        dtReturn.Columns.Add("Company");
        dtReturn.Columns.Add("Phone");
        dtReturn.Columns.Add("Email");
        dtReturn.Columns.Add("Notes");
        dtReturn.Columns.Add("Message");
        //Add a single row to the data table to contain
        //information describing the results of the method call
        DataRow drReturn = dtReturn.NewRow();
        drReturn["Alias"] = strAlias;
        drReturn["Name"] = strName;
        drReturn["Company"] = strCompany;
        drReturn["Phone"] = strPhone;
        drReturn["Email"] = strEmail;
        drReturn["Notes"] = strNotes;
        drReturn["Message"] = strMsg;
        dtReturn.Rows.Add(drReturn);
        dtReturn.AcceptChanges();
        return dtReturn.Copy();
    }
}

0 Comments:

Post a Comment

<< Home