Wednesday, March 24, 2021

Making the workbench full width

I often am frustrated by the forced max width of the workbench - which inhibits my web part testing. To overcome this, I add the following in the componentDidMount of my web part during development phase:


$("#workbenchPageContent").attr("style","max-width:inherit");

Wednesday, March 17, 2021

Getting user ID by email in REACT SPFX web part

Missed me? I'm back!


Here is a small function I whipped up for React web parts that need the user id.
 /**
     * Fetches the user ID for the specified user
     * @param email the email for the user
     * @returns a promise containing the user ID in the site collection
     * example:
     * var userID = await this.getUserIDByEmail(this.props.wpContext.pageContext.user.email);
     */
    private async getUserIDByEmail(email:string):Promise<number>
    {
        var url = `${this.props.wpContext.pageContext.site.absoluteUrl}/_api/web/siteusers?$filter=Email eq '${email}'`;
        var userData:any = await  Query.GetQueryData(this.props.wpContext,url);
        return userData.value[0].Id;
    }

this refers to a class I created called Query where I put some code to help me do queries:


export default class Query {
  public static async GetQueryData(contextWebPartContexturlstring) {
    var deferred = $.Deferred();
    console.log(`running query '${url}'`);
    let _nometaOptISPHttpClientOptions = {
      headers: { 'Accept': 'application/json;odata=nometadata''odata-version': '''Content-type': 'application/json;odata=verbose' }
    };
    context.spHttpClient.get(urlSPHttpClient.configurations.v1_nometaOpt).then(
      (responseSPHttpClientResponse=> {

        if (response.status == 200) {
          console.log("got query results");
          if (response.headers.get("content-type").indexOf("atom") > -1) {
            console.log("Got xml instead of json on " + url);
            response.text().then((text:string=> {
              deferred.resolve(text);
            });
          }
          else {
            response.json().then((jsondataJSON=> {
              deferred.resolve(jsondata);
            });
          }
        }
        else {
          console.log("error getting query results!");
          console.log(response.status);
        }
      }, (errany=> {
        debugger;
        console.log("error getting query results!");
        console.log(err);
      });
    return deferred;
  }
}

Wednesday, June 12, 2019

Restricting a User Picker field to only selecting SharePoint groups

 After a lot of research, I couldn't find the answer, so I wrote one myself.
To change a person field in sharepoint that is configured to allow "users and groups" to only allow groups, you need to inject code that changes the picker settings after the page is loaded.

Code below:



$(document).ready(function(){
//wait for the initialisation of the sharepoint script 

  SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
//call our special function with the field's internal name
    SetGroupOnly("myfieldinternalname");
  });
});

function SetGroupOnly(fieldName)
{
//make sure there is a control for that field on the page
  if($("div[id^='"+fieldName+"_']").length>0)
  {
    //wait for the initialisation of the control to finish
    WaitForControl("div[id^='"+fieldName+"_'][id$='$ClientPeoplePicker']", function(){
//get the people picker control object
      var peoplepicker = SPClientPeoplePicker.SPClientPeoplePickerDict[$("div[id^='"+fieldName+"_'][id$='$ClientPeoplePicker']").attr("id")];
//set the type to SPGroup
      peoplepicker.PrincipalAccountType = "SPGroup";
      peoplepicker.PrincipalAccountTypeEnum = 8;
      peoplepicker.ResolvePrincipalSource = 15;
      peoplepicker.SearchPrincipalSource = 15;
    });
  }
}



function WaitForControl(controlSelector, returnFunction)
{
  if($(controlSelector).length>0)
    returnFunction();
  else
    setTimeout(function(){
      WaitForControl(controlSelector,returnFunction)},50);    
}

Sunday, November 18, 2018

User is in SharePoint Group but doesn't get permissions

Found this today - a user shows up in a SharePoint group, but when you do a permission check the user doesnt have permissions to resources in sharepoint that the group has permissions to.
One explanation to this that I found is when the user was added to the group using the API (REST, JSOM, CSOM) by specifying the user's login name (domain\username). Turns out that adds the user to the group, but not the correct user....so it looks right, but it isn't. what is the correct user? you have to add the claims token "i:0#.w|" before the domain\username to properly add the user.
This off course applies to the code that adds the users. As far as I can tell you will have to remove the incorrect users, and then add them again either manually or using code.


Tuesday, July 25, 2017

When Cumulative doesn't mean Cumulative

 So, I just tried adding a new server to a farm, after patching it to the same level as all other servers in the farm (April 2017 CU).
Surprisingly, the SharePoint configuration wizard told me off, saying the server is missing the December 2016 CU.

Yes, that is right - the April 2017 CU does not include the CU that was released 5 months before it...Cumulative? nope!

Monday, June 01, 2015

Taxonomy field value doesnt set

We had a puzzle today, which we were sure was an issue with the document property parser in SharePoint. Every time we tried to set the value of a specific column using either our existing powershell script or an event handler that works on every other library in the system, the document would be updated with the property value, but after a second we'd refresh the page and see the value went back to null.


It was frustrating! I was sure it was because the document had an empty value in the document properties that was overriding the value from my code - despite the fact that my code is implemented with a delay to ensure it runs after the parser.


We troubleshooted several ways and couldn't find the solution...until we noticed something weird when we were looking at the content type schema - the taxonomy field was set to support multiple values! our code was specifically written for that field, which is not supposed to support multiple values. Some nasty little elf went into the column setting in the library and changed my precious from its normal settings. Setting it back and everything went to normal.

Moral of the story - since setting a taxonomy field's value in code is different if the field supports multivalue or not, make sure either your code is robust enough to handle a nasty user making a change, or tell your users to keep their hands to themselves!

Thursday, June 12, 2014

Creating links to documents inside document sets - BUG

This is a bug a client of mine found in SharePoint 2010, and I verified on 2013 and Office 365 (as of today - not yet fixed).

The issue is when you create a link to a document inside a document set. If you are not familiar with this - users can create links inside document libraries, using a content type called "Link To Document". You can also create document sets - which is a special type of folder. To do so, add the two content types to a document library:




You then also have to configure the document set content type to accept links to documents in the document set settings under the content type settings:



The problem is when you create a document set, and in it you then create a link to document:


The result is that the users get redirected to the wrong URL, and instead of seeing the actual document set they started from, with the new link (or any document that is already in the document set) the users see a default view of a generic document set - not the one they started from:

The reason for this is different in 2010 and 2013. I have yet to pinpoint the reason for the issue in 2013, but in 2010 the issue is that the URL when creating a new link to document has two "RootFolder" parameters, and that confuses the server when the users click "OK" to save the link and to get redirected back. Instead of seeing the document set, they see the default document set home page - with no parameter to tell the server which document set to actually display the contents of.


I have created a workaround for 2010, and am yet to modify it for 2013 (since the behaviour in 2013 is slightly different, though the results are the same). The workaround is to use javascript to detect if we got to the current page from the edit form, and if the current page is a document set home page and if the current page parameters have two question marks in them. If so, redirect the user, removing the second "&RootFolder=" parameter. This will not work in 2013 since the url there doesnt have parameters after creating the link to document.

Here is an example of the code. To inject it I used a farm level feature that added a ScriptLink to all pages in the farm. The script link was to a .js file that contained the following code:

function FixDocumentSetRedirect() {
    if (document.referrer.indexOf("EditForm.aspx") > 0 && document.location.href.toLowerCase().indexOf("docsethomepage.aspx?id=") > 0 && document.location.href.toLowerCase().indexOf("docsethomepage.aspx?id=") < document.location.href.indexOf("?")) {
        var source = document.referrer;
        source = source.substring(source.indexOf("Source=") + "Source=".length);
        var firstRootFolder = source.indexOf("&RootFolder=");
        var secondRootFolder = source.indexOf("&RootFolder=", firstRootFolder + 1);
        if (secondRootFolder > firstRootFolder) {
            source = source.substring(0, secondRootFolder);
        }
        alert(source);
        
        document.location.href = source;
    }
}

_spBodyOnLoadFunctionNames.push("FixDocumentSetRedirect"); 



Wednesday, April 09, 2014

Users able to open documents using links, even without permissions

Recently I had to troubleshoot an issue where end-users were able to open links to documents they had no permissions to open. If they tried opening the library they got the "access denied" message that is expected, but clicking a link directly to a document in the library resulted in the document either opening up in the browser, or downloaded. We double checked the documents did not have item level security, and they didn't.

What a puzzle!

Turns out that those libraries were provisioned by code, and the code set a property on the library called "AllowEveryoneViewItems" (msdn documentation). This property, when set to true, means that anyone- even unauthenticated users, will be able to download and view items in the list or library - even without permissions.

The reason to turn it to true is when dealing with anonymous sites - for example, if you have an internet site and you want to put links to documents from pages, but you don't want users to be able to browse the library itself.

Wednesday, June 19, 2013

SharePoint 2013 Book is ready to purchase

If you are looking for a sharepoint 2013 end-user specific book, look no further

Monday, May 20, 2013

Activating the Document ID feature by code causes document sets welcome pages to show each web part twice

This is a weird one - I have a feature, that when activated loops over a list of other features and activates them - using "Force" :

site.Features.Add(currentFeatureID, true);


This works fine on most sites, but in Document Center sites, where the document ID feature is already activated document sets in the site suddenly show the web parts on the welcome page twice. I debugged it, and it turns out that this happens when the document ID feature is the culprit. However, this doesn't happen if I activate the ID feature using powershell.


My only solution at the moment is to check if the feature is already activated before activating it. This stopped the problem, but doesn't explain it.