Issue in web.EnsureUser for FBA users programatically - sharepoint

I am trying to ensure user through web.EnsureUser for FBA users. Here is my code snipplet.
as an example :
string fbUsername = "i:0#.f|ie-fbamembership|userlogin";
SPUser userSP = site.RootWeb.EnsureUser(fbUsername);
But i get an error user does not exists. But i can surely add this user to the site collection manually.
But could not add the user through code (programatically).
Any ideas? i could not find a solution for this in the net.
S.R.G
SharePoint Developer

I'm very late to this question, but I had the same problem today and a colleague of mine finally found a solution.
I just use the AllowUnsafeUpdates property of my SPWeb object and write :
web.AllowUnsafeUpdates = true;
oUser = web.EnsureUser(userId);
In my case, userId is from a PeoplePicker, I construct it like this :
PickerEntity selectedEntity = (PickerEntity)peEditor.ResolvedEntities[i];
string userId = selectedEntity.Key;
Hope it can helps someone !

Related

Create post entity to crm

I am getting unexpected error while trying to create post in Dynamics CRM. Below is the code:
Entity objEntity = new Entity("post");
objEntity["regardingobjectid"] = IncidentID;
objEntity["text"] = URLs;
objEntity["source"] = new OptionSetValue(2);
objEntity["type"] = new OptionSetValue(4);
Guid newPostID = lOrgService.Create(objEntity);
Please suggest what could be the problem.
It could be a multitude of things, which is hard to pinpoint based on the small amount of code you have submitted, but my best guess is that IncidentID is a GUID, where regardingobjectid should be an EntityReference.
Try replacing:
objEntity["regardingobjectid"] = IncidentID;
with
objEntity["regardingobjectid"] = new EntityReference("incident", IncidentID);

Is there any log of login attempts to sharepoint 2007?

Where can I find a log of login attempts to share point 2007?
Thanks.
PS: I have another question too, I 'd be really grateful if anybody helps me on it:
Sharepoint users are logged out
I haven't been able to find much without a third party tool. Our group is looking into acquiring DocAve by AvePoint.
In the mean time you can at least get an idea in your site analytics area of your site settings dashboard to see how many people have encountered the /_layouts/accessdenied.aspx page. It wont tell you much, but perhaps you can find a way to customize and add a snippet of code that will take a user's ID when they hit that page. Its not perfect, so I'd suggest a 3rd party tool unless you can scan all of your web front ends etc.
We had a similar requirement once, where we needed to log the last visited time of all the users on the site. So after some period of time, say 90 days, if a particular user had not logged into the site, the admin could delete his profile.
We overcame this problem with a very simple approach. You can follow the sample code for your reference.
You would need to create a list in your site by the name "UserLoginDetails" and create a column "LastLogIn" in that. Code is self explanatory.
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Xml.Serialization;
using Microsoft.SharePoint;
namespace Ubaid.WebParts
{
[Guid("883a77d6-271d-4b88-9ca2-d5150a00520b")]
[DefaultProperty("Text"), ToolboxData("<{0}:UserLastVisited runat=server></{0}:UserLastVisited>"), XmlRoot(Namespace = "Ubaid.WebParts")]
public class UserLastVisited : System.Web.UI.WebControls.WebParts.WebPart
{
protected override void CreateChildControls()
{
base.CreateChildControls();
string siteName = SPContext.Current.Web.Url;
using (SPSite site = new SPSite(siteName))
{
SPWeb web = site.OpenWeb();
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
SPList UserLoginDetailsList = web.Lists["UserLoginDetails"];
SPQuery query = new SPQuery();
string uname = SPContext.Current.Web.CurrentUser.LoginName;
query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + uname + "</Value></Eq></Where>";
SPListItemCollection listItemColl = UserLoginDetailsList.GetItems(query);
if (listItemColl.Count > 0)
{
SPListItem item = listItemColl[0];
item["LastLogIn"] = DateTime.Now.ToLocalTime();
item.Update();
}
else
{
SPListItem item = UserLoginDetailsList.Items.Add();
item["Title"] = uname;
item["LastLogIn"] = DateTime.Now.ToLocalTime();
item.Update();
}
}
}
}
}
You can insert this webpart in your masterpage, as the data in this list needs to be updated on every page load.
Not sure which is the best way to do it / performance issues, but since ours was a small site we could manage with this pretty well.

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.

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

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

Add items to list programmatically

I am using form base authentication in my Sharepoint site. On my login page there are custom fields to be filled by unauthenticated user. These fields i want to add in to my list. I am using following code to insert record in list.
protected void AddVendor(object sender, EventArgs e)
{
string strList = "http://comp01:5353/Lists/Vendors/";
using (SPSite site = new SPSite(strList))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPUser user = web.AllUsers["demouser"];
SPList list = web.Lists["Vendors"];
SPListItem Item = list.Items.Add();
Item["First Name"] = txtVendorName.Text;
Item["Last Name"] = txtVLastName.Text;
Item["business"] = txtDescription.Text;
Item["Description"] = txtDescription.Text;
Item["Mobile No"] = txtMobileNumber.Text;
Item["Approved"] = "No";
Item["Created By"] = "demoadmin";
Item["Modified By"] = "demoadmin";
Item.Update();
}
}
}
but is is giving me an error saying that Thread was being aborted. I don't know what exactly missing. but is it because I am performing add action and user is not authenticated...?
I donĀ“t know if it will help you but the code that says (f.e.) Item["Modified By"] will not work since that is the internal name which is Modified_x0020_By. This goes for all the fields with "spaces" in them.
This might be one of your issues...
Where have you written this code, is it inside some event ? Login Control Provides two events that will help you to solve this
OnLoginError="OnLoginError" OnLoggedIn="OnLoggedIn"
I did similar functionality where I wanted to capture the user name loggin to the site and log it to the DB Table. And with respect to the ThreadAbort Exception, it happens when you use Response.Redirect while a code is being executed. In you case I doubt that its being thrown because you are trying to do the above code but the FBA system tries to redirect the user to the default.aspx . Try out above said Event of the Login Control it should help you.

Resources