ContentByQuery not working with OrderBy

I had some issues where I put a content by query web part in a page and when I added the OrderBy clause, it just stopped showing anything with no errors. I ended up putting the whole query on one line with no spaces and it started working. Not that it worked with spaces and line breaks as a normal where query, but only stopped working when I added the orderby. Also if your data isn't showing, check the data mapping view fields :).  

 

<Publishing:ContentByQueryWebPart runat="server" 
            	        ChromeType="TitleOnly" 
            	        Title="Executive Team Update"
				        ItemXslLink="{{SITE_COLLECTION_URL}}/Style Library/site/stylesheets/itemstyle.xsl"
				        ItemStyle="ExecutiveUpdate"
                        ItemLimit="1"
                        DataMappingViewFields="{94f89715-e097-4e8b-ba79-ea02aa8b7adb},Lookup;{108fed99-9aa6-4776-9065-23c19a63b787},Image;{fa564e0f-0c70-4ab9-b863-0177e6ddd247},Text;{f55c4d88-1f2e-4ad9-aaa8-819af4ee7ee8},HTML;{f55c4d88-1f2e-4ad9-aaa8-819af4ee7ee8},HTML;{8c06beca-0777-48f7-91c7-6da68bc07b69},DateTime;{446b839b-6220-4c3d-8444-9041faf31257},Choice;"
				        DataMappings="TeamMember:{446b839b-6220-4c3d-8444-9041faf31257},ExecutiveTeamMember,Choice;|PublishingPageContent:{f55c4d88-1f2e-4ad9-aaa8-819af4ee7ee8},PublishingPageContent,HTML;|Description:{f55c4d88-1f2e-4ad9-aaa8-819af4ee7ee8},PublishingPageContent,HTML;|Title:{fa564e0f-0c70-4ab9-b863-0177e6ddd247},Title,Text;|LinkUrl:{94f89715-e097-4e8b-ba79-ea02aa8b7adb},FileRef,Lookup;|Created:{8c06beca-0777-48f7-91c7-6da68bc07b69},Created,DateTime;|ImageUrl:{108fed99-9aa6-4776-9065-23c19a63b787},FeaturedImage,Image;|"
                        QueryOverride="<OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy><Where><Eq><FieldRef Name='ContentType' /><Value Type='Computed'>Executive Team Update Page</Value></Eq></Where>" />

 

Check if user is in a group in JavaScript

Useful if you want to show/hide buttons or html/controls on a page layout or in masterpage. Details from http://stackoverflow.com/questions/8841985/sharepoint-10-lists-want-to-limit-form-fields-per-user-groups/8847834#8847834

Link jquery 11 and spservices into your masterpage through script links or custom actions

function:

function IsGroupMember(GroupName)
{
    var isGroupMember = false;
    $().SPServices({
        operation: "GetGroupCollectionFromUser",
        userLoginName: $().SPServices.SPGetCurrentUser(),
        async: false,
        completefunc: function(xData, Status) {
            if($(xData.responseXML).find("Group[Name='" + GroupName + "']").length == 1)                
            {
                isGroupMember = true;
            }
        }
    });
    return isGroupMember;
}

Call function

Admin_Group = "Owners";
if (IsGroupMember(Admin_Group))
    $('.div').show;
else
    $('.div').hide();

 

Create a link in JavaScript to create a new page in pages library with custom content type

The following code should go in a page layout. This is useful for landing pages where users want to be able to quickly create pages.

Replace the content type id and url information. To find out the content type id you can navigate to the create page for your content page and look at the url. Note that this only works if you are deploying your content types with the same id every time. 

var siteCollectionUrl = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
                var returnURL = siteCollectionUrl + "/newsandevents/Pages";
                var url = '/newsandevents/_layouts/15/CreatePage.aspx?List=Pages&ContentTypeId=0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900DBB9F5D2AD4B436592E51AF81B2B2560007821B1F1235E524B982C1512AFCF515C' + returnURL;
                $('.jsCreateUpdate').html('<a href="' + siteCollectionUrl + url + '">+ Create Update</a>');

 

html:

<div class="create-update jsCreateUpdate">

</div>

 

Get radio button selected text from SharePoint choice field on page layout – JQuery, bind to change event

So I couldn't find anything obvious for this so chucked this together, hopefully useful for someone else 🙂

Page layout:

<div class="featured-breaking">
        <SharePoint:RadioButtonChoiceField FieldName="FeaturedBreaking" runat="server"></SharePoint:RadioButtonChoiceField>
</div>

JavaScript:

var selectedVal = "";
var selected = $(".featured-breaking input[type='radio']:checked");
if (selected.length > 0) {
    selectedVal = selected.parent().attr('title');
}
console.log(selectedVal);

On load, bind to change event:

<script type="text/javascript">
	_spBodyOnLoadFunctionNames.push("LoadNewsEntryPage");
	function LoadNewsEntryPage() {
		$(".jsFeaturedBreaking input[type='radio']").bind("change", FeaturedBreakingChanged);
		FeaturedBreakingChanged();
	}

	function FeaturedBreakingChanged() {
		var selectedVal = "";
		var selected = $(".jsFeaturedBreaking input[type='radio']:checked");
		if (selected.length > 0) {
			selectedVal = selected.parent().attr('title');
		}
		if (selectedVal == "N/A") {
			$('.jsExpiresOn').hide();
		}
		else {
			$('.jsExpiresOn').show();
		}
	}
</script>

 

Creating an administrator token in Yammer

Update: October 2017, this is all still relevant! Tested myself this month on a project.

Create an Admin access token

  1. Sign into Yammer as Yammer Admin via https://www.yammer.com
  2. Go to https://www.yammer.com/client_applications and register a new app.

Register a New App – Required Fields:

Description

Application Name:

Token Requestor App

Organization:

Organization name

Support e-mail:

An email address, which users of your app can contact for support.

Website:

Your organization’s website.

Redirect URL:

https://www.yammer.com

 

  1. Copy your Client ID, Redirect URI from the Application Information page.

  1. Paste this url into your browser, where client_id, redirect uri are the values obtained from step 4 above (replace including the brackets):

https://www.yammer.com/oauth2/authorize?client_id=[:client_id]&redirect_uri=[:redirect_uri]

  1. Copy the “code=” value from the URL created.
  2. Paste this url into your browser, where client_id, client secret are obtained in step 4 above. Code is the code from step 6 (replace including the brackets).

https://www.yammer.com/oauth2/access_token.json?client_id=[:client_id]&client_secret=[:client_secret]&code=[:code]

  1. Copy the “token:” value from the resulting JSON. Store it e.g. in Notepad.

You have your admin token! 

Thanks to Roland Oldengarm for putting together these instructions: https://rolandoldengarm.wordpress.com/

 

PowerShell to add and sort Managed Metadata navigation – on premises

Here's a useful snippet of PowerShell code for creating Managed Metadata navigation and sorting it – on premises

Add-PSSnapin Microsoft.SharePoint.Powershell

# Change these variables based on environment ****
$centralAdminURL = "http://centraladmin"
$siteCollectionURL = "http://sitecollection"

$termStoreName = “Managed Metadata Service”
$termGroupName = “Navigation Group”
$termGroupDescription = "Group Description"
$termsetName = "Navigation Termset"
$termSetDescription = "Termset Description"
# *************************************************


function CreateTerm($parent, $name, $url)  
 {  
    Write-Host "Adding term $name to parent $parent.Name"  
    $term = $parent.CreateTerm("$name", 1033)  
    $term.IsAvailableForTagging = $false    
    $newUrl = $url
    if(!$url.ToLower().Contains("http"))
    {  
        # Logic to append site url to relative path to create complete url which is needed for Simple Link Navigation
        $newUrl = $url
    }

    $term.SetLocalCustomProperty("_Sys_Nav_SimpleLinkUrl", $newUrl)   
    return $term  
 } 

$site = Get-SPSite -Identity $centralAdminURL
$session = Get-SPTaxonomySession -Site $centralAdminURL
$termStore = $session.TermStores[$termStoreName]

# Remove if exists already
$group = $termStore.Groups[$termGroupName]
if ($group -ne $null)
{
    Write-Host "Removing terms"
    $group.TermSets|foreach{
        $_.Delete()
    }
    $group.Delete()
    $termstore.CommitAll()
}

# Create term group and term set
$group = $termstore.CreateGroup($termGroupName)
$group.Description = $termGroupDescription
$termStore.CommitAll()

Write-Host "TermGroup - $termGroupName created successfully"  

$termSet = $group.CreateTermSet($termsetName,1033)
$termSet.Description = $termSetDescription
$termSet.IsAvailableForTagging = $false
$termSet.IsOpenForTermCreation = $false
$navigationSet = $group.TermSets[$termsetName]
$navigationSet.SetCustomProperty("_Sys_Nav_IsNavigationTermSet", "True")
$termStore.CommitAll()

Write-Host "TermSet - $termsetName created successfully"  

# Create terms

# Home
$homeTerm = CreateTerm $termSet "Home" $($siteCollection + "/")

# Other term set

$otherTerm = CreateTerm $termSet "Other Term" $($siteCollection + "/subsite/Pages/home.aspx")

$termStore.CommitAll()

# Create sub terms
$otherTermSub1 = CreateTerm $otherTerm "Other Term Sub 1" $($siteCollection + "/subsite/Pages/othertermsub1.aspx")
$otherTermSub2 = CreateTerm $otherTerm "Other Term Sub 2" $($siteCollection + "/subsite/Pages/othertermsub2.aspx")
$otherTermSub3 = CreateTerm $otherTerm "Other Term Sub 3" $($siteCollection + "/subsite/Pages/othertermsub3.aspx")
$otherTermSub4 = CreateTerm $otherTerm "Other Term Sub 4" $($siteCollection + "/subsite/Pages/othertermsub4.aspx")

# Set sort order
$customSortOrder = $otherTermSub1.id.ToString() + ":" + $otherTermSub2.id.ToString() + ":" + $otherTermSub3.id.ToString() + ":" + $otherTermSub4.id.ToString()
$otherTerm.CustomSortOrder = $customSortOrder

$termStore.CommitAll()

Write-Host "Terms for Term Set - $termsetName created successfully"   

 

How to connect to SharePoint Online

Running PowerShell with SharePoint on premises is pretty easy, you jump on the server and run up PowerShell or PowerShell ISE and start connecting and commanding. So how do you connect to SharePoint online from either a server or your local machine?

You need to install Windows Management Framework 3.0 and SharePoint Online Management Shell. The cool thing about SharePoint online and cmdlets is that you can run them from any machine with the tools installed.

Create a new PowerShell script by either opening a new notepad document and saving it as a '.ps1' file, or by opening PowerShell ISE. Paste in the following code and change the user, password and URLs.

Clear-Host
$spOnlineUser = ''
$spOnlinePassword = ''
$spOnlineSiteAdminUrl = 'https://pkswlgsandbox-admin.sharepoint.com'
$spOnlineSiteUrl = 'https://pkswlgsandbox.sharepoint.com/sites/devicechannels'

$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $spOnlineUser, $(convertto-securestring $spOnlinePassword -asplaintext -force)
Connect-SPOService -Url $spOnlineSiteAdminUrl -Credential $cred
Write-Host "Connecting to " $spOnlineSiteUrl

$site = Get-SPOSite -Identity $spOnlineSiteUrl
Write-Host "Success!!" -ForegroundColor "Green"
$site

Now that you have a .ps1 file ready, run SharePoint Online Management Shell as Administrator and run your script.

Quick side note, if you get the following error "….ps1 cannot be loaded because running scripts is disabled on this system….", you need to run the following command "Set-ExecutionPolicy RemoteSigned" and click "Yes".

In SharePoint Online Management Shell:

In PowerShell ISE:

Once you have scripts running, and if you have set your credentials and URL's correctly, you should see the following:

I love PowerShell ISE, so if your planning on writing many scripts you should use it. It allows editing and running of scripts on one screen as well as intellisense and debugging.


So, what can you actually do against SharePoint online?? The cmdlets available out of the box are very limited, which means you need to write CSOM in your PowerShell. Here is a post by Chris O'Brien with more information on CSOM in PowerShell. You can also start to use custom CMDlets:

Māori spell checking in SharePoint 2013 and SharePoint Online

There isn't (as far as I can tell from anywhere) a Māori dictionary in SharePoint, even though you can set it as a prefered language in your profile. I found a post from SharePoint 2010 which specifies a work around for setting another language as the spell check language by adding some JavaScript into your master page, you can also add the code into a page layout. This worked fine for French when I tried it, but didn't work for Māori which uses the local ID 1153. Instead I got the following message "The spelling check cannot be completed because there is no dictionary installed for the current language". Dictionaries must only be installed when a language pack is installed, of which there isn't a huge variety.

It's not ideal, but you can still include Māori words in the dictionary. Keep reading!

In SharePoint 2010, you could add a custom dictionary which would be used by spell check throughout the site. This hasn't changed in SharePoint 2013 and SharePoint Online.

This works per site collection:

  • Create a new word document (if you don't require macrons then you can just use notepad to create the .txt file and follow the same steps)
  • Add a word to each line, as in the screen shot below

    Adding words to custom dictionary

  • Save the file as a .txt file named "Custom Dictionary.txt" – this has to be the exact name of the file, select "Other encoding" and set Inicode (UTF-8)

    saving the custom dictionary

  • In the root of your site collection, create a document library named exactly "Spelling"
  • Upload your Custom Dictionary.txt file into the document library

The words you added to the dictionary will now be correct spelling.

example editing html field with new dictionary

 

 

 

Requesting images with specified width/height in SharePoint 2013 with the query string (image renditions)

Image renditions are a powerful new SharePoint 2013 feature which allow not only users to specify the size of an image when adding one to a page, but also for developers to request a specified size in code.

I'm not going to go over image renditions in too much detail as it's covered pretty well on other blogs, such as this one by Waldek Mastykarz. Bascically you set up an image size (e.g. Banner Image – Width: 750px, Height: 120px) in the image renditions list, this is displayed as an option to the user when adding an image to a page. The user can drag the rendition size around the image (like when cropping a profile image in FaceBook).

For developers this gives us a few new tools to work with to help with performance and usability/governance

Setting Renditions

When adding an RichImageField to a page layout, you can specify the default rendition ID, this means the user can't change the rendition. This would be useful for pages where an image always needs to be a certain size (such as a news banner).

You can do this through SharePoint Design Manager in the snippets screen by entering either some dimensions or the rendition ID into the "Rendition Properties". This will generate the snippet to put in your .html page layout file.

image rendition properties example in snippets

If you are using .aspx files instead of Design Manager files, simply add the following properties to your image fields markup:
<%@Register Tagprefix="PageFieldRichImageField" Namespace="Microsoft.SharePoint.Publishing.WebControls" Assembly="Microsoft.SharePoint.Publishing, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<PageFieldRichImageField:RichImageField runat="server" FieldName="942cf913-d3ad-4493-9754-e91cf53e3cd9" RenditionId="1">

edit image rendition not avilable as set by control
As you can see, the Image Rendition is set to rendition ID 1 and the user can't change this. The one issue with this, is that the user can't crop the image.

OR

<PageFieldRichImageField:RichImageField runat="server" FieldName="942cf913-d3ad-4493-9754-e91cf53e3cd9" DisplayHeight="100" DisplayWidth="100" RenditionId="-1">

Setting the display width and height on the field sets the size settings to disabled on the image screen for the user. It also leaves the rendition options open for the user to select. Regardless of the image rendition the user chooses, it will be added to the page as the specified width and height, in this case 200 x 200. The user can then change the rendition post adding to the page. This could be a good option if you want to force the image to a certain size, but still give the user the option to change it later. It seems a little confusing though, the user would wonder why the rendition field is still enabled initially when it isn't used.

specify height on rendition image field
 

Query String

Performance wise, this gives us the ability to request images by specific rendition ID OR by width/height. This is awesome!! Images will now be generated at the specified size server side, meaning users aren't downloading large images unnecessarily. Great for mobile sites.

Recently I was coding a news widget for a client using REST calls to the search service. I had to display the first image in all announcements posts. The problem I encountered was some images being returned were pretty massive and caused the widget to load slowly. Lukily, using renditions I was able to overcome the issue by appending the size I required to the query string. Here's an example of an image's src:

https://site.sharepoint.com/sites/devicechannels/PublishingImages/bg_body_5.jpg?Width=100
OR
https://site.sharepoint.com/sites/devicechannels/PublishingImages/bg_body_5.jpg?RenditionId=2

 

For SharePoint online, this all just works. For on premises, you will need to enable the blog cache.