How do I obtain Central Administration site url programmatically? - sharepoint

I have some code (console app) running on a SharePoint farm machine, and I need the app to figure out the url of Central Administration site for that farm. I remember seeing some SharePoint API doing exactly that, but I can't find it now.
I've seen a bunch of hacks people are using for that, like looking it up in Windows registry, but I need a way via SharePoint API.

in C#
Microsoft.SharePoint.Administration.SPAdministrationWebApplication centralWeb =
SPAdministrationWebApplication.Local;

To expand on the answer from #RDeVaney:
Microsoft.SharePoint.Administration.SPAdministrationWebApplication centralWeb =
SPAdministrationWebApplication.Local;
string centralAdminUrl = centralWeb.Sites[0].Url;

Here is the code from msdn, please refer if it can answer your question
SPWebServiceCollection webServices = new SPWebServiceCollection(SPFarm.Local);
foreach (SPWebService webService in webServices)
{
foreach (SPWebApplication webApp in webService.WebApplications)
{
if (!webApp.IsAdministrationWebApplication)
{
get the URL here
}
}
}

Related

Microsoft Sharepoint 2010-Connecting to a remote site and fetching changelogs

My problem is simple. I have a registered Sharepoint site/domain (say https://secretText-my.sharepoint.com/personal/blabla) and I want to fetch the changelogs as described here Sharepoint Change log
So my question boils down to >>> How can I use this Changelog API to fetch data for a remote Sharepoint site?
How can I achieve this? I have tried Client Object Model and everything related but my goal is to use Sharepoint Change log.
I am hoping for something like,
using (ClientContext ctx = ClaimClientContext.GetAuthenticatedContext("https://secretText-my.sharepoint.com/personal/blabla"))
{
if (ctx != null)
{
ctx.Load(ctx.Web); // Query for Web
ctx.ExecuteQuery(); // Execute
ctx.Load(ctx.Site);
ctx.ExecuteQuery();
SPSite site = new SPSite(ctx.Site.Id);
SPContentDatabase db = site.ContentDatabase;
// Get the first batch of changes,
SPChangeCollection changes = db.GetChanges();
//USE this 'site' object to fetch the change logs
.
.
.
My aim is to somehow instantiate this SPSite object which would then help me get the data I want. Although this code seems a bit too ambitious(or totally wrong) but please don't hold it against me, I couldn't find any solution to this.
Much appreciated!
After a lot of Google searches and after reading so many answers, I have come to know that it isn't possible to connect to a remote Sharepoint server through the Server API. As that API works only when SP server is on the same network (same machine or intranet)
The only solution is to use Client Object Model. It provides(maps) quite a lot operations that the Server API gives.
To connect to the remote site I have used the samples provided at the MSDN site for Client Object Model. Here

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 How do you work out what type of site a site it?

How do you work out what type of site a site is in sharepoint 2010?
The by far easiest way to do this is to use PowerShell:
PS> asnp Microsoft.SharePoint.PowerShell
PS> $web = get-spweb http://server/site
PS> $web.WebTemplate
YOURSITEDEF
PS> $web.WebTemplateId
12345
In the object model, SPWeb.WebTemplate will tell you what template was used to the create the site.
If you are just looking to find out the template without writing code, there is a great tool called SharePoint Explorer that you can browse to find the web template and more.
http://spm.codeplex.com/
I found this answer from sharepoint.stackexchange.com useful: "View the HTML source of the page and search for 'g_wsaSiteTemplateId' - this will give you the site template and configuration used to create the site."
In my case the template is a Team Site:
var g_presenceEnabled = true;
var g_wsaEnabled = false;
var g_wsaLCID = 1033;
var g_wsaSiteTemplateId = 'STS#0';
var g_wsaListTemplateId = 119;
The other answers need to be performed on the server (or using remoting for the PowerShell option). That isn't always practical and this option can performed from any machine with web access to the site.

Install ClientAccessPolicy.xml to Default Web Site using Wix

I'm using Wix to install my web application, and it includes a Silverlight app. Because of cross-domain restrictions, I need to install a ClientAccessPolicy file to ensure that the Silverlight app can talk to the included web services.
Unfortunately, ClientAccessPolicy.xml has to be available from the root of the site, so I can't just place it with my web services or web site. e.g.
Works: http://someserver/ClientAccessPolicy.xml
Doesn't work: http://someserver/MyApp/ClientAccessPolicy.xml
How can I find the directory for the IIS "Default Web Site" to copy the file there as part of the install?
Unfortunately, you have to author a custom action for this. It seems to be just a simple immediate action, which is to find the correct directory path and put it to a property.
UPDATE: The sample C# code for this might look like this:
DirectoryEntry website = new DirectoryEntry(string.Format("IIS://localhost/w3svc/{0}/Root", siteID));
if (website != null)
{
string sitePath = website.InvokeGet("Path") as string;
if (sitePath != null)
{
session["SITE_PATH"] = sitePath;
return ActionResult.Success;
}
}
return ActionResult.Failure;
It assumes that you know the siteID in some way. If it's not always default web site, it is better to let the user choose, for instance. But that's another story.
Note also that this code requires special privileges to access DirectoryEntry - the regular user is not enough.
Hope this helps.

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