Retrieve additional user properties from ActiveDirectoryMembershipProvider - asp.net

The ActiveDirectoryMembershipProvider in ASP.NET returns users as instances of MembershipUser. This class only returns two of the properties defined for the given user in AD: email and username. I need to get access to additional properties, specifically "DisplayName", as I need to show full names in a dropdown in a web form.
The only way I can find to do this, is via a separate connection to AD, along the lines of what is described here: How can I convert from a SID to an account name in C#. This seems like a cumbersome and inefficient solution. I would like to do something like membershipProvider.GetUserProperty(username, propertyName), but that's not available.
Are there any nice solutions that people know of?

Based on feedback from my colleagues (thanks, Eirik!), #KennyZ's comment and lots of Googl'ing, I have found that this is the best/only way to do it. For reference, and other people seeing this question, here is some useful code for getting the AD settings out of web.config+connectionStrings.config, and using that data to query AD for a given user's Display Name:
var membershipSection = (MembershipSection)WebConfigurationManager.GetSection("system.web/membership");
var providerSettings = membershipSection.Providers["ActiveDirectoryMembershipProvider"];
var connectionStringName = providerSettings.Parameters["connectionStringName"];
var adUser = providerSettings.Parameters["connectionUsername"];
var adPassword = providerSettings.Parameters["connectionPassword"];
var adConnection = WebConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
var adReference = new DirectoryEntry(adConnection, adUser, adPassword);
var search = new DirectorySearcher(adReference) {Filter = string.Format("(mail={0})", username)};
search.PropertiesToLoad.Add("displayName");
SearchResult result = search.FindOne();
if (result != null)
{
var resultCollection = result.Properties["displayName"];
if (resultCollection.Count > 0)
{
var displayName = resultCollection[0].ToString();
...
}
}
Note: This assumes that I am using userPrincipalName as the attributeMapUsername in web.config, as that maps to the user's email address.

Related

How to get IdentityUser by Username

I have previously worked with Membership through "System.Web.Security.Membership"
Here, you can do the following:
var currentUser = Membership.GetUser();
var otherUser = Membership.GetUser(username);
...giving you a MembershipUser.
Now, with Identity, I can find a load of ways to get the current logged in user.
But no way to get another user.
I can use:
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
var user = userManager.Find(username, password);
But that takes both username and password, with no overload for just username.
How do i get the IdentityUser from only a username?
Almost every answer I find is connected to MVC.
This is for a WCF service, where authorization is made using Identity. And in some cases the user is getting to the site from an other site with a generated "token" - an encrypted string, containing the username. From here, user is logged in and a session-cookie is set, depending on users settings.
Also, is there a shorter way to get UserInformation?
"var currentUser = Membership.GetUser(username);"
is much more convenient than
"var user2 = (new UserManager((new UserStore()))).Find(username, password);"
UserManager has UserManager<TUser>.FindByNameAsync method. You can try using it to find user by name.

Change a space to a + in order to complete an api in flex

I'm trying to make a search form to use on an api. However when the user types in the search field more then one name I want it to break the string into pieces and make a new string with a + between every keyword. I have no idea how to do this however.
Try this
var searchString:String = "nameOne nameTwo nameThree";
var whiteSpacePattern:RegExp = /\s+/g;
var replacedString:String = searchString.replace(whiteSpacePattern, "+");
trace(replacedString); // nameOne+nameTwo+nameThree
More information about String.replace : http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f00.html#WS5b3ccc516d4fbf351e63e3d118a9b90204-7ef1

Get List of Localized Items

I need to get the list of localized items of a publication programatically using coreservice in tridion. Could any one suggest me.
I would use the GetListXml method and specify a BluePrintChainFilterData filter object.
var subjectId = "[TCM Uri of your item]";
var filter = new BluePrintChainFilterData
{
Direction = BluePrintChainDirection.Down
};
var subjectBluePrintChainList = coreServiceClient.GetListXml(subjectId, filter);
You then still need to verify the localized items from the received list.
This wasn't in my original answer, and probably isn't complete because I don't take into account namespaces, but the following would work to select the localized (not shared) items.
var localizedItems = subjectBluePrintChainList.Elements("Item")
.Where(element => "false".Equals(element.Attribute("IsShared").Value, StringComparison.OrdinalIgnoreCase));
The only way I know is to use search functionality:
var searchQuery = new SearchQueryData();
searchQuery.BlueprintStatus = SearchBlueprintStatus.Localized;
searchQuery.FromRepository = new LinkToRepositoryData{IdRef = "tcm:0-5-1"};
var resultXml = ClientAdmin.GetSearchResultsXml(searchQuery);
var result = ClientAdmin.GetSearchResults(searchQuery);

Get ALL Mailboxes via EWS (Exchange WebServices) - not my own but also shared and group mailboxes

Can anyone provide me with a .NET (C# / VB) sample of how to get all mailboxes that I have access to ?
I have only been able to get my OWN mailbox via EWS - not ALL THE OTHER mailboxes that I also have access to through Outlook.
I don't have the names nor the id's of these mailboxes but isn't it possible to retrieve ALL mailboxes - including my own - that I am allowed to see - just as I can in Outlook ?
I am using Autodiscover to get my mailbox like this: service.AutodiscoverUrl("xxxx#ee.dd") - this will perhaps only get my own mailbox and not all the rest?
Please help !?
The way I got around this was to define the group mailbox in question as a "mailbox" object and then obtain the FolderID for the particular folder.
Define mailbox object
Mailbox gpmailbox = new Mailbox("mailbox#yourdomainname.com");
Get the FolderID (in this case, the Inbox)
FolderId gpInbox = new FolderId(WellKnownFolderName.Inbox, gpmailbox);
Use FolderID in your normal code (in this case I'm obtaining 100 messages)
ItemView view = new ItemView(100);
FindItemsResults<Item> results = hookToServer.FindItems(new FolderId(WellKnownFolderName.Inbox, gpmailbox), view);
The key is to grab the FolderID of the folder you need. Hope this helps.
Edit: I also failed to note that my object "hookToServer" is simply the ExchangeService object. Here's how I defined it:
ExchangeService hookToServer = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
hookToServer.UseDefaultCredentials = true;
hookToServer.Url = new Uri("TheExchangeServer")
I also used this as reference:
EWS 2007 Group Mailbox Guide
You can do this by Using Autodiscover to get user settings, this is a completely separate service to the one with the AutodiscoverUrl method.
The setting name you need is AlternateMailboxes, this will give a collection of all the 'other' mailboxes you have access to. You might then add the user's default mailbox to get a complete list.
In c#:
using Microsoft.Exchange.WebServices.Autodiscover; // from nuget package "Microsoft.Exchange.WebServices"
internal List<string> GetAccessibleMailboxes()
{
AutodiscoverService autodiscoverService = new AutodiscoverService("outlook.office365.com");
autodiscoverService.Credentials = networkCredential;
var userSmtpAddress = networkCredential.UserName;
GetUserSettingsResponse userresponse = autodiscoverService.GetUserSettings(
userSmtpAddress,
UserSettingName.AlternateMailboxes);
var alternateMailboxCollection = (AlternateMailboxCollection)userresponse.Settings[UserSettingName.AlternateMailboxes];
var smtpAddressList = alternateMailboxCollection.Entries.ToList().Select(a => a.SmtpAddress).ToList();
smtpAddressList.Add(userSmtpAddress);
return smtpAddressList;
}

Update user using DirectoryService

So I managed to get some code rolling for updating the AD from an external sourced. However, I'm a bit confused about how it works.
I have a person with sAMAccount xxxx existing in different OUs.
Now, I only want to update the info in a specific OU, so I put that in my LDAP path. Still, it seem that the info has been updated in different OU's as well?
Could that be possible? Is it because there's only one "Person" object, or do the "GetDirectoryEntry()" not put me where I thought in the tree? Or.. am I only imagine and the weird things I see is becausde of something else.
Some code
DirectoryEntry entry = new DirectoryEntry(LDAP://my.path/ou=myou, dc=my, dc=path);
entry.Username = myUser
entry.Password = myPass
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = #"(&(objectClass=Person)(SamAccountname=" + person.id + "))";
SearchResult result = searcher.FindOne();
try
{
DirectoryEntry user = result.GetDirectoryEntry();
user.Properties["displayName"].Value = person.DisplayName;
user.Properties["givenName"].Value = person.Firstname;
user.CommitChanges();
user.Close();
}
catch (DirectoryServicesCOMException ex)
EDIT: It did update the Person object in all the OU's. So either the Person object is one and the same in the whole AD, whick makes my attempt to update them in only the specific OU pointless, or does the "result.GetDirectoryEntry" ignore the fact that I thought I was working only in my specific OU declared in my LDAP path.
Functionality confirmed, still wonder why I needed a specific test-ou since it's still the same users. Anyway, here we go!

Resources