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

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

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;

SharePoint 2013 Activity Event in Newsfeed

I need to add custom notifications to the personal Newsfeed on people's MySites. I found several tutorials and code examples for SharePoint 2010 on the net and tried to do the same with SharePoint 2013. They're all about creating ActivityEvents with the ActivityManager.
Here's the code I tried:
var targetSite = new SPSite("URL to MySite webapp");
SPServiceContext context = SPServiceContext.GetContext(targetSite);
var userProfileManager = new UserProfileManager(context);
var ownerProfile = userProfileManager.GetUserProfile("domain\\user1");
var publisherProfile = userProfileManager.GetUserProfile("domain\\user2");
var activityManager = new ActivityManager(ownerProfile, context);
Entity publisher = new MinimalPerson(publisherProfile).CreateEntity(activityManager);
Entity owner = new MinimalPerson(ownerProfile).CreateEntity(activityManager);
ActivityEvent activityEvent = ActivityEvent.CreateActivityEvent(activityManager, 17, owner, publisher);
activityEvent.Name = "StatusMessage";
activityEvent.ItemPrivacy = (int)Privacy.Public;
activityEvent.Owner = owner;
activityEvent.Publisher = publisher;
activityEvent.Value = "HELLOOOO";
activityEvent.Commit();
ActivityFeedGatherer.BatchWriteActivityEvents(new List<ActivityEvent> { activityEvent }, 0, 1);
The Id 17 in the CreateActivityEvent function is for the StatusMessage activity type, which is layouted like {Publisher} says: {Value} in the ressource files, so I provide the Value property of my ActivityEvent.
The code runs without any exception and in the User Profile Service Application_ProfileDB database I can see the right entries appear in the ActivityEventsConsolidated table.
But the activity is not visible in the activity feed, neither on the Owner's one, nor on the Publisher's one, even though these people follow each other. I ran the Activity Feed Job in the CA manually to update the activity feed.
Also, I tried to do the same with custom ActivityTypes with own ressource files, same result: The entry in the ActivityEventsConsolidated table (or ActivityEventsPublished if Owner=Publisher) appear, but no entries on the MySite.
Can anyone help?
I found the solution for this problem myself.
In Central Administration, Setup MySites, you have to enable the Enable SharePoint 2010 activity migration setting in the Newsfeed section in order to support SP1010 legacy activities in SP2013.

Displaying Managed Property in Search Results - FAST Search for Sharepoint 2010

We are working with Fast Search for Sharepoint 2010 and had some backend setup done with creating some managed properties e.g. BestBetDescription, keywords etc.
From the front-end part we are creating an application what will fetch all these properties and display in a grid.
However while querying the backend we are NOT getting these managed properties (BestBetDescription) along with other properties such as Title, URL etc.
Following is my source code:
settingsProxy = SPFarm.Local.ServiceProxies.GetValue<SearchQueryAndSiteSettingsServiceProxy>();
searchProxy = settingsProxy.ApplicationProxies.GetValue<SearchServiceApplicationProxy>("FAST Query SSA");
keywordQuery = new KeywordQuery(searchProxy);
keywordQuery.EnableFQL = true;
keywordQuery.QueryText = p;
keywordQuery.ResultsProvider = SearchProvider.FASTSearch;
keywordQuery.ResultTypes = ResultType.RelevantResults;
ResultTableCollection resultsTableCollection = keywordQuery.Execute();
ResultTable searchResultsTable = resultsTableCollection[ResultType.RelevantResults];
DataTable resultsDataTable = new DataTable();
resultsDataTable.TableName = "Results";
resultsDataTable.Load(searchResultsTable, LoadOption.OverwriteChanges);
return resultsDataTable;
The results are returned and I cannot see the Managed properties which we create in the resultDataTable.
Is there any property I missed or is this a backend issue ?
Thanks.
Hi if you are creating your custom Metadata Property then u should use this option to be selected
please check below link
http://screencast.com/t/SQdlarjhx4F
You can find this option in :
central admin:- services :- fast search :- Metadata Property :- your property
I was missing a property KeywordQuery.SelectProperties
So the code looks something like this
String[] arrSearchProperties = new String[] { "Title", "body", "url" };
KeywordQuery.SelectProperties(arrSearchProperties);
This will fetch you all the Managed Properties defined by you.

Get all users from active directory to sharepoint

I have to populate my autocomplete PeopleEditor-like control based on brililant ASPTokenInput with all people from my AD domain. Reflecting PeopleEditor shows a real mess in their Active Directory search engine and all potentially helpful classes are internal.
My test method works fine, but I need to get ALL users from AD(not sharepoint site ones) to populate my list:
public string GetUsers(string filter)
{
var spWeb = SPContext.Current.Web;
SPUserCollection allusers = spWeb.AllUsers;
List<SPUser> users = allusers.Cast<SPUser>().ToList();
var query = from spUser in users.Select(usr => new {id = usr.ID, name = usr.Name})
.Where(p => p.name.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) >= 0)
select new {id = spUser.id.ToString(), spUser.name};
return new JavaScriptSerializer().Serialize(query);
}
How can I query active directory like this? Is it possible to retrieve all AD connection settings from sharepoint itself? I need just id and user name to fill my dropdownlist Converting this to SPUserCollection is another big deal.
It would be great to use some built-in SP methods like this:
[SubsetCallableExcludeMember(SubsetCallableExcludeMemberType.UnsupportedSPType)]
public static IList<SPPrincipalInfo> SearchWindowsPrincipals(SPWebApplication webApp, string input, SPPrincipalType scopes, int maxCount, out bool reachMaxCount)
Solution was simple, the only thing I needed was SharePoint Group search implementation (If specified in Field Editor Control). SP has a nice built-in method, so I use it.
/// <summary>
/// Provides searching for AD or SharePoint group if specified in field setting
/// </summary>
public static class ActiveDirectorySearchProvider
{
public static IList<SPPrincipalInfo> Search(string filter, string selectionGroup, string principalType)
{
var site = SPContext.Current.Site.WebApplication;
bool reachmaxcount;
var scope = SPUtils.GetSpPrincipalType(principalType);
if (!String.IsNullOrEmpty(selectionGroup)) //search for users in SPGroup if present
{
var rawSPGroupList = SPUtility.GetPrincipalsInGroup(SPContext.Current.Web, selectionGroup, 100,
out reachmaxcount).ToList();
string lowerFilter = filter.ToLowerInvariant();
var filteredGroupList =
rawSPGroupList.Where(
pInfo =>
pInfo.LoginName.Substring(pInfo.LoginName.IndexOf('\\') + 1).StartsWith(lowerFilter) ||
pInfo.DisplayName.ToLowerInvariant().StartsWith(lowerFilter) ||
pInfo.DisplayName.ToLowerInvariant().Substring(pInfo.DisplayName.IndexOf(' ') + 1).StartsWith(
lowerFilter)).ToList();
return filteredGroupList;
}
return SPUtility.SearchWindowsPrincipals(site, filter, scope, 100, out reachmaxcount); //Search in AD instead
}
I can think of two options here.
You can use System.DirectoryServices and query all users from your Active Directory in your c# code.
You can setup User Profile Sync so that your SharePoint user DB is upto date.

Problem with Sharepoint speed using sharepoint Object Model: get user's group from userID

I am quite stumped with this. In enhancing an existing feature to a SharePoint solution, I found that they were querying the Wss_Content directly. Knowing I should not be using that stored procedure, I used the SharePoint object model to retrieve the users group information from the userName. What's burning me is that it is slower then the stored procedure. Is there a smarter/faster way to get this information? We are using SharePoint 2007. Below is roughly what the function does:
private string GetTitle(string userName)
{
string results = string.Empty;
try
{
SPSite spSite = new SPSite("http://devvm");
SPWeb spWeb = spSite.AllWebs[""];
SPUser user = spWeb.AllUsers["aspnetsqlmembershipprovider:" + userName];
SPGroupCollection groups = user.Groups;
results = groups[0].Name;
}
catch (Exception ex)
{
Console.WriteLine("Unable to find user" + userName);
results = "No Group Found";
}
return results;
}
and the Stored Procedure code is:
SELECT #role=Groups.Title
FROM WSS_Content.DBO.UserInfo Info
LEFT JOIN WSS_Content.DBO.GroupMembership Membership
ON Info.tp_ID=Membership.MemberID
LEFT JOIN Wss_Content.DBO.Groups Groups
ON Membership.GroupID=Groups.ID
WHERE tp_Login='aspnetsqlmembershipprovider:' + #username
FYI the reason I have this in a try-catch is that this is a sub-query to another list that might not have a user associated to the item.
Any help in this would be greatly appreciated.
How are you calling that code? If you are using this inside a console application then yes it will be slower, it needs to fire up the supporting objects that are normally live when using this inside a native sharepoint context.
Also you are referencing an SPSite and SPWeb object without disposing of the object, this has inherent performance issues as well.

Resources