SharePoint UserProfile from User Principal Name in Claims environment - sharepoint

I have an account that has been persisted in a database using the User Principal Name (UPN) format: jdoe#domain.gobalx.com
I am working in a SharePoint environment that is Claims authenticated using the UPN format.
My problem is I need to get a UserProfile object for the persisted UPN account. I have tried the following but it doesn't work:
string upnAccount = "jdoe#domain.globalx.com";
SPServiceContext ctx = SPServiceContext.GetContext(SPContext.Current.Site);
UserProfileManager upm = new UserProfileManager(ctx);
UserProfile user = upm.GetUserProfile(upnAccount);
I keep getting: Microsoft.Office.Server.UserProfiles.UserNotFoundException: An error was encountered while retrieving the user profile
Does this mean that I have to convert the UPN account into a claim, and if so does anyone have an example on how to do that?

UserProfileManager UPM = null;
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
ServerContext serverContext = ServerContext.GetContext(site);
UPM = new UserProfileManager(serverContext);
foreach (UserProfile profile in UPM)
{
an = profile["AccountName"].Value;
title = profile["Title"].Value;
}
}
}
U can try this for get All userprofile. In foreach loop u can check for your fields and get perticular user details

In some cases under SharePoint sites with federated authentication there are no user profiles automatically created until you haven't setup synchronization. For this issue you may check if there already exists user profile for jdoe#domain.globalx.com via Central Admin.
Also your code must be run under impersonation, check the log for exception and try to use SPSecurity.RunWithElevatedPrivileges.

Related

How do I get the Active Directory Information with Sharepoint programatically on sharepoint 2013 Farm Solution On Code Behind File?

I want to Get the Active Directory names in sharepoint in a list.
To got Know that SharePoint 2013 Has some Hidden URL which Shows Current Active Directory User I wan to get it into List.
http://{YourSharepointUrl}/_catalogs/users/simple.aspx
Now I want to have list of all the names Displayed on my sharepoint
I am using the code:
private static void GetAllSiteUsers()
{
// Starting with ClientContext, the constructor requires a URL to the server running SharePoint.
var sharepointContext = new ClientContext("http://yoursharepointurl/");
}
Now I am Getting error it says about assembly reference doesn't exist.So I checked on google and added up this ddl and add the using Microsoft.SharePoint.Client; reference also.Still Not working.
Please Let me Know what needed to be done Guys
Purpose Of Making Program:To have all the AD Users and Make a work Group so that I can Assign them some right in such a way when assigned grp open something some other URL in iframe shows. and if some one else than other URL in iframe is shown to him.
Thanks IN Advance Guys.
You are in Server side (Farms solution), so don't use : ClientContext, this is for Client application, not server.
You just have to get the : User Information List
You could try somthing like :
using(SPSite site = new SPSite("URLsiteCollection")){
using(SPWeb web = site.rootWeb){
SPList userList = web.SiteUserInfoList;
SPListItemCollection allUsers = userList.Items;
foreach(SPListItem userItem in allUsers){
string userEmail = Convert.Tostring(userItem["EMail"]);
string userName = userItem.Title;
....
}
}
}
To get all information about active directory user or group you can use
PrincipalContext pContext = new PrincipalContext (ContextType.Domain, YOUR_DOMAIN);
//For User
UserPrincipal userPrincipal = new UserPrincipal (pContext);
PrincipalSearcher userSearch = new PrincipalSearcher (userPrincipal);
//For Group
GroupPrincipal grpPrincipal = new GroupPrincipal (pContext);
PrincipalSearcher grpSearch = new PrincipalSearcher (grpPrincipal);
foreach (UserPrincipal result in userSearch.FindAll())
{
if (result.SamAccountName!= null)
// Your code
}
foreach (GroupPrincipal result in grpSearch.FindAll())
{
if (result != null)
{
// Your code
}
Assembly
System.DirectoryServices.AccountManagement
Namespace
using System.DirectoryServices.AccountManagement;

Access denied office 365 / SharePoint online with Global Admin account

I am going crazy since two days solving an issue. The problem is;
I am making a console APP which is talking to SharePoint Online using global admin account (One which was specified as admin while making a new subscription). What I am trying to achieve is, I want to add a custom action using CSOM to each site collection and subsite of office 365. That code works fine except on the root site collection which is pre-created by office 365 while signing up (i.e. https://xyz.sharepoint.com)
For any tenant for root site collection, it gives me below error;
{
"SchemaVersion":"15.0.0.0","LibraryVersion":"16.0.3912.1201","ErrorInfo":{
"ErrorMessage":"Access denied. You do not have permission to perform
this action or access this
resource.","ErrorValue":null,"TraceCorrelationId":"2a47fd9c-c07b-1000-cfb7-cdffbe3ab83a","ErrorCode":-2147024891,"ErrorTypeName":"System.UnauthorizedAccessException"
},"TraceCorrelationId":"2a47fd9c-c07b-1000-cfb7-cdffbe3ab83a" }
Now the user is global admin. I also added again that user as site collection admin.
The same piece of code works fine on other site collections (search site collection, any newly made site collection...).
here is a code;
using (ClientContext spcollContext = new ClientContext(web.Url))
{
SecureString passWord = new SecureString();
foreach (char c in strAdminPassword.ToCharArray()) passWord.AppendChar(c);
SharePointOnlineCredentials creds = new SharePointOnlineCredentials(strAdminUser, passWord);
spcollContext.Credentials = creds;
Web currentweb = spcollContext.Web;
spcollContext.Load(currentweb);
spcollContext.ExecuteQuery();
// authCookie = creds.GetAuthenticationCookie(new Uri(web.Url));
var existingActions2 = currentweb.UserCustomActions;
spcollContext.Load(existingActions2);
spcollContext.ExecuteQuery();
var actions2 = existingActions2.ToArray();
foreach (var action in actions2)
{
if (action.Description == "CustomScriptCodeForEachsite" &&
action.Location == "ScriptLink")
{
action.DeleteObject();
spcollContext.ExecuteQuery();
}
}
var newAction2 = existingActions2.Add();
newAction2.Description = "CustomScriptCodeForEachsite";
newAction2.Location = "ScriptLink";
newAction2.ScriptBlock = scriptBlock;
newAction2.Update();
spcollContext.Load(currentweb, s => s.UserCustomActions);
spcollContext.ExecuteQuery(); // GETTING ERROR ON THIS LINE.
}
Note: Above error is Fiddler traces.
Most probably this behavior is caused by Custom Script feature, basically
the issue occurs when the Custom Script feature is turned off
How to verify?
You could verify the site permissions using the following console app:
using (var ctx = GetContext(webUri, userName, password))
{
var rootWeb = ctx.Site.RootWeb;
ctx.Load(rootWeb, w => w.EffectiveBasePermissions);
ctx.ExecuteQuery();
var permissions = rootWeb.EffectiveBasePermissions;
foreach (var permission in Enum.GetValues(typeof(PermissionKind)).Cast<PermissionKind>())
{
var permissionName = Enum.GetName(typeof(PermissionKind), permission);
var hasPermission = permissions.Has(permission);
Console.WriteLine("Permission: {0}, HasPermission: {1}", permissionName, hasPermission);
}
}
where
public static ClientContext GetContext(Uri webUri, string userName, string password)
{
var securePassword = new SecureString();
foreach (var ch in password) securePassword.AppendChar(ch);
return new ClientContext(webUri) {Credentials = new SharePointOnlineCredentials(userName, securePassword)};
}
When SP.PermissionKind.AddAndCustomizePages is set to False, the Access denied error occurs while adding user custom action.
Solution
According to Turn scripting capabilities on or off:
For self-service created sites, custom scripting is disabled by
default
Solution: enable Allow users to run custom scripts on self-service created sites
To enable or disable scripting from the SharePoint admin center
Sign in to Office 365 with your work or school account.
Go to the SharePoint admin center.
Select Settings.
Under Custom Script choose:
Prevent users from running custom script on personal sites or Allow
users to run custom script on personal sites.
Prevent users from running custom script on user created sites or
Allow users to run custom script on self-service created sites.
Select OK. It takes about 24 hours for the change to take
effect.
Since any change to the scripting setting made through the SharePoint Online admin center may take up to 24 hours to take effect, you could enable scripting on a particular site collection immediately via CSOM API (SharePoint Online Client Components SDK) as demonstrated below:
public static void DisableDenyAddAndCustomizePages(ClientContext ctx, string siteUrl)
{
var tenant = new Tenant(ctx);
var siteProperties = tenant.GetSitePropertiesByUrl(siteUrl, true);
ctx.Load(siteProperties);
ctx.ExecuteQuery();
siteProperties.DenyAddAndCustomizePages = DenyAddAndCustomizePagesStatus.Disabled;
var result = siteProperties.Update();
ctx.Load(result);
ctx.ExecuteQuery();
while (!result.IsComplete)
{
Thread.Sleep(result.PollingInterval);
ctx.Load(result);
ctx.ExecuteQuery();
}
}
Usage
using (var ctx = GetContext(webUri, userName, password))
{
using (var tenantAdminCtx = GetContext(tenantAdminUri, userName, password))
{
DisableDenyAddAndCustomizePages(tenantAdminCtx,webUri.ToString());
}
RegisterJQueryLibrary(ctx);
}
where
public static void RegisterJQueryLibrary(ClientContext context)
{
var actions = context.Site.UserCustomActions;
var action = actions.Add();
action.Location = "ScriptLink";
action.ScriptSrc = "~SiteCollection/Style Library/Scripts/jQuery/jquery.min.js";
action.Sequence = 1482;
action.Update();
context.ExecuteQuery();
}
If you don't have time for CSOM as described by Vadim, the page also links to a powershell script you can use:
Set-SPOsite <SiteURL> -DenyAddAndCustomizePages 0
But note that SiteUrl needs to be the admin url. If your tenant is https://mysite.sharepoint.com, the url you use is https://mysite-admin.sharepoint.com"
In our case, we were in the midst of a deployment when this hit and could not wait 24 hours (or even one hour!) to continue. Everything had been fine in our testing site collections, but when we deployed to the tenant root, we hit the error described above and this script fixed it. Apparently the feature is turned off by default on the tenant root.
Current site is not a tenant administration site
Turn scripting capabilities on or off
My first response would be that you shouldn't add a CustomAction on the fly through code. That said, I'm sure you have a good reason to need to do so.
Try to set the AllowUnsafeUpdates flag on SPWeb to true as soon as you reference currentWeb. Make sure to also set it back to false after you call the final ExecuteQuery()
By default, AllowUnsafeUpdates is false. It is used to block cross-site scripting attacks.
https://msdn.microsoft.com/en-us/library/Microsoft.SharePoint.SPWeb_properties.aspx

In SharePoint, is it possible to programmatically get the current list of users associated with the "nt authority/authenticated users" group?

In SharePoint, I'd like to find out all of the users who have been given access to a site.
If the user is directly granted permissions, granted permissions via a SharePoint group, or granted permissions via a domain group; then I'm able to get the necessary information.
However, if the user is granted permissions via the "authenticated users" group, I am not sure how to find the list of users associated with that group.
Is this possible?
This is more of a .Net question than a Sharepoint question. Yes, you can do this - use the AD APIs to query your domain controller for a list of all users. Here is some code to get you started on programmatic AD access:
http://www.codeproject.com/KB/system/everythingInAD.aspx
You could try to do a query for all objects in AD that are Users.
Please note that this will not list any users outside of AD that might have access to the Sharepoint content. Also, if you have multiple domains, be sure to query all of the AD domains that might have access to the Sharepoint server.
Kyle, thanks for the response.
Using that information, I came up with the following to get all of the users in all of the domains:
private List<Principal> GetAllAuthenticatedUsers()
{
List<Principal> users = new List<string>();
foreach (string domain in GetAllDomains())
{
try
{
PrincipalContext context = new PrincipalContext(ContextType.Domain, domain);
// Create search condition for all enabled users
PrincipalSearcher searcher = new PrincipalSearcher();
UserPrincipal user = new UserPrincipal(context);
user.Enabled = true;
user.Name = "*";
searcher.QueryFilter = user;
// Get the users
System.DirectoryServices.AccountManagement.PrincipalSearchResult<Principal> results = searcher.FindAll();
foreach (Principal principal in results)
{
users.Add(principal);
}
}
catch
{
}
}
return users;
}
private static List<string> GetAllDomains()
{
List<string> domains = new List<string>();
using (Forest forest = Forest.GetCurrentForest())
{
foreach (Domain domain in forest.Domains)
{
domains.Add(domain.Name);
}
}
return domains;
}

SharePoint permissions for a specific group

I'm trying to establish whether a specific group has Read access to a particular site collection.
I have been trying for a day and a half but feel as if I have found three halves of different solutions!
The code fragments I have so far are:
using (SPSite site = new SPSite(this.GenerateAbsoluteUri(moduleCode, academicYear)))
{
using (SPWeb web = site.OpenWeb())
{
for (int i = web.SiteGroups.Count - 1; i >= 0; i--)
{
SPGroup group = web.SiteGroups[i];
if (Regex.IsMatch(group.Name, theGroupImLookingFor))
{
but then what?!
Most of my Google results tell me about roles but I don't know how to tie a role to a group.
Please help!
To assign permission to a user (account) or a SharePoint group there are some objects that we need to look at in a certain order. The first thing we need to do is get the the security principal that we want to assign the role to (SPUser or SPGroup). The next thing we need to do it get the actual permission (role) that we want to assign (ex: Read, Full Control etc…). Then we need to create a SPRoleAssignment object and on the constructor pass it in the SPUser or SPGroup (security principal) that we want to assign the permissions to. Now we need to add the role definition to the RoleDefinitionBindings collection of the role assignment object. Then we need to add the actual role assignment to the web (site) and update the web. Below is the full code lisitng.
// Create the site that contains our list
using(SPSite oSite = new SPSite("<<my site url>>"))
{
// Open the web object
using(SPWeb oWeb = oSite.OpenWeb())
{
// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<<group name>>"];
// Get the role definition we want to assign ex: Full Control
SPRoleDefinition oRole = oWeb.RoleDefinitions["<< role name>>"];
// Create the role assignment object
SPRoleAssignment oRoleAssignment = new SPRoleAssignment(oGroup);
// Add the role definition to the role assignemnt.
// This will assign the specific permission to the security principal for this role assignemnt.
oRoleAssignment.RoleDefinitionBindings.Add(oRole);
// Now we need to add the role assignment to the web
oWeb.RoleAssignments.Add(oRoleAssignment);
// Now update the web
oWeb.Update();
}
}
Heres snippets from my own code (Sharepoint 2010).
Creating a role:
SPRoleDefinition network_role = new SPRoleDefinition();
network_role.BasePermissions = SPBasePermissions.AddListItems |
SPBasePermissions.BrowseDirectories |
SPBasePermissions.EditListItems |
SPBasePermissions.DeleteListItems;
network_role.Name = "Network - Project Member";
network_role.Description = "Provides permissions required for a member of a project.";
web.RoleDefinitions.Add(network_role);
Adding a role to a group:
var assign = new SPRoleAssignment(oweb.SiteGroups["Network Project - " + item.Code]);
assign.RoleDefinitionBindings.Add(network_role);

MOSS2007 UserProfile Property: programmatic access to "mapped attribute" in AD

As you may know, MOSS 2007 offers functionality to synchronize Active Directory properties to SharePoint UserProfile Properties. You can map AD properties to userProfile properties in
Shared Services > User Profile and Properties > View Profile properties (all the way at the bottom).
I'm currently investigating the possibility to synchronize modifications on userProfiles back to AD.
I'm new to SharePoint and struggling my way through its API's, but what I dug up so far, is that you can iterate to UserProfile changes and find out timestamps, old values, new values, etc.
string siteUrl = #"http://[siteUrl]/";
Microsoft.SharePoint.SPSite spsite = new Microsoft.SharePoint.SPSite(url);
Microsoft.Office.Server.ServerContext serverContext = Microsoft.Office.Server.ServerContext.GetContext(spsite);
Microsoft.Office.Server.UserProfiles.UserProfileManager userProfileMgr = new Microsoft.Office.Server.UserProfiles.UserProfileManager(serverContext);
var collection = userProfileMgr.GetChanges();
List<ProfilePropertyChange> changes = new List<ProfilePropertyChange>();
foreach (Microsoft.Office.Server.UserProfiles.UserProfileChange change in collection)
{
if (change.ObjectType == Microsoft.Office.Server.UserProfiles.ObjectTypes.SingleValueProperty)
{
var singleValue = change as Microsoft.Office.Server.UserProfiles.UserProfileSingleValueChange;
string oldValue = singleValue.OldValue;
string newValue = singleValue.NewValue;
var profileProperty = singleValue.ProfileProperty;
DateTime modificationDate = singleValue.EventTime;
...
}
}
However, what I'm currently unable to discover, is programmatic access to the so called "Mapped Attribute" (the original property name in AD).
Can anybody point me to the SharePoint API that will reveale this information for me?
Many thanks
Steve Curran was kind enough to address my question on the MSDN forum:
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/019c1e60-babb-4942-90e1-d33e924c7c73
Using the PropertyMapCollection you
may be able to look up the mapped AD
attribute given the Userprofile name.
DataSource ds = upcm.GetDataSource();
PropertyMapCollection pmc =
ds.PropertyMapping;
http://msdn.microsoft.com/en-us/library/microsoft.office.server.userprofiles.propertymapcollection%28office.12%29.aspx

Resources