I want to get a user by its id in SharePoint 2013 via CSOM C#:
clientContext ctx = new ClientContext(siteUrl);
Web web = clientContext.Web;
User gUser = web.GetUserById(selectedUserId);
clientContext.Load(web);
clientContext.Load(gUser);
clientContext.ExecuteQuery();
foreach (Group gGroup in gUser.Groups)
{
...
}
But i get always the following error message:
The collection has not been initialized. It has not been requested or
the request has not been executed. It may need to be explicitly
requested.
What i want to do is:
get the user from sharepoint by its user id
loop through user.groups
(get users groups)
I am googling around since this morning, but cannot find any solution/description how to solve this.
This is similar to EF eager vs lazy loading issue. In SP, only simple properties of objects are loaded by default (string, date, number, boolean). Other properties will need to be explicitly loaded. To do that, you need to do this:
clientContext.Load(gUser.Groups);
That will load the Groups collection as well. Now you can access it.
i have a sharepoint 2013 project and i need to create a list of all employees created on active diretory in last 30 days.
What is the best way to do that?
I think that i can do a c# query to active directory using the system.DirectoryServices but because i'm implementing this on a sharepoint farm i dont know if is the best way to do that.
On sharepoint i have the User Profile Service running, so my question is if i can do this with the User Profile Service or use the "old c# way"
Thanks
Flávio
If you run "user profile service synchronization" service, your "user information list" will be uptade. Then you can filter the list by created date. Also you can synch. any AD field with "user information list"
(simple : http://yasingokhanyuksel.blogspot.com.tr/2015/11/sharepoint-survey-add-active-directory.html)
"user information list" is hidden, so type http://yourSiteUrl/_catalogs/users/simple.aspx
more information
http://zimmergren.net/technical/sharepoints-hidden-user-list-user-information-list
ygy59 is right about the hidden "user information list" being the only source of a date for a user in SharePoint. To access it programmatically you would do something like this:
using (ClientContext context = new ClientContext(projURL))
{
CamlQuery query = new CamlQuery();
query.ViewXml = "";
ListItemCollection items = context.Web.SiteUserInfoList.GetItems(query);
context.Load(items);
context.ExecuteQuery();
foreach (ListItem item in items)
{
DateTime hireDate = (DateTime)item["Created"];
if(hireDate > DateTime.Today.AddDays(-30))
{
Console.WriteLine(item["Name"]);
}
}
Console.ReadLine();
}
It's important to note that this is the date the item was added to SharePoint and not the day the account was created. That is something you can control via your server settings though.
Flávio,
When I have created these sorts of solutions for SharePoint environments in the past I have often had to edit them once live to take account of "new requirements" which weren't specified at the beginning.
I would suggest that you architect your solution so that it is simple for the user and or yourself to add extra fields to display, and select by other time periods e.g. new users in past 7 days, new users in past 90 days. OR display firstname, logon, lastname, department, manager, email, phone etc
We did this for one project by allowing specific URL parameters to be used e.g. myreport.aspx?numdays=60&display=firstname,manager,email
Good luck
Dorje
SharePoint's user profile service is useful for a lot of things, but I'm not sure it's warranted here (you're not creating audiences, aggregating user information from multiple sources, exposing editable properties, etc.).
Assuming this is an on-premises SharePoint farm coupled with an on-premises Active Directory, I would just hit up Active Directory directly for this information.
As you mentioned, you'll need to add a reference to System.DirectoryServices in your C# code.
string subpath = "CN=something, CN=com"; // CNs appropriate to your environment here
string filter = ""; // append additional LDAP filter parameters as necessary
// build LDAP filter query
DateTime date = DateTime.UtcNow;
date.AddDays(-30);
string LDAPQuery = "(&(whenCreated>="+date.ToString("YYYYMMdd")+"000000.0Z)" + filter + ")";
// get DNS host name
DirectoryEntry entry = new DirectoryEntry("LDAP://RootDSE");
Object value = entry.NativeObject;
string dnsHostName = entry.Properties["dnsHostName"].value.ToString();
// search Active Directory
DirectorySearcher searcher = new DirectorySearcher();
searcher.Filter = LDAPQuery;
searcher.SearchRoot = new DirectoryEntry("LDAP://"+dnsHostName+"/"+subpath);
SearchResultCollection results = searcher.FindAll();
// then iterate through results and
// either display them on a page or create items in a list
As Dorje McKinnon mentioned, it's a good idea to make the code flexible enough to accommodate new requirements. I'd parameterize the LDAP query and subpath strings and put them in a SharePoint list somewhere, then have your C# code retrieve them from the SharePoint list before it executes the query.
If this code is going to be run frequently, and if it's only really being used for reporting purposes, you might want to avoid creating SharePoint list items for each of the AD profiles discovered, and instead just show the results on a page, such as in a grid view.
I am trying to access data remotely from sharepoint 2010 site using client object model. For some restrictions I am not able to use CAML query even if I use I am not able to filter for proper audiences based on user login (if you can help me regarding the CAML query is also fine :: i do not know how to get current user audience name and all audiences using CAML/client object model. This code sits on the mobile site and calling the share point site as shown in my code). This following code works good but not able to get the content from the webpart. Can someone help regarding this.
using (ClientContext ctx = new ClientContext("https://mysite.com/Pages/Default.aspx"))
{
ctx.ExecutingWebRequest += new EventHandler<WebRequestEventArgs> (clientContext_ExecutingWebRequest);
File home=ctx.Web.GetFileByServerRelativeUrl("/Student/Pages/default.aspx");
//get the web part manager
Microsoft.SharePoint.Client.WebParts.LimitedWebPartManager wpm = home.GetLimitedWebPartManager(Microsoft.SharePoint.Client.WebParts.PersonalizationScope.Shared);
IEnumerable<Microsoft.SharePoint.Client.WebParts.WebPartDefinition> wpds = null;
//create the LINQ query to get the web parts from
//the web part definition collection
wpds = ctx.LoadQuery(wpm.WebParts.Include(wp => wp.Id,wp => wp.WebPart));
//load the list of web parts
ctx.ExecuteQuery();
//enumerate the results
foreach (Microsoft.SharePoint.Client.WebParts.WebPartDefinition wpd in wpds)
{
string title= wpd.WebPart.Title;
Microsoft.SharePoint.Client.WebParts.WebPart wpart = wpd.WebPart;
????? How to render and receive the data (looking for the same data When you browse the site with the browser)
}
Code continues...
I am also struggling with this issue. It really looks like this is not possible with client object model. Actually i've asked it to some SharePoint staff member at Build Conference 2012.
But, with the SharePoint Designer it's actually possible to download the wanted WebPart. Fiddler may come handy to track down which service will deliver you the bits.
Take a look at this post here on SharePoint StackExchange
Unfortunately the post will not give you any concrete way to solve it.
Wish you good luck!
I'm trying to get one user group in SP 2010. I currently have five groups but SPGroupCollection only contains two when i read the groups with oSPWeb.Groups. Anyone know if there is any security or other reason for this?
Code:
using (SPSite oSPsite = new SPSite(_serverUrl))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
SPGroup spGroup = oSPWeb.Groups["AIT Owners"];
}
}
Yes, there is a security reason. The Groups property will only return groups that have assigned permissions within the website, while the SiteGroups property returns all groups within the site collection.
For more information, there are a number of blog articles that cover the difference.
I am using MOSS 07 & VisualStudio 07 (c#) on a WindowsServer2003
My Problem is that I want to have access from one Sharepoint to another.
In SharePoint_1 is a SPList I want to read out from SharePoint_2.
The results of my research are IMPERSONATION and RUN_WITH_ELEVATED_PRIVILEGES.
With impersonation I can read out the html code of the SPSite I am connected with, but how can I get the List I want?
When I try to RunWithElevatedPrivileges I have to take a user form the site of SharePoint_1. But I cant get the User (even if I got his name) because of a FileNotFoundException.
How can I solve the problem?
Thanks
There is something I forgot to tell.
In the List are Attachments and I need access to them, too.
What would be the best way to solve this issue?
Hopefully its not very tricky, because I used Sharepoint 5 weeks ago the first time and dont so feel very familiar with it :)
Thanks
You dont need to specify a user when using SPSecurity.RunWithElevatedPrivileges. I think you will be ok if you use:
[url] = url to the other site collection
SPSecurity.RunWithElevatedPrivileges(() => {
using (var site = new SPSite("[url]")) {
using (var web = site.OpenWeb()) {
// Access list here
}
site.RootWeb.Dispose();
}
});