Getting the GUID for any given path to sharepoint - sharepoint

I'm trying to get the GUID of a given sharepoint URL. I don't mind using the API or the webservices or Sharepoint's database.
if i were to write a function, it's signature would be:
//get a GUID from path.
string GetGuidFromPath(string path){}
I had a lead: SPContentMapProvider but it doesn't seem to get the right info.
Thank you!

Depends - what's the context of the current request? Is your code running in the context of a SharePoint request? If so you can just use SPContext.Current.Web.ID
Otherwise, is your code at least running on one of the SharePoint servers? If so you'll need to use:
// Given the URL http://mysharepointsite.com/sites/somesite/somesubsite
using(SPSite site = new SPSite("http://mysharepointsite.com/sites/somesite"))
{
using(SPWeb web = site.OpenWeb("somesubsite"))
{
Guid webId = web.ID;
}
// Or
Guid rootWebId = site.RootWeb.ID;
}

Related

What is the Sharepoint Document Location endpoint really returning?

I'm trying to get the OneNote notebook information that is linked to my organization's CRM accounts. Each account has a OneNote book created for it that can be accessed inside of CRM.
From what I understand, I can use the SharePointDocumentLocation endpoint (found here: https://learn.microsoft.com/en-us/dynamics365/customer-engagement/web-api/sharepointdocumentlocation?view=dynamics-ce-odata-9) to get the location of the specific file if I ask for location type to be 1.
However, SharePointDocumentLocationId and SiteCollectionId don't seem to be pointing to anything on my company's sites. Should I be getting my data somewhere else?
I started searching through my company's SharePoint structure to see if I can get any hints as to where these documents may be located. My initial Postman request (getting the sites off of the root site) don't show the site that hosts our CRM documents (sites/crmdocs). I was able to find where this was stored eventually, but trying to get the OneNote notebooks stored there returns an error since we have more than 20,000 notebooks there, so I can't fetch them all. As far as I know, I'm able to get notebooks if I have the specific ID I want.
Once I fetch the CRM information, I try to send a request like this:
https://graph.microsoft.com/v1.0/sites/{myCompanyUrl},{siteCollectionId},{sharepointDocumentLocationId}/onenote/notebooks/
SiteCollectionId and SharePointDocumentLocationId are from my CRM SharePointDocumentLocation request
The error I receive is:
The requested site was not found. Please check that the site is still accessible.
Assuming your environment is using the out of the box sharepoint site and sharepoint document location hierarchy, you can access One Note files using the following link structure:
[SharePointAbsoluteUrl]/[EntityLogicalName]/[RelativeUrl]_[RegardingObjectId]/[RelativeUrl]
How to get [SharePointAbsoluteUrl] :
Querying for sharepointdocumentlocations is actually not enough because Dynamics 365 stores this information in another entity called sharepointsite. This is how you can obtain it:
var query = new QueryExpression("sharepointsite")
{
ColumnSet = new ColumnSet("absoluteurl")
};
query.Criteria.AddCondition("IsDefault", ConditionOperator.Equal, true);
var entityCollection = _service.RetrieveMultiple(query);
var absoluteUrl = entityCollection[0].Attributes["absoluteurl"];
In Web API it is equivalent to:
GET https://[Your Org]/api/data/v9.0/sharepointsites?$select=absoluteurl&$filter=isdefault%20eq%20true
There can only be a default sharepoint site so this query will return a single record.
How to get the remaining parts:
Fetch for sharepointdocumentlocations that have Location Type dedicated to One Note Integration:
var query = new QueryExpression("sharepointdocumentlocation")
{
ColumnSet = new ColumnSet("regardingobjectid", "relativeurl")
};
query.Criteria.AddCondition("locationtype", ConditionOperator.Equal, 1);
var entityCollection = _service.RetrieveMultiple(query);
In Web API it is equivalent to the following get request, don't forget to add add Prefer: odata.include-annotations="*" to your HTTP Request Headers so that it gets the lookup lookuplogicalname field:
GET https://[Your Org]/api/data/v9.0/sharepointdocumentlocations?$select=relativeurl,_regardingobjectid_value&$filter=locationtype%20eq%201
This query can return many records, I've only used the first one in the examples below for explanation purposes.
[EntityLogicalName] will be your ((EntityReference)entityCollection[0].Attributes["regardingobjectid"]).LogicalName;
In Web Api will be your value._regardingobjectid_value#Microsoft.Dynamics.CRM.lookuplogicalname value.
[RelativeUrl] will be your entityCollection[0].Attributes["relativeurl"];
In Web Api will be your value.relativeurl value.
[RegardingObjectId] can be obtained with this expression ((EntityReference)entityCollection[0].Attributes["regardingobjectid"]).Id.ToString().Replace("-", "").ToUpper();
In Web Api id will be your _regardingobjectid_value value and you have to remove dashes and convert it to upper case in whatever language you are doing the request.
You should end up with an URL like this https://mycompany.sharepoint.com/account/A Datum Fabrication_A56B3F4B1BE7E6118101E0071B6AF231/A Datum Fabrication

Getting extension properties using Azure AD B2C Graph API does not work

I am attempting to discover which extension properties I have available to my application. I originally followed this guide to get the extension attributes:
https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/#use-custom-attributes
But that just returns the following JSON:
{
"odata.metadata": "https://graph.windows.net/screenmediatestb2c.onmicrosoft.com/$metadata#directoryObjects/Microsoft.DirectoryServices.ExtensionProperty",
"value": []
}
I have also attempted to do this with regular HTTP requests using Postman, but with the exact same result. I can authenticate and load applications, users, groups etc. But it doesn't return any of my custom attributes, of which I have 2.
The endpoint I am using is:
https://graph.windows.net/[tenant]/applications/[application object ID]/extensionProperties?api-version=1.6
Does anyone have any idea what I am doing wrong?
I just noticed a disclaimer at the bottom of this page https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-reference-custom-attr/. Looks like this might be our problem.
There is a known limitation of custom attributes. It is only created
the first time it is used in any policy, and not when you add it to
the list of User attributes.
There is a bug in the accompanying GitHub repo for the tutorial at:
https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/#use-custom-attributes
Un-bust your balls by changing Program.GetB2CExtensionApplication(...) to:
private static void GetB2CExtensionApplication(string[] args)
{
object formatted = JsonConvert.DeserializeObject(client.
GetApplications("$filter=startswith(displayName, 'b2c-extensions-app')").Result);
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(JsonConvert.SerializeObject(formatted, Formatting.Indented));
}
Instead of checking if the displayName equals 'b2c-extensions-app' it checks if it starts with 'b2c-extensions-app'. They have changed the name of the application in later versions of Azure AD B2C.
When you use the returned ID to get your extensions you will see that the Custom Attribute Name is prefixed with a Guid, and that's why we're been having trouble accessing it:
Eg. extension_10ecdccd92c446829a399e68ed758978_MyCustomAttribute
The correct GET URL for the Get-B2C-Application should be:
GET https://graph.windows.net/{Tenant}/applications?api-version=1.6&$filter=startswith(displayName,'b2c-extensions-app')
And the GET URL for the Extensions Properties (Custom Atttributes) should be:
GET https://graph.windows.net/{Tenant}/applications/{ObjectID}/extensionProperties?api-version=1.6
It's possible to get the attributes via LINQ:
string selectClause = "GivenName,Surname,Id,Mail"
+ ",extension_{ExtensionPropertyPrefixGUID}_myAttribute1"
+ ",extension_{ExtensionPropertyPrefixGUID}_myAttribute2";
var result = await _graphClient.Users
.Request()
.Select(selectClause)
.GetAsync();
The extension attributes will then be accessible via the AdditionalData
foreach (User user in result.CurrentPage)
{
string attribute1Value = (string)user.AdditionalData["extension_{ExtensionPropertyPrefixGUID}_myAttribute1";
}

How can i access the current url in a sharepoint custom webpart?

I have created a custom webpart and deployed it in sharepoint. Now i want to modify the webpart and use the url of the site page where the web part is embedded. How can i access the url progmatically?
If you mean in the Webpart codebehind you can reference it like this:
string currentWebUrl = SPContext.Current.Web.Url;
NOTE: SPContext.Current.Site\Web (unlike new SPWeb\SPSite) does NOT need to be disposed.
Hope this helps.
Resource:
SPContext MSDN (http://msdn.microsoft.com/en-us/library/ms475883.aspx)
Something like this will give you access to the url and then you can do whatever your trying to do:
using (var spSite = new SPSite(SPContext.Current.Web.Url))
using (var spWeb = spSite.OpenWeb())
{
// code here
}

How to get sharepoint site collection url using javascript?

I need to get the the site colllection url using the javascript.
I have written one simple function as below
function getSiteCollectionUrl()
{
var pageUrl= window.location.href;
var protocol = pageUrl.split(":")[0];
var addr=pageUrl.split("//")[1];
var webUrl = addr.split("/")[0];
var siteColleUrl = protocol + "://" + webUrl
}
let say the site address is "http://mysite/trialsite/default.aspx",
then it will return: "http://mysite"
But I think this isn't proper way to get the site collection url.
PLease suggest if you have any other idea.
Just by looking at SharePoint tag, right below this question, there is exactly the same question: How to get site collection url using javascript?
And the answers are there. And luckily you can get SharePoint site collection URL without invoking SharePoint API, because there is a L_Menu_BaseUrl variable available that contains it.
At http://server/documents it returns:
console.log(L_Menu_BaseUrl)
/documents
You cannot obtain the Site collection Url from just pure javascript without invoking SharePoint API.
If you need to do it in Javascript, you can invoke SharePoint API through web services and get the Site collection Url.
There is already Javascript API available called SPServices. You can use the following function:
SPGetCurrentSite

SPContext.Current.Web.CurrentUser returns misleading value

I'm trying to find out current user name for my sharepoint application. There are more that one way how to do this. However the sharepoint way returns misleading value.
System.Security.Principal.WindowsIdentity.GetCurrent().Name // returns MY_COMPUTER\\my_user
HttpContext.Current.User.Identity.Name // returns MY_COMPUTER\\my_user
HttpContext.Current.Request.ServerVariables["AUTH_USER"] // returns MY_COMPUTER\\my_user
Microsoft.SharePoint.SPContext.Current.Web.CurrentUser.LoginName // returns SHAREPOINT\\system
What is the cause of this behavior? Will I encounter problems if I'll use non-sharepoint way?
Are you browsing as the admin account that you used to install the system? SharePoint will "helpfully" rename that SHAREPOINT\System. Use a different account and all of the methods will return the same value.
This is expected if the user is the application pool account running the current web application.
BTW, it's supposed to be the same name as displayed in the welcome control (upper left control)
The problem is because you are probably getting the current user from an elevated SPWeb inside a RunWithElevatedPrivileges code. You can use the snippet below to get the real user
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))
{
using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID))
{
string currUser = site.CurrentUser; //not the ElevatedSite.CurrentUser
}
}
});
This will show the real user name instead of the SHAREPOINT\System user.
I think you might have include this code under SPSecurity.RunWithElevatedPriviliges. Check it out once. I am not sure though
The other way SPWeb.CurrentUser could return SHAREPOINT\system is if the web is elevated, though I'm not sure why SPContext.Current would be elevated. On what kind of page are you seeing this behavior?

Resources