Enumerate SharePoint 2010 Groups Using C# - sharepoint

I want to enumerate all of the Groups in my SharePoint 2010 site using Visual Studio 2010 and C#. I don't want to create anything that needs to be deployed unless it's absolutely necessary. Is there a way to, basically, connect to the SharePoint instance and interrogate it for Groups and other objects without deploying anything?
Please don't respond with a PowerShell script. I want to do this using Visual Studio and C#.
Thanks,
Doug

Using the SharePoint 2010 Client Object Model (2010 & 2013) you can write something like this:
static void Main(string[] args)
{
var ctx = new ClientContext("http://server");
ctx.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
ctx.Load(ctx.Web.SiteGroups);
ctx.ExecuteQuery();
foreach (Group g in ctx.Web.SiteGroups)
{
Console.WriteLine(g.LoginName);
}
}

Related

Unable to add a service reference to Dynamics 365 crm in visual studio 2012

I am trying to add service reference to Dynamics 365 CRM using the following API https://[Organization].api.crm8.dynamics.com/api/data/v8.2/ but each time I am getting this window that asks me for credentials....
I tried using the credentials that I use to login to the crm...but they donot work...can someone tell me which credential I should use?..
Why exactly are you trying to add a reference to the CRM web services? Assuming you want to access CRM from server side code, what you need to do is:
Add references to the core CRM SDK assemblies (Microsoft.Crm.Sdk.Proxy.dll and Microsoft.Xrm.Sdk.dll). You get can them from the downloadable SDK or just add the "Microsoft.CrmSdk.CoreAssemblies" NuGet package.
After doing this you'll be able to write code "talking" with CRM. But what you are missing is the actual "connection". There are several ways of obtaining it, but the easiest one is to use the Xrm Tooling helper class, described here - https://msdn.microsoft.com/en-us/library/mt608573.aspx. You'll need to reference the required assemblies or use the "Microsoft.CrmSdk.XrmTooling.CoreAssembly" NuGet package.
After doing all this, you'll be able to successfully code against Dynamics CRM.
CrmServiceClient crmSvc = new CrmServiceClient(ConfigurationManager.ConnectionStrings["MyCRMServer"].ConnectionString);
IOrganizationService orgService = crmSvc.OrganizationServiceProxy;
// Who am I?
WhoAmIResponse whoAmIResp = orgService.Execute(new WhoAmIRequest()) as WhoAmIResponse;
Guid myUserId = whoAmIResp.UserId;
// Get all accounts starting with 'A'
QueryExpression query = new QueryExpression("account");
query.ColumnSet = new ColumnSet("accountid", "name");
query.Criteria.AddCondition("name", ConditionOperator.BeginsWith, "a");
EntityCollection ecoll = orgService.RetrieveMultiple(query);
foreach(Entity account in ecoll.Entities)
{
if(account.Attributes.Contains("name"))
{
Console.WriteLine((string)account["name"]);
}
}
// Update some account
Entity accountToUpdate = new Entity("account");
accountToUpdate["accountid"] = new Guid("_some_guid_here");
accountToUpdate["name"] = "new name";
orgService.Update(accountToUpdate);
If you want to use the type safe approach, you'll need to generate a proxy class - like described here: https://msdn.microsoft.com/en-us/library/gg327844.aspx
Afterwards you'll be able to write code like this:
DataContext data = new DataContext(orgService);
// DataContext is the name of the service context, as defined in the CrmScv tool
var myAccountData = (from a in data.AccountSet
where a.Address1_Telephone1 == "12312313"
select new
{
a.AccountId,
a.Name,
a.EMailAddress1,
a.PrimaryContactId
}).First();
Contact contactToUpdate = new Contact()
{
ContactId = myAccountData.PrimaryContactId.Id,
EMailAddress1 = myAccountData.EMailAddress1
};
orgService.Update(contactToUpdate);
... which is much nicer and less error prone.
From the looks of it you are trying to authenticate through an App outside of the context of Dynamics 365. If you want to authenticate with the Web API this way you will have to connect to Microsoft Dynamics 365 web services using OAuth and authenticate using ADAL
https://msdn.microsoft.com/en-us/library/gg327838.aspx
Here is a walkthrough on how to do it
https://msdn.microsoft.com/en-us/library/mt622431.aspx
Additional note:
If you are using CRM 2013 SDK you may need to update to 6.1.2 for Dynamics 365 Support
https://blogs.msdn.microsoft.com/crm/2017/02/01/dynamics-365-sdk-backwards-compatibility/

Get the SharePoint URL for a Team Project programmatically

I want to find out by coding if a given Team Project has an associated SharePoint. If yes I also want to get the URL for the SharePoint in order to create a specific link to it.
I do not mean the web access of the TFS but the associated SharePoint. Is there a way to find this out without knowing the URL of the SharePoint server that is different from the TFS server?
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
private static string RetrieveProjectPortalBaseAddress(TfsTeamProjectCollection tfs, string teamProject)
{
IRegistration registration = (IRegistration)tfs.GetService(typeof(IRegistration));
RegistrationEntry[] entries = registration.GetRegistrationEntries("TeamProjects");
ServiceInterface endpoint = entries[0].ServiceInterfaces.FirstOrDefault(si => si.Name == teamProject + ":Portal");
return endpoint.Url;
}

Sharepoint 2010 Client Object Module getting a site url list

I’m trying to learn SharePoint Client Object Model, specifically how to get a list of all SharePoint site URLs using a remote connection. This is possible using webservices…but I want to do it using the client object model.
I’ve figured how to get the title lists of a specific sharepoint site using the following code:
client object module):
ClientContext ctx = new ClientContext( server );
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ctx.Credentials = WindowsAuthenticationCredentials(username, password);
Web w = ctx.Web;
var lists = ctx.LoadQuery(w.Lists);
ctx.ExecuteQuery();
//Enumerate the results.
foreach (List theList in lists)
{
}
Output:
Announcements, Master Collection Pages… etc…
How can I do the same to get a site url list?
In web services you can call the following to achieve that, but as I said just trying to figure out how to do the same using client object module. If you can provide c# code that would greatly be appreciated.
WSPSitedata.SiteData sitedata = new SiteData();
sitedata.Url = #SharePointBaseURL + #"_vti_bin/sitedata.asmx";
sitedata.Credentials = our_credentials
_sSiteMetadata metaData = new _sSiteMetadata();
_sWebWithTime[] webWithTime
sitedata.GetSite(out metaData, out webWithTime, out users, out groups, out vgroups);
The SharePoint Client Object Model CSOM is designed to remotly interact with your SiteCollection. Sure, it is possible to connect to various SiteCollections, but it's not possible to look over all SiteCollections sitting within a SPWebApplications.
In 2010 you could still use the ASMX WebServices which are available in earlier versions of SharePoint.
To get a better understanding of the CSOM you should have a look at the MSDN site http://msdn.microsoft.com/en-us/library/ee537247.aspx
Did you really mean a list containing all SiteCollection URLs or was that a misunderstanding?
Thorsten

Sharepoint Object Model applicaton cannot run outside of WSS server

I create a C# console application using Microsoft.SharePoint object model VS WSS extensions on Windows Server 2003. The application is supposed to iterate WSS3.0 sites looking for all available lists. It runs just fine on the server. But if I try to run the exe from another computer on the network, the application crashes instantly on SPSite siteCollection = new SPSite("http://devsharepoint);
Even my try and catch doesn't help as catch is not executed.
Is it intended to run the Sharepoint object model applications only on machines with VS SharePoint extensions installed?
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace ConsoleApplicationWSSobjectModel
{
class Program
{
static void Main(string[] args)
{
string url = "http://sharepoint";
Console.WriteLine("Trying to access: " + url);
try
{
SPSite siteCollection = new SPSite(url);//"http://Server_Name");
SPWebCollection sites = siteCollection.AllWebs;
foreach (SPWeb site in sites)
{
SPListCollection lists = site.Lists;
Console.WriteLine("Site: " + site.Name + " Lists: " + lists.Count.ToString());
}
Console.WriteLine("Press ENTER to continue");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
You cannot use the SP object model ”outside sharepoint” you will have to use web services (or if your go with sharepoint 2010 you can use the new client object model)
Anything built with the SharePoint object model can only run on a server with SharePoint installed. There is however no dependency on the VS extensions.
You can use Client Object Model using C# or VB as your language. Add references Microsoft.sharepoint.client.dll and Microsoft.sharepoint.client.Runtime.dll it can be found under 14(SP2010) or 15(SP2013) hive ISAPI folder.

How to Create a Managed Path through SharePoint Object Model

This is a question for a WSS/SharePoint guru.
Consider this scenario: I have an ASP.Net web service which links our corporate CRM system and WSS-based intranet together. What I am trying to do is provision a new WSS site collection whenever a new client is added to the CRM system. In order to make this work, I need to programmatically add the managed path to the new site collection. I know that this is possible via the Object Model, but when I try it in my own web service, it fails. Sample code extract below:
Dim _ClientSiteUrl As String = "http://myintranet/clients/sampleclient"
Using _RootWeb As SPSite = New SPSite("http://myintranet")
Dim _ManagedPaths As SPPrefixCollection = _RootWeb.WebApplication.Prefixes
If Not (_ManagedPaths.Contains(_ClientSiteUrl)) Then
_ManagedPaths.Add(_ClientSiteUrl, SPPrefixType.ExplicitInclusion)
End If
End Using
This code fails with a NullReferenceException on SPUtility.ValidateFormDigest(). Research suggested that this may be due to insufficient privileges, I tried running the code within an elevated privileges block using SPSecurity.RunWithElevatedPrivileges(AddressOf AddManagedPath), where AddManagedPath is a Sub procedure containing the above code sample.
This then fails with an InvalidOperationException, "Operation is not valid due to the current state of the object."
Where am I going wrong?
One workaround I have managed to do is to call out to STSADM.EXE via Process.Start(), supplying the requisite parameters, and this works.
Update: whilst developing the web service, I am running it using the built-in Visual Studio 2005 web server - what security context will this be running under? Can I change the security context by putting entries in web.config?
Update: I think the problem is definitely to do with not running the web service within the correct SharePoint security context. I decided to go with the workaround I suggested and shell out to STSADM, although to do this, the application pool identity that the web service runs under must be a member of the SharePoint administrators.
Update
I think you have proved that the issue is not with the code.
SPSecurity.RunWithElevatedPrivileges: Normally the code in the SharePoint web application executes with the privileges of the user taking the action. The RunWithElevatedPrivileges runs the code in the context of the SharePoint web application pools account (i think)
The description on MSDN could go into the details a tiny bit more.
The issue with the call may be that the web service is not actually running the code within a SharePoint process, so explaining why it cannot elevate (wild guess alert).
Have a crack at changing the user of your web services application pool and see if that gives any joy.
It is likely to be a permissions issue.
Maybe try:
Dim clientSiteUrl As String = "http://myintranet/clients/sampleclient"
Using SPSite = new SPSite(clientSiteUrl)
webApp As SPWebApplication = SPWebApplication.Lookup(new Uri(clientSiteUrl));
If Not (webApp.Prefixes.Contains(clientSiteUrl)) Then
webApp.Prefixes.Add(clientSiteUrl, SPPrefixType.ExplicitInclusion)
End If
End Using
This is not exact code.
Since the above code is not the exact code, here is the exact working code for a Web Application scopped feature in the Feature Activated event:
On feature activation at the Mange web application features page, activate feature will create a new Explicit managed path in the specified web application (I want to replace the hard coding, maybe with Properties.Feature.Parent, or something similar.)
using (SPSite site = new SPSite("http://dev-moss07-eric/PathHere")) {
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://dev-moss07-eric"));
if (webApp.Prefixes.Contains("PathHere"))
{
//
}
else
{
webApp.Prefixes.Add("PathHere", SPPrefixType.ExplicitInclusion);
}
}
Code can probably be improved, but its my attempt at converting the above code.
If you want to create a managed path (explicit) and a site collection at that path, do the following:
using (SPSite site = new SPSite("http://dev-moss07-eric")) {
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://dev-moss07-eric"));
if (webApp.Prefixes.Contains("ManagedPathHere"))
{
//
}
else
{
webApp.Prefixes.Add("ManagedPathHere", SPPrefixType.ExplicitInclusion);
}
using (SPWeb web = site.OpenWeb())
{
SPWebApplication webApplication = web.Site.WebApplication;
try
{
webApplication.Sites.Add("ManagedPathHere","Site Title Here","This site is used for hosting styling assets.", 1033, "STS#1", "6scdev\\eric.schrader", "Eric Schrader", "eric.schrader#6sc.com");
}
catch (Exception ex)
{
//ex.ToString;
}
}
}

Resources