modo più semplice per ottenere SPUser o SP Group Da ID in SharePoint 2010
-
22-10-2019 - |
Domanda
Sono bloccato per un problema in cui ho una lista ID - elenco di ID devo trovare il LoginName di SPUser o SPGroup con l'id nel listid
Ho provato quanto segue ma threws eccezione in quanto non trovare l'utente quando il gruppo id c'è
foreach (var id in ID)
{
SPUser spUser = web.SiteUsers.GetByID(Convert.ToInt32(id));
if (spUser != null)
{
lstUsers.Add(spUser.LoginName);
continue;
}
SPGroup spGroup = web.SiteGroups.GetByID(Convert.ToInt32(id ));
if (spGroup != null)
{
lstGroups.Add(spGroup.LoginName);
continue;
}
}
Si prega di suggerire cosa fare !!!
Soluzione
Vorrei suggerire due cambiamenti.
- Usa
SPFieldUserValue
. Essa non genera un'eccezione se l'utente non lo fa esistono. -
Utilizzare il
SPGroupCollection.GetCollection(int[] ids)
SPUserCollection users = web.SiteUsers; SPGroupCollection groups = web.SiteGroups; foreach (var id in ID) { // try to get user-name SPUser spUser = new SPFieldUserValue(web, Convert.ToInt32(id), null).User; if (spUser != null) { lstUsers.Add(spUser.LoginName); continue; } // try to get group-name var foundGroups = groups.GetCollection(new int[] { Convert.ToInt32(id) }); if (foundGroups.Count > 0) { lstGroups.Add(foundGroups[0]); continue; } // If execution reaches this point: Nothing found with this id }
Altri suggerimenti
Se ho letto la tua domanda corretta: Hai lista denominata ID
in cui si dispone di ID numerici (ID utente e gruppo) e si desidera aggiungere il nome dell'utente o del gruppo che corrisponde al id a un altro elenco (chiamato lstUsers o lstGroups).
L'eccezione è prevedibile se l'id manipolato è l'id di un gruppo. La funzione di web.SiteUsers.GetById()
genera un'eccezione quando l'id non si trova e che è quello che si prova prima. Prova avvolgendolo in un try-catch
blocco.
Bonus:. SiteUsers negozi e SiteGroups in una variabile, per evitare di ottenere questo infomation più e più volte dal database in ogni iterazione del ciclo
SPUserCollection users = web.SiteUsers;
SPGroupCollection groups = web.SiteGroups;
foreach (var id in ID)
{
// try to get user-name
try{
SPUser spUser = users.GetByID(Convert.ToInt32(id));
if (spUser != null)
{
lstUsers.Add(spUser.LoginName);
continue;
}
}catch(Exception){
// no user found with id.
}
// try to get group-name
try {
SPGroup spGroup = groups.GetByID(Convert.ToInt32(id ));
if (spGroup != null)
{
lstGroups.Add(spGroup.LoginName);
continue;
}
}catch(Exception){
// no group found with id
}
// If execution reaches this point: Nothing found with this id
}