Get user email programmatically if I have user guid? (SharePoint) - sharepoint

Currently I have a method to get all the users in a site collection and databind this to a dropdown.
private void getUsers()
{
SPGroupCollection collGroups = SPContext.Current.Web.Groups;
foreach (SPGroup oGroup in collGroups)
{
foreach (SPUser oUser in oGroup.Users)
{
ddlSiteOwner.Items.Add(new ListItem(oUser.Name, oUser.ID.ToString()));
}
}
}
Is there a way to get users based on their guid?
I select a user in the dropdown with guid as value and I would like to use this to search for the users email.
I tried something like
private string getUserEmail(string userGuid)
{
string userEmail = null;
SPGroupCollection collGroups = SPContext.Current.Web.Groups;
foreach (SPGroup oGroup in collGroups)
{
foreach (SPUser oUser in oGroup.Users.GetByID(userGuid))
{
userEmail = oUser.Email;
}
}
return userEmail;
}
But with GetByID it wants 32bit integer and not a guid so how would I achieve this?
Thanks in advance.
Edit: saw that users don't have guids but sids now.

The SPUser.ID property you are using in your dropdown is an integer, not a guid.
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spuser.id.aspx
So the GetByID should work normally, just parse the value as an integer.
int.Parse(), or int.TryParse()

Related

Display a specific result using foreach in Dictionary C#

Problem that I'm unable to solve is that when I search a contact, if found than I need that contact to be the only output but it's displaying whole record. What should I do?
here is my code
namespace Telephone_Directory
{
class Program
{
public bool info()
{
Console.WriteLine("ENTER THE NAME TO BE SEARCHED");
Dictionary<string, uint> contact = new Dictionary<string, uint>();
contact.Add("usman", 03453648729);
contact.Add("Iqtiqa", 03159825052);
contact.Add("Aamir", 03343315412);
contact.Add("Ghous", 03323142783);
var items = from pair in contact
orderby pair.Value ascending
select pair;
string chk = Console.ReadLine();
if (contact.ContainsKey(chk))
{
foreach (KeyValuePair<string, uint> pair in contact)
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
} return true;
}
else
return false;
}
static void Main(string[] args)
{
Program ob =new Program();
bool a=ob.info();
if (a == true)
{
Console.WriteLine("Your contact is found successfully");
}
else
Console.WriteLine("Not found");
Console.ReadLine();
}
}
}
You are checking if the Contact is available but you are iterating over the whole collection as an output. So you can completely remove the first query (var item = ...) because it does not have any effect because you are not using it anywhere.
I would propose accessing everything directly by the Dictionary Key like this
uint srchNumber;
contact.TryGetValue(chk, out srchNumber);
if (srchNumber != null)
Console.WriteLine("{0}: {1}", chk, srchNumber);
this will get you what you want.
But I would suggest to change the implementation because a Dictionary may be not optimal if you will have multiple items with the same name because it only allows you to have every key once. Instead I would suggest to use something like SortedList> or List<...>. Then you may query all possible results with a LINQ-Statement like
var results = from c in contact select c where c.key == chk
this will get you all Key-Value-Pairs belonging to a certain name.
But it is a matter of what you are trying to achieve.

Getting Task Modified By

I'm trying to retrieve a name of the persdon who completed a task. In my Tasks list i can see 'Modified By' which is Editor.
In Sharepoint Manager I can see the persons name in the Editor column.
How can I get this value in the code
I create a task and after the ontaskchanged I have a code block. I've tried many permutations but cannot retrieve this data.
private void UpdateCreatedByAndModifiedByFieldData(string strSiteUrl, string strListName, string strUserFieldName)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(strSiteUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[strListName];
foreach (SPListItem listItem in list.Items)
{
//Read user id from a list column of user type and create SPUser object
SPUser user = web.EnsureUser(listItem[strUserFieldName].ToString().Trim());
if (user != null)
{
string userValue = user.ID + ";#" + user.Name;
//Assign the above user to the "Created By" column
listItem["Author"] = userValue;
//Assign the above user to the "Modified By" column
listItem["Editor"] = userValue;
//Call the update method to apply the above changes
listItem.Update();
web.Update();
}
}
}
}
});
}
catch (Exception ex)
{
throw ex;
}
}
Check this also
How to get SharePoint file creator name using AllDocs table?

How can I choose user group name in list in SharePoint 2010?

I have list of clients through which i have created SharePoint user groups with this code.
namespace CreateGroupCSharp.EventReceiver1
{
public class EventReceiver1 : SPItemEventReceiver
{
public override void ItemAdded(SPItemEventProperties properties)
{
using (SPSite site = new SPSite("http://abc/"))
{
SPWeb web = site.AllWebs[0];
SPList customList = web.Lists["Client"];
string strCount = properties.ListItem.Title.ToString();
string status = properties.Status.ToString();
SPGroup groupOwner = web.SiteGroups.GetByID(int.Parse(web.Properties["vti_associateownergroup"]));
string groupName = strCount;
web.SiteGroups.Add(groupName, groupOwner, null, "Custom SharePoint Group for Demo");
SPGroup wcmGroup = web.SiteGroups[groupName];
SPRoleDefinition designerRoleDefinition = web.RoleDefinitions["Contribute"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(wcmGroup);
roleAssignment.RoleDefinitionBindings.Add(designerRoleDefinition);
web.RoleAssignments.Add(roleAssignment);
wcmGroup.Update();
web.Update();
}
base.ItemAdded(properties);
}
}
}
Is it possible to create users for each client in SharePoint list itself?
How can I assign these created groups to the the users in list?
I would add a Person or Group column named Users to your list. Allow multiple selections and allow people only (no groups) to be selected. You can then add the users to the group using the following code in your event receiver:
private void AddUsers(SPWeb web, SPGroup group, SPListItem item)
{
object value = item["Users"];
if (null != value)
{
SPFieldUserValueCollection userValues =
new SPFieldUserValueCollection(web, value.ToString());
foreach (SPFieldUserValue userValue in userValues)
{
SPUser user = userValue.User;
if (null == user)
{
user = web.EnsureUser(userValue.LookupValue);
}
group.AddUser(user.LoginName, user.Email, user.Name, null);
}
}
}

Is it possible to get user email with loginname programmatically in sharepoint?

I have a search function that returns the email for a user when I have the user's ID
private string getUserEmail(string userID)
{
string userEmail = null;
SPGroupCollection collGroups = SPContext.Current.Web.Groups;
int userIDint = Convert.ToInt32(userID);
foreach (SPGroup oGroup in collGroups)
{
userEmail = oGroup.Users.GetByID(userIDint).Email.ToString();
}
return userEmail;
}
with Users I can do either GetByID or GetByEmail but what should I do if I have the domain name such as MyDomain\myUsername and want the email for that user?
Any help or links would be appreciated.
Thanks in advance.
http://msdn.microsoft.com/en-us/library/ms414398.aspx
SPContext.Current.Web.AllUsers["loginname"].Email
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.ensureuser.aspx
SPContext.Current.Web.EnsureUser("loginname").Email

Get username from SharePoint User field in List

I have a custom sharepoint workflow that I'm developing in Visual Studio. The workflow is running against a document library which has a custom content type connected to it. The content type includes a user lookup field ("owner").
I'm trying to have my workflow assign a task to the "owner" lookup field. However, I've only been able to get the display name for the user, not the account username.
Can anyone help?
Refer to this Article on how to get the User Details from the Field.
public static SPUser GetSPUser(SPListItem item, string key) {
SPFieldUser field = item.Fields[key] as SPFieldUser;
if( field != null) {
SPFieldUserValue fieldValue = field.GetFieldValue(item[key].ToString()) as SPFieldUserValue;
if(fieldValue != null)
return fieldValue.User;
}
return null;
}
Your Code should be like this
SPUser spUser=GetSPUser(splistItem,"Owner");
String sUserName=(spUser!=null)?spUser.UserName:null;
My solution:
public static SPUser GetSPUser(SPListItem item, string key)
{
SPUser user=null;
SPFieldUserValue userValue = new SPFieldUserValue(item.Web, item[key].ToString());
if (userValue != null)
{
SPUser user = userValue.User;
}
return user;
}
How To Call:
SPUser spUser=GetSPUser(splistItem,"Owner");
This is tested code and working fine.

Resources