EnsureUser not returning valid User - sharepoint

I am trying to get a user back in SharePoint Client OM using EnsureUser. My code is:
ClientContext clientContext = new ClientContext(siteUrl);
User spUser = clientContext.Web.EnsureUser(user);
Where siteUrl and user are both strings set as appropriate.
The result is spUser is the shell of a User object but all its properties (for example Email, Title, etc.) are not initialized. In VS they are showing {"The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."}
What would be causing this? I thought EnsureUser would create the user if it is not already there. I know in Server OM sometimes you need to use "AllowUnsafeUpdates", is there something like that for Client OM?

It is almost a year late, but just in case someone else is searching for the same answer.
After getting a reference to the user object you need to do the following before accessing the properties of the user.
clientContext.Load(spUser);
clientContext.ExecuteQuery();
or if you want to get the email and title only to reduce the pay load.
clientContext.Load(spUser, u => u.Email, u => u.Title);
clientContext.ExecuteQuery();
Basically, it establishs a request to the SharePoint Web and ask for the properties of the spUser. The request will be send when ExecuteQuery() is called.

Related

IBM Domino 10 - Java XPage create session or compare credentials of another user

I'm writing Java code in an XPage Rest Service basing on https://setza-projects.atlassian.net/wiki/spaces/RSD/pages/44007659/IBM+Domino which is an REST service written in Java used to handle Resource Reservations database. However the way it currently works, it creates the reservations for the current session user only:
private JsonObject createIntanceAppointment(ResourceDefinition rd, Database reDatabase, Date dtStart, Date dtEnd, String subject) throws NotesException {
Session session = reDatabase.getParent();
Name nnOrganizier = session.createName(session.getEffectiveUserName());
Name nnREsource = session.createName(rd.getFullName());
DateTime dt_startDateUTC = session.createDateTime(dtStart);
DateTime dt_endDateUTC = session.createDateTime(dtEnd);
Document doc = reDatabase.createDocument();
doc.replaceItemValue("form", "Reservation");
doc.replaceItemValue("Purpose", subject);
doc.replaceItemValue("ReservedFor", nnOrganizier.getCanonical());
doc.replaceItemValue("ResourceName", nnREsource.getAbbreviated());
doc.replaceItemValue("ResNameFormat", nnREsource.getAbbreviated());
I'm doing a very similar integration with Domino, although I'd prefer to have the reservations created for individual users (they provide their username & password on the room-booking application on a touch screen).
I could just authenticate as the user in my REST client, but if I understand the installation requirements for that RoomZ api correctly, the 'api managing user' needs to be exclusively signed to the database, so I would need to do that for every user in Domino that could make reservations.
I tried using NotesFactory.createSession("", "user", "password"); but that doesn't work, it gives Cannot create a session from an agent error
If I cannot create another session, is there any way I could verify that the username and password passed to the API in the payload is correct (to verify if the user can login)? Then I could just set the organizer/reserved for to this user.
Also, is there any way to make these reservation also appear in the organizer's Notes calendar? Currently they are succesfully created in the Reservations database and all, but the organizer is unaware of them despite he's assigned to the reservation.
You do not need to create a session for every user. The important thing is the nnOrganizer = session.createName(" ") which should contain the user. Probably you'll also need to set additional fields like chair or from for the reservation.
If you want to have some entries in the organizers calendar, send them a proper invitation or create a calendar entry in their mailfile.

SharePoint session persist across several users?

I have a custom web part that starts by getting a current user login name like this:
protected static string iAm = System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].Split("\\".ToCharArray())[1].ToLower().
Then it passes this string to a bbl class and fetches a user id:
`IDataReader _drInfo = cisf_BLL.bll_MyInfo.drGetMyInfo(iAm);
while (_drInfo.Read())
{
iUser_Ident = _drInfo.GetInt32(30);
}
`After that it passes the user id integer to another method that fetches user's training record:
_drUserTraining = bll_Training.drGet_required_training_records(iUser_Ident);
_drUserTrainingCompleted = bll_Training.drGet_completed_training_records(iUser_Ident);
This information is then displayed in a tab container with three tab such as "Overdue", "Required", and "Completed".
The problem I'm having is this: I'm logged into SharePoint collaboration site with my domain user name and all my training is displayed just fine. If my someone else then logs in to the SP Portal that user sees my training and not his, even though this user has logged in with his unique credential using a common access card, just as I.
Somehow some strange session seems to persist and I was hoping someone out here has encountered this anomaly.
Thanks in advance!
Risho
You are misusing static - a static property is stored once per web server process, not once per user.
Not an answer, but code improvement: there is much simplyer way to get current user name/id
SPUser user = Microsoft.SharePoint.[SPContext][1].Current.Web.CurrentUser;
user.ID;
user.Email;
user.Name
user.LoginName;
user.Grups;
....
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spuser_members.aspx

Accessing the user from a liferay portlet?

I'm attempting to develop a portlet for liferay.
How can I get access to the username and password (and other data liferay has) of the user that's currently logged in?
I'd also like to be able to execute some code when users change their password.
You can get the User ID by calling getRemoteUser() in the PortletRequest object. This is defined by JSR-168 therefore it's cross-portal compatible.
Once you have the ID you can fetch the additional informations by calling getUserById() (a Liferay specific service). This is something not covered by Portlet API specification, so it locks you to the Liferay.
Liferay Specific stuff, here is a code sample to be written in your Portlet Class to retrieve the User:
ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(WebKeys.THEME_DISPLAY);
User user = themeDisplay.getRealUser(); // it gives you the actual Logged in User
//you can also use
// User user = themeDisplay.getUser(); // this would fetch the User you are impersonating
long userId = user.getUserId();
String userName = user.getEmailAddress();
Alternatively;
long userId = themeDisplay.getRealUserId(); // themeDisplay.getUserId();
User user = UserLocalServiceUtil.getUser(userId);
Impersonate User:
Liferay has a concept that admins (or persons with the correct set of permissions) can impersonate a particular user of the portal. Through this they can see how the portal looks to that user.
For executing the code when user change their passwords:
One approach would be to create a hook plugin and overriding the services by extending the UserLocalServiceWrapper class. Then checking for the password change and executing your code inside the your custom class.
Hope this helps.
Or you can just use javascript:
Liferay.ThemeDisplay.getUserId()
There are many nice to haves in the Liferay namespace, take a look at the not so well documented API:
https://www.liferay.com/community/wiki/-/wiki/Main/Liferay+JavaScript+API
https://www.liferay.com/web/pankaj.kathiriya/blog/-/blogs/usage-of-liferay-js-object
Also, take a look at the web services available under localhost:8080/api/jsonws which you can invoke with a javascript call:
Liferay.Service(
'/user/get-user-by-id',
{
userId: 10199
},
function(obj) {
console.log(obj);
}
);
One simple and easy way to get the user in Liferay is PortalUtil.getUser function.
User user = PortalUtil.getUser(portletRequest);

Retrieve GMail data through DotNetOpenId

I'm Trying to login with dotNetOpenId to GMail accounts. It works but I'm not able to retrieve any claims. I know I could retrieve email addresses or user names as well, but no claims are being returned only the ClaimedIdentifier is available. Anyone know how to retrieve this data from Gmail accounts? If you could please provide me an example of ClaimsRequest configuration I would be grateful.
Thanks
// Either you're creating this already or you can get to it in
// the LoggingIn event of the control you're using.
IAuthenticationRequest request;
// Add the AX request that says Email address is required.
var fetch = new FetchRequest();
fetch.Attributes.Add(
new AttributeRequest(WellKnownAttributes.Contact.Email, true));
request.AddExtension(fetch);
Google then authenticates the user and returns the email address, which you can get with:
var fetch = openid.Response.GetExtension<FetchResponse>();
if (fetch != null)
{
IList<string> emailAddresses = fetch.GetAttribute(
WellKnownAttributes.Contact.Email).Values;
string email = emailAddresses.Count > 0 ? emailAddresses[0] : null;
}
You can see my blog post on the subject for a bit more information. The important thing to note here is that Google will only tell you the user's email address if you mark it as required (as I have done in the above snippet). But this also means that if the user does not want to share his email address, he cannot log in at all. Sorry, that's the way Google set it up. Other Providers that people use have different behaviors, unfortunately.

SPContext.Current.Web.CurrentUser returns misleading value

I'm trying to find out current user name for my sharepoint application. There are more that one way how to do this. However the sharepoint way returns misleading value.
System.Security.Principal.WindowsIdentity.GetCurrent().Name // returns MY_COMPUTER\\my_user
HttpContext.Current.User.Identity.Name // returns MY_COMPUTER\\my_user
HttpContext.Current.Request.ServerVariables["AUTH_USER"] // returns MY_COMPUTER\\my_user
Microsoft.SharePoint.SPContext.Current.Web.CurrentUser.LoginName // returns SHAREPOINT\\system
What is the cause of this behavior? Will I encounter problems if I'll use non-sharepoint way?
Are you browsing as the admin account that you used to install the system? SharePoint will "helpfully" rename that SHAREPOINT\System. Use a different account and all of the methods will return the same value.
This is expected if the user is the application pool account running the current web application.
BTW, it's supposed to be the same name as displayed in the welcome control (upper left control)
The problem is because you are probably getting the current user from an elevated SPWeb inside a RunWithElevatedPrivileges code. You can use the snippet below to get the real user
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))
{
using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID))
{
string currUser = site.CurrentUser; //not the ElevatedSite.CurrentUser
}
}
});
This will show the real user name instead of the SHAREPOINT\System user.
I think you might have include this code under SPSecurity.RunWithElevatedPriviliges. Check it out once. I am not sure though
The other way SPWeb.CurrentUser could return SHAREPOINT\system is if the web is elevated, though I'm not sure why SPContext.Current would be elevated. On what kind of page are you seeing this behavior?

Resources