Check if specified user belongs to specific group or not - sharepoint

I posted this question on SharePoint exchange but it did not get any attention. Any help will be appreciated.
I have implemented a site and have added a SharePoint group called "SG_Uploader".
In this group, I ONLY have one Active Directory group called "AD_L6" and there are many users in AD_L6.
If a user comes to site and I want to check if he can upload a document, I use below code which is very simple:
SPWeb web = // ...
SPGroup group = web.SiteGroups["SG_Uploader"];
if (group.ContainsCurrentUser)
{
// allow user to upload
}
Now, I want to do the same thing, not for current user but for a specific user that I have his username. By that mean I want to write a code like
SPWeb web = // ...
SPGroup group = web.SiteGroups["SG_Uploader"];
if (group.ContainsUser(username))
{
// allow user to upload
}
I could not figure out who I can do that. Please advise.

The following code for your reference.
var username = "user1";
var spGroupName = "SG_Uploader";
var adGroupName = "AD_L6";
using (SPSite spSite = new SPSite("http://sp2013/sites/team/"))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
SPUser user = spWeb.EnsureUser(adGroupName);
if (user.Groups.Cast<SPGroup>().Any(g => g.Name.Equals(spGroupName)))
{
var principalContext = new PrincipalContext(ContextType.Domain);
var group = GroupPrincipal.FindByIdentity(principalContext, adGroupName);
var isGroupMember = group.Members.Any(x => x.Name == username);
if (isGroupMember)
{
Console.WriteLine("User " + username + " is a member of group " + spGroupName);
}
else
{
Console.WriteLine("User " + username + " is not a member of group "+spGroupName);
}
}
}
}

You can do that.
string userName = "PERSEUS\\dmitry.kaloshin";
string groupName = "Home Members";
using (SPSite spSite = new SPSite("http://perseus"))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
SPUser user = spWeb.EnsureUser(userName);
if (user.Groups.Cast<SPGroup>().Any(g => g.Name.Equals(groupName)))
{
Console.WriteLine("User " + userName + " is a member of group " + groupName);
}
else
{
Console.WriteLine("User " + userName + " is NOT a member of group " + groupName);
}
}
}
Visit https://social.msdn.microsoft.com/Forums/office/en-US/65066c08-9924-4935-9bba-f715b75d3fac/how-to-check-if-user-exists-in-a-particular-sharepoint-group-or-not-programatically?forum=sharepointdevelopmentprevious

Related

mapping/migrating sharepoint users

I am currently working on a sharepoint migration on a test environment, and have now come to the point where I would like to map/migrate my existing Ad groups and users from SP 2010 to SP 2013. Now when researching this I find alot of vague information but nothing very solid concerning this matter. How would I best go about this.
Let's say I have following users in a csv file representing the users on the SP 2010 environment:
c:0!.s|windows
i:0#.w|domainhere\administrator
i:0#.w|domainhere\apservice
i:0#.w|domainhere\koen
NT AUTHORITY\LOCAL SERVICE
SHAREPOINT\system
Domainhere\APService
Should I write a powershell script somehing which resembles the following
$csv = Import-CSV ".\sites-default.csv"
$web = Get-SPWeb = "https://mymachine.mydomain"
foreach($row in $csv)
{
#You could do this to format your account name if not already in the csv
$username = "Domain\" + $row.key
$web.EnsureUser($username)
$group = $web.SiteGroups |?{$_.name -eq "GROUPNAME"}
Set-SPUser -identity $username -web $web.url -group $group
}
Or are they better ways to do this kind of matter?
I have some code that works in C# using CSOM. It reads the permissions from all lists (document libraries also are lists) and the site level and writes them to an excel.
Then it reads the permissions from Excel and puts them on the new SharePoint.
The Excel uses using OfficeOpenXml;
The model
public class PermissionsToExcel
{
public string ListTitle { get; set; }
public string Gebruikersnaam { get; set; }
public string Rechten { get; set; }
public string ListUrl { get; set; }
public bool HasUniqueRoleAssignments { get; set; }
}
The code that gets the groups and their permissions from each list:
List<PermissionsToExcel> permissionsToExcelList = new List<PermissionsToExcel>();
using (ClientContext ctx = new ClientContext(#"http://yoursharepointurl.com/"))
{
Web web = ctx.Web;
ctx.Load(web, w => w.HasUniqueRoleAssignments, w => w.Url);
ctx.Load(web.RoleAssignments);
ctx.Load(web.Lists);
ctx.Load(web.Lists, lists => lists.Include(list => list.Title, list => list.DefaultViewUrl, list => list.RoleAssignments, list => list.RoleAssignments.Groups, list => list.HasUniqueRoleAssignments));
ctx.ExecuteQuery();
//Get permissions on site level
foreach (RoleAssignment webRA in web.RoleAssignments)
{
ctx.Load(webRA.Member);
ctx.Load(webRA.RoleDefinitionBindings);
ctx.ExecuteQuery();
foreach (RoleDefinition definition in webRA.RoleDefinitionBindings)
{
ctx.Load(definition);
ctx.ExecuteQuery();
permissionsToExcelList.Add(new PermissionsToExcel() { ListTitle = "", Gebruikersnaam = webRA.Member.LoginName, Rechten = definition.Name, ListUrl = web.Url, HasUniqueRoleAssignments = web.HasUniqueRoleAssignments });
}
}
//Write down each group per list and their permissions
foreach (List list in web.Lists)
{
string listUrl = list.Context.Url + list.GetWebRelativeUrl();
foreach (RoleAssignment listRA in list.RoleAssignments)
{
ctx.Load(listRA.Member);
ctx.Load(listRA.RoleDefinitionBindings);
ctx.ExecuteQuery();
foreach (RoleDefinition definition in listRA.RoleDefinitionBindings)
{
ctx.Load(definition);
ctx.ExecuteQuery();
permissionsToExcelList.Add(new PermissionsToExcel() { ListTitle = list.Title, Gebruikersnaam = listRA.Member.LoginName, Rechten = definition.Name, ListUrl = listUrl, HasUniqueRoleAssignments = list.HasUniqueRoleAssignments });
}
}
}
}
Write the permissions to Excel using EPPlus
ExcelPackage excel = new ExcelPackage();
var workSheet = excel.Workbook.Worksheets.Add("Permissions");
workSheet.Cells[1, 1].LoadFromCollection(permissionsList, true);
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=Permissions.xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
Read the permissions from Excel
List<PermissionsToExcel> permissionslist = new List<PermissionsToExcel>();
FileInfo existingFile = new FileInfo(#"C:\path\Permissions.xlsx");
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//Get the first worksheet in the workbook
ExcelWorksheet excelWorksheet = package.Workbook.Worksheets["Permissions"];
int colCount = excelWorksheet.Dimension.End.Column; //get Column Count
int rowCount = excelWorksheet.Dimension.End.Row; //get row count
for (int row = 2; row <= rowCount; row++)//Rij 1 is de titel rij, beginnen bij rij 2
{
PermissionsToExcel permission = new PermissionsToExcel
{
ListTitle = excelWorksheet.Cells[row, 1].Value.ToString().Trim(),
Gebruikersnaam = excelWorksheet.Cells[row, 2].Value.ToString().Trim(),
Rechten = excelWorksheet.Cells[row, 3].Value.ToString().Trim(),
ListUrl = excelWorksheet.Cells[row, 4].Value.ToString().Trim(),
HasUniqueRoleAssignments = excelWorksheet.Cells[row, 5].Value.ToString().Trim().ToBoolean()
};
permissionslist.Add(permission);
}
return permissionslist;
}
Put the permissions onto a new site (which has the same library setup as the old one!!
using (ClientContext ctx = new ClientContext(#"http://newSharePointSiteUrl.com/"))
{
Web web = ctx.Web;
ctx.Load(web.Lists);
ctx.Load(web.RoleDefinitions);
ctx.ExecuteQuery();
//Ophalen rollen
RoleDefinition roleTypeOwner = ctx.Web.RoleDefinitions.GetByType(RoleType.Administrator);
RoleDefinition roleTypeEditor = ctx.Web.RoleDefinitions.GetByType(RoleType.Editor);
RoleDefinition roleTypeVisitor = ctx.Web.RoleDefinitions.GetByType(RoleType.Reader);
//RoleDefinition roleTypeNone = ctx.Web.RoleDefinitions.GetByType(RoleType.None);//Werkt niet
ctx.ExecuteQuery();
//Get groups
ctx.Load(ctx.Web.SiteGroups);
ctx.Load(ctx.Web.SiteUsers);
ctx.ExecuteQuery();
foreach (PermissionsToExcel pte in permissionslist)
{
if (pte.ListTitle == "")//If listtitle is empty, it's the site permissions
{
//Get site
User user = ctx.Web.SiteUsers.GetByLoginName(pte.Gebruikersnaam);
ctx.Load(user);
ctx.ExecuteQuery();
//Check if the site had unique permissions
if (pte.HasUniqueRoleAssignments)//Site had unique permissions, break inheritance and take away the old groups
{
RoleDefinitionBindingCollection rdbc = new RoleDefinitionBindingCollection(ctx);
switch (pte.Rechten)
{
case "Read":
rdbc.Add(roleTypeVisitor);
break;
case "Edit":
rdbc.Add(roleTypeEditor);
break;
case "Full Control":
rdbc.Add(roleTypeOwner);
break;
default:
break;
}
web.BreakRoleInheritance(false, true);
web.RoleAssignments.Add(user, rdbc);
}
else//Site had no unique permissions, inherit from above
{
//TODO: do we want that?
}
}
else if (web.ListExists(pte.ListTitle))//Go over all lists
{
//Get List
List list = web.Lists.First(t => t.Title == pte.ListTitle);
//var group = ctx.Web.SiteGroups.GetByName(pte.Gebruikersnaam);
//ctx.Load(Group);
//ctx.ExecuteQuery();
User user = ctx.Web.SiteUsers.GetByLoginName(pte.Gebruikersnaam);
ctx.Load(user);
ctx.ExecuteQuery();
//Check if list had unique permissions
if (pte.HasUniqueRoleAssignments)//List had unique permissions, stop inheritance and put back groups with their permissions
{
RoleDefinitionBindingCollection rdbc = new RoleDefinitionBindingCollection(ctx);
switch (pte.Rechten)
{
case "Read":
rdbc.Add(roleTypeVisitor);
break;
case "Edit":
rdbc.Add(roleTypeEditor);
break;
case "Full Control":
rdbc.Add(roleTypeOwner);
break;
default:
break;
}
list.BreakRoleInheritance(false, true);
//list.RoleAssignments.Add(Group, rdbc);
list.RoleAssignments.Add(user, rdbc);
}
else //List had no unique permissions, inherit from above
{
list.ResetRoleInheritance();
}
}
else
{
Debug.WriteLine("LIST NOT FOUND: PROBLEM");
}
}
}
The process you would follow is:
$user = Get-SPUser -Identity "DOM\john.smith" -Web https://siteCollectionUrl
Move-SPUser -Identity $user -NewAlias "i:0#.w|IDD\142909" -IgnoreSid
This will migrate the user farm-wide. You do not need to call EnsureUser.
If you're using the User Profile Service App, make sure your user account has explicit Full Control over the UPSA to migrate users. I also provided the example above if using Windows Claims auth. On the Get-SPUser, you don't have to specify it, but on the Move-SPUser, you do.
https://social.technet.microsoft.com/Forums/en-US/2703f6de-7a79-46b8-9184-01279a845c4b/migrating-all-users-to-a-new-domain?forum=sharepointadmin

Unable to get subsites of sharepoint web applicaton

I have a sharepoint web application, with two subsites "test1" and "test2".
The addresses are the next:
http://www05:48042
http://www05:48042/sites/test1
http://www05:48042/sites/test2
var context = new ClientContext(string.Format("http://{0}", "www05:48042"));
context.Credentials = new NetworkCredential(credentials.Login,
credentials.Password);
var sites = context.Web.Webs;
context.Load(sites);
context.ExecuteQuery();
Login and password are correct. However, I am always getting an empty collection in webs, but should get at least 2 elements. What am I doing wrong? Any suggestions?
Please use the code snippet below:
public static void getSubWebs(string path)
{
try
{
ClientContext clientContext = new ClientContext(path);
Web oWebsite = clientContext.Web;
clientContext.Load(oWebsite, website => website.Webs, website => website.Title);
clientContext.ExecuteQuery();
foreach (Web orWebsite in oWebsite.Webs)
{
string newpath = mainpath + orWebsite.ServerRelativeUrl;
getSubWebs(newpath);
Console.WriteLine(newpath + "\n" + orWebsite.Title);
}
}
catch (Exception ex)
{
}
}
static string mainpath = "http://sp:80/";
getSubWebs(mainpath);
Console.Read();

Need help in converting DirectoryServices code to PrincipalContext

DirectorySearcher deSearch;SearchResultCollection result;
deSearch.SearchRoot = baseResult.GetDirectoryEntry();// I know this one can be done like - PrincipalContext pContext = new PrincipalContext(ContextType.Domain, deSearch.SearchRoot.Path);
deSearch.Filter = "(&(&(objectClass=user)(objectCategory=person))(name=" + name + "))"; //???? **Not sure how to apply the filter in Principal Context**
results = deSearch.FindAll();
Please help me in applying filter in principlecontext
You can use PrincipalSearcher to search for a particular user.
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
UserPrincipal searchUser = new UserPrincipal(ctx);
searchUser.GivenName = "Name";
PrincipalSearcher srch = new PrincipalSearcher(searchUser);
foreach(var found in srch.FindAll())
{
//found will contain the info
}
}
You can also use UserPrincipal.
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName, "DN"))
if (user != null)
{
//user contains info
}
}
You can define different IdentityType if you want to search by samAccountName or etc.

Why am I unable to list all my accounts with this code?

This is my first foray into Google Analytics. I created a service account and downloaded the p12 file from the developer console.
This code works, but in an incomplete way.
I have two accounts, but the code below just returns one account from the list.
How do I get all my accounts listed?
private static ServiceAccountCredential Run2()
{
const string keyfilePath = "file.p12";
const string serviceAccountMail = "notarealemailaddress#developer.gserviceaccount.com";
var certificate = new X509Certificate2(keyfilePath, "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountMail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics, AnalyticsService.Scope.AnalyticsReadonly, AnalyticsService.Scope.AnalyticsProvision }
}.FromCertificate(certificate));
return credential;
}
static void Main()
{
var cr = Run2();
var service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = cr,
ApplicationName = "Analytics API Sample"
});
var request = service.Management.Accounts.List();
request.MaxResults = 20;
var result = request.Execute();
foreach (var item in result.Items)
{
Console.WriteLine("Account Name: {0} {1} {2}", item.Name, item.Kind, item.Id);
}
}
This is what I ended up doing. The service account that Google creates needs to be added to every account that you need to access. I figured this from reading the documentation.
https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/service-py
Try this out
ManagementResource.AccountSummariesResource.ListRequest list = service.Management.AccountSummaries.List();
list.MaxResults = 1000; // Maximum number of Account Summaries to return per request.
AccountSummaries feed = list.Execute();
List allRows = new List();
//// Loop through until we arrive at an empty page
while (feed.Items != null)
{
allRows.AddRange(feed.Items);
// We will know we are on the last page when the next page token is
// null.
// If this is the case, break.
if (feed.NextLink == null)
{
break;
}
// Prepare the next page of results
list.StartIndex = feed.StartIndex + list.MaxResults;
// Execute and process the next page request
feed = list.Execute();
}
feed.Items = allRows;
//Get account summary and display them.
foreach (AccountSummary account in feed.Items)
{
// Account
Console.WriteLine("Account: " + account.Name + "(" + account.Id + ")");
foreach (WebPropertySummary wp in account.WebProperties)
{
// Web Properties within that account
Console.WriteLine("\tWeb Property: " + wp.Name + "(" + wp.Id + ")");
//Don't forget to check its not null. Believe it or not it could be.
if (wp.Profiles != null)
{
foreach (ProfileSummary profile in wp.Profiles)
{
// Profiles with in that web property.
Console.WriteLine("\t\tProfile: " + profile.Name + "(" + profile.Id + ")");
}
}
}
}
Reference: http://www.daimto.com/googleanalytics-management-csharp/
http://www.daimto.com/googleAnalytics-authentication-csharp/

Add group to list using SharePoint 2010 JSOM

Can someone give me an example of adding a SharePoint group to a list using the javascript client object model. I was able to create groups and add them to the site but I haven't seen any documentation on adding the groups to a list? I know how to do this via c# but not javascript.
How to grant permissions for Group in List via CSOM (JavaScript) in SharePoint 2013
The following example demonstrates how to grant Contribute permissions for group Approvers in list:
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var group = web.get_siteGroups().getByName("Approvers");
var roleDef = web.get_roleDefinitions().getByType(SP.RoleType.contributor);
var roleDefBindings = SP.RoleDefinitionBindingCollection.newObject(context);
roleDefBindings.add(roleDef);
list.get_roleAssignments().add(group,roleDefBindings);
list.update();
context.load(group);
context.load(list);
context.load(roleDef);
context.executeQueryAsync(
function () {
console.log('For group ' + group.get_title() + ' has been granted ' + roleDef.get_name() + ' permissons in List ' + list.get_title());
},
function (sender, args) {
console.log("Error: " + args.get_message());
}
);
Since SP.GroupCollection does not contain the method getByName in SharePoint 2010, use the method SP.GroupCollection.getById(id) instead to return Group client object:
var group = web.get_siteGroups().getById(16); //get Approvers group by Id
function getGroupByName(groupName, completeFunction) {
if (groupName == null) {
throw new Error("Group Name cannot be null");
}
var rv = null;
var currentContext = SP.ClientContext.get_current();
var currentWeb = currentWeb = currentContext.get_web();
var allGroups = currentWeb.get_siteGroups();
currentContext.load(allGroups);
currentContext.executeQueryAsync(getGroupByName_Success, getGroupByName_Failed);
function getGroupByName_Success() {
var groupEnumerator = allGroups.getEnumerator();
while (groupEnumerator.moveNext()) {
rv = groupEnumerator.get_current();
var groupTitle = rv.get_title();
if (groupTitle == groupName) {
groupFound = true;
break;
}
}
if (groupFound == false) {
rv = null;
}
completeFunction(rv);
}
function getGroupByName_Failed(sender, args) {
alert("Error Occurred: " + args.get_message() + "\n" + args.get_stackTrace());
}
}

Resources