Shahbas, here is the code:
private static void SetSecurityOnSubSite(ClientContext clientContext, ListItem item, bool confidential, Web newWeb)
{
try
{
if (confidential)
{
newWeb.BreakRoleInheritance(false, false);
clientContext.ExecuteQuery();
Group ownerGroup = default(Group); Group memberGroup = default(Group); Group visitorGroup = default(Group);
// web has unique permissions, so create default assosiated groups (owners, members, visitors)
if (!newWeb.GroupExists(newWeb.Title + " Owners"))
{
ownerGroup = newWeb.AddGroup(newWeb.Title + " Owners", "", true);
clientContext.Load(ownerGroup);
}
if (!newWeb.GroupExists(newWeb.Title + " Members"))
{
memberGroup = newWeb.AddGroup(newWeb.Title + " Members", "", false);
clientContext.Load(memberGroup);
}
if (!newWeb.GroupExists(newWeb.Title + " Visitors"))
{
visitorGroup = newWeb.AddGroup(newWeb.Title + " Visitors", "", false);
clientContext.Load(visitorGroup);
}
// executequery in order to load the groups if not null
clientContext.ExecuteQuery();
newWeb.AssociateDefaultGroups(ownerGroup, memberGroup, visitorGroup);
newWeb.AddPermissionLevelToGroup(newWeb.Title + " Owners", RoleType.Administrator);
newWeb.AddPermissionLevelToGroup(newWeb.Title + " Members", RoleType.Contributor);
newWeb.AddPermissionLevelToGroup(newWeb.Title + " Visitors", RoleType.Reader);
FieldUserValue userValueCreatedBy = item[Constants.Projects.CreatedBy] as FieldUserValue;
User createdByUser = clientContext.Web.EnsureUser(userValueCreatedBy.LookupValue);
clientContext.Load(createdByUser);
clientContext.ExecuteQuery();
UserCreationInformation createdByUserCI = new UserCreationInformation();
createdByUserCI.LoginName = createdByUser.LoginName;
ownerGroup.Users.Add(createdByUserCI);
clientContext.ExecuteQuery();
foreach (FieldUserValue userValue in item[Constants.Projects.ProjectTeam] as FieldUserValue[])
{
User user = clientContext.Web.EnsureUser(userValue.LookupValue);
clientContext.Load(user);
clientContext.ExecuteQuery();
UserCreationInformation userCI = new UserCreationInformation();
userCI.LoginName = user.LoginName;
memberGroup.Users.Add(userCI);
}
clientContext.ExecuteQuery();
}
}
catch (Exception)
{
throw;
}
}
Reference link:
http://sharepoint.stackexchange.com/questions/116682/how-to-create-a-group-in-a-subweb-using-csom