The functionality of web.EnsureUser("login name") function is to resolve the user from the sharepoint site. But there might be a case where the login name you are passsing as a parameter, which does not exist in the site, then it will give you a run time error.
But this function will work like a brilliant. It will check the user and if does not exist then add that to "Home Owners" group. You can specify your own group name also.
public SPUser CustomEnsureUser(string fullName,SPWeb web)
{
SPPrincipalInfo objInfo = SPUtility.ResolvePrincipal(web, fullName, SPPrincipalType.SecurityGroup | SPPrincipalType.User, SPPrincipalSource.All, null, false);
if objInfo == null)
{
throw new SPException(SPResource.GetString("User could not be found", new object[]{objInfo.LoginName}));
}
if (objInfo.PrincipalId < 0)
{
web.Groups["Home Owners"].AddUser(objInfo.LoginName, objInfo.Email, objInfo.DisplayName, string.Empty);
}
return web.SiteUsers[objInfo.LoginName];
}
This part is funny ;)
ReplyDeleteif objInfo == null)
{
throw new SPException(SPResource.GetString("User could not be found", new object[]{objInfo.LoginName}));
}
objInfo.LoginName - is null or?!