Use Microsoft Flow to grab image of the day for SharePoint

The default Search Center in SharePoint is quite minimalist- just an empty page layout with a search box. This post will show you how to use the workflow logic of Microsoft Flow to grab a reference to the Bing image of the day, copy it’s URL to a SharePoint list, and then use clientside scripting to set the image as a background to your search center or use elsewhere in your portal.

There’s been plenty of tutorials posted over the years in terms of SP image rotaters, jazzing up search centers, etc. – the focus of this post is really more about using Flow to parse external RSS data into a SharePoint list on an ongoing basis, and then do something with that data.

1. Create the SharePoint List

In order to not have to query an external RSS feed every time a user hits a page where we want to display referenced images, we’re going to use a SharePoint list as a repository for the image links as they come in each day.

  • In your SharePoint site collection of choice (in this case, i’m using the root site collection), create a new Custom List with the name “Daily Images”. There’s no extra columns or tweaks needed for this List, we’re just going to be using the OOTB Title field to store our daily image URL and that’s it.
    Need help creating a List?:
    -If you’re using the new SharePoint UI style (Lists, Libraries & Subsites listed on “Site Contents” page are text links), these are the instructions.
    -If you’re using the legacy SharePoint UI style (Lists, Libraries & Subsites listed on “Site Contents” page are square, “metro”-style icons), follow these steps.

2. Create the Flow

  • You haven’t checked out Microsoft Flow yet? Come on, get on it – it’s the future of workflow! Head on over and sign up with your Microsoft or organizational Office 365 account.
  • Browse the Templates and locate the “RSS to SharePoint” template by Craig Stanley (thanks Craig!). Click “Use this template”.
  • For the “When a feed item is published” URL, input your image RSS feed URL, e.g. http://feeds.feedburner.com/bingimageswhen-a-feed-item-is-published-microsoft-flow
  • A particularity of this specific RSS feed, is that some image URL’s it was outputting (with “feedproxy” in the URL) we’re not rendering when linked to, so I used the “Add a Condition” link to create a Flow Condition that only registered image links in the RSS feed, that do not contain the string “feedproxy”. For the true part of the Condition, you’re going to have it run the Create SharePoint List Item action, using the URL of the image from the RSS feed for the Title field:
    add-a-condition-create-list-item-microsoft-flow
  • It’ll take the flow a bit to pick up some data, so if it’s a daily RSS feed check back the next day. When it’s working and there’s no problems reported in the log, you should see some RSS image URL links showing up like so:
    daily-images-list-items

3. Add some script to render the images

We’re going to use Jquery and some of the SharePoint REST API to query our Daily Images list, and grab the latest image. We’re going to run with the assumption you already have your Jquery reference set up. If you don’t have Jquery in there already, you can either bake it into your page layouts (if you’re using custom branding) like this, or add a one-off reference on the page where you’re embedding this Daily Image code, like in this example.

Go to your Search Center homepage (https://yourTenant.SharePoint.com/Search by default), Edit the page, and add a Script Editor web part with the following code. It renders the latest image of the day as the CSS background image of the #DeltaPlaceHolderMain div. Note that we are doing a string replace to change the original image URL’s provided via the RSS feed, which just happened to be non-SSL http://. Since we’re displaying this image on a secure SharePoint Online page, we’re changing the http:// to https://. Bing, in this case, serves both versions happily- not all image sources may play along like this so double-check they can render https:// before committing.

<script type="text/javascript">
var Module = {} || Module;

Module.GetImages = (function () {
    var pub = {},
        _images = [],      
        _options = {
            listName: "Daily Images"
        };

    pub.init = function () {
        var url = "https://yourTenant.sharepoint.com/_api/lists/getbytitle('" + listName + "')/items?$top=1&$orderby=Created desc"
        $.ajax({
            url: url,
            type: "GET",
            headers: {
                "accept": "application/json;odata=verbose",
            },
            success: function (results) { createImageView(results, listName); },
            error: function (error) { 
                console.log("Error in getting List: " + listName); 
                $(_options.container).html("Error retrieving your " + listName + ".");
            }
        });   
    };

    function createImageView(results, listName) {
        _images = results.d.results;

        $.each(_images, function (index, task) {
			var imageURL = task.Title;
			imageURL = imageURL.replace("http:","https:");
			$('#DeltaPlaceHolderMain').css('background-image', 'url(' + imageURL + ')');
			$('#DeltaPlaceHolderMain').css('background-repeat', 'no-repeat');
			$('#DeltaPlaceHolderMain').css('background-position', 'center');	
        });
    }

    function _onQueryFailed(sender, args) {
        alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
    }

    return pub;
}());

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
        Module.GetImages.init();
    });
});
</script>

When all is working, you’re going to get a new Bing image of the day each day, as the background to your search center page:
search-center

This technique could be applied to any instance where there’s a list of images delivered by an RSS feed, for example:
NASA Image of the Day
Flickr daily interesting image
Wikimedia Image of the Day
..etc.

For the Bing Image and any other source, make sure to check that you’re obeying the copyright & author attribution & usage requirements of the image provider – the above technique implies nothing about such nuances, it’s only intended as a technical proof of concept/demo.

SharePoint Code Analysis Framework 5 released

chartsAndReports_
I’m not one to make a blatant product plug but I really like the SharePoint Code Analysis Framework tool and they’ve upped the ante on how effective it is for running QA on SharePoint code, including tests for SharePoint Apps.

What is the SPCAF tool?
A desktop program that evaluates SharePoint code, solutions, features, Apps etc. and  checks all XML, HTML, ASPX, CSS, JavaScript and also assembly code against the quality policies, calculates metrics, generates dependency graphs and builds an inventory report.

Features list here: http://www.spcaf.com/features/

Grab it from: http://visualstudiogallery.msdn.microsoft.com/d3b2aaf7-0d6a-4995-a4e5-4153c57e3889

WARNING: This tool can reveal flaws big and small in your SharePoint Solutions. Prepare for some soul-crushing issues to be discovered in your code that your previously considered beautiful.  Hearts may be broken but remember the phoenix always rises out of the ashes. SharePoint is hard, Dev is hard, SharePoint + Dev = well.. a grey hair or two should be expected. Tools like SPCAF help keep us in line with best practices.

You may find that some of the problems reported by SPCAF do not meet your operational engineering minimum standards for rectifying – in particular HTML, CSS, & JS validation is such a patchwork of standards & recommendations, automated validation reports need to be taken with a grain of salt.

Overall, I’ve found SPCAF to be a worthwhile exercise to run on any major chunk of new or updated SharePoint code.

New Features in v5

  • Analyzers
    • New analyzer for JavaScript code applies ca. 150 rules to .JS files in WSPs and Apps
    • New analyzer for SharePoint Apps with lots of rules, metrics, dependencies and inventory checks
  • Client application
    • Completely new client application to improve usability and functionality
    • New client application “Result Viewer” (separate download) to view analysis results without license
    • New settings editor application
  • Migration Assessment
    • New analyzers and reports to analyze WSPs and give recommendations for a transition to the App model
    • Free limited version available
  • Reporting
    • New format of HTML reports with filters, charts, sorting, grouping and many more
    • Extensibility with custom reports and report section
    • New reporting engine based on Razor to ease the creation of custom reports
    • New report type PDF

Can’t wait to try SPCAF? Get your trial now or update the SharePoint Code Analysis Framework already installed on your machine.

New Client Application

The new SPCAF client makes your code analysis even easier.

Just drop your WSP or App Packages in the center of the application and start the analysis or access your recent analysis results directly from the start screen.

Learn more

Client_StartSeite
SPCAF Client

Better Analysis Dashboard

The new analysis dashboard shows you a 360° degree overview of Code Quality, Metrics, Dependencies and Inventory.

From there you can access the individual reports and download Word, PDF, XML or CSV reports to share them with team members.

Learn more

SPCAF Analysis Dashboard
SPCAF Analysis Dashboard

New dynamic reports

The new reports have a simple overview dashboard showing the key findings in a graphical presentation.

You can filter, sort and re-arrange the results and dig down deep into source code to find out what is inside your solution or app.

Learn more

Client_Report
SharePoint Code Quality Report

 

Code Quality Analysis HTML DOCX PDF XML CSV
Code Metrics HTML DOCX PDF XML CSV
Code Dependency Analysis HTML DOCX PDF XML CSV DGML
Code Inventory HTML DOCX PDF XML CSV
Code Migration Assessment HTML DOCX PDF XML

New SharePoint Code Migration Assessment Report

Full trust customizations are the main risk and cost driver for migrations to a newer SharePoint version or to Office 365. Without knowing what has been customized you cannot manage the transformation or elimination of custom code.

The new SharePoint Code Migration Assessment provides deep insight into your customizations and allows better effort estimations and risk mitigation.

Learn more

Client_Report
SharePoint Migration Assessment Report

New Analyzers for Apps and JavaScript

With the JavaScript and Apps becoming the only future-proof way of customizing SharePoint both on-premises and in the cloud many seasoned SharePoint developers are now facing a paradigm shift which requires them to adjust their skills.

With the new App and JavaScript analyzers, which contain already in this first release over 170 rules, developers can assure their code quality with SPCAF like they are used to for full-trust code.

Learn more

Client_Report
Documentation of JavaScript Rules

Try it!

Would you like to see these new features in action?

Get a trial and start getting your SharePoint Code under control!

Introducing TypeScript – Microsoft’s new open source JS language

TypeScript is a language for application-scale JavaScript development.TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open Source.

http://www.typescriptlang.org/#Download

Starts from JavaScript, Ends with JavaScript

TypeScript starts from the syntax and semantics that millions of JavaScript developers know today. With TypeScript, you can use existing JavaScript code, incorporate popular JavaScript libraries, and be called from other JavaScript code. TypeScript compiles to clean, simple JavaScript code which runs on any browser, in Node.js, or in any other ES3-compatible environment.

Contribute

Read the specification in doc or pdf

Discuss and provide feedback on the language.

Play with the bits and file bugs.

Join the #typescript Twitter discussion and follow the CodePlex project.

Learn

Tutorial – Best way to get up to speed on TypeScript.

Forums – Great place to get help with using TypeScript.

Firefox Friday #1 – Useful Plugins for SharePoint Development

As SharePoint developers we are bound to IE but often fallback to other browsers for various reasons such as performance, HTML standards compliance, or in my case with Firefox – the plugins available.   The official Technet on what is and is not supported on various browsers (Chrome is notably not even in there): http://technet.microsoft.com/en-us/library/cc263526.aspx. I will follow up this post with a list of what specifically will not work with SharePoint when using Firefox (so you can’t say I didn’t warn you!)

While Google Chrome is definitely a solid choice, if you are using Firefox the following plugins will help you out:

FasterFox Plugin

Download: http://fasterfox.mozdev.org/
Description:
Various network tweaks that deliver a zippy experience. This will also speed up your SharePoint user experience greatly too.

  • Prefetch Links
    Dynamic speed increases can be obtained with Fasterfox’s unique
    prefetching mechanism, which recycles idle bandwidth by silently
    loading and caching all of the links on the page you are browsing.
  • Tweak Network
    Fasterfox allows you to tweak many network and rendering
    settings such as simultaneous connections, pipelining, cache,
    DNS cache, and initial paint delay.
  • Page Load Timer
    A millisecond accurate page load timer tests the effectiveness
    of your settings.
  • Block Popups
    A popup blocker for popups initiated by Flash plug-ins is also
    included.

Notes:
1. Remember, just because you’ve got a turbocharged browser doesn’t mean your colleagues or clients do.  This plugin is a double-edged sword because you can get lazy or indifferent about performance problems on web applications. If you are developing, testing, or QA’ing systems you should either use a different browser (COUGH IETester COUGH) or temporarily disable Fasterfox.

2. The out of the box setting in the Firefox > Add-Ons > FasterFox > Options menu is “Optimized“. Set that bad boy to “Turbo Charged” and to hell with playing nice with server resources – our time is worth more!


Windows Media Player Plugin for Firefox

Download: http://www.interoperabilitybridges.com/windows-media-player-firefox-plugin-download
Description: Lets you run Windows Media content in Firefox. In particular you will be able to stream WMV videos such as the ones we have in the newly minted it groove SharePoint center directly in your browser window.

Web Developer Toolbar

Download: https://addons.mozilla.org/en-US/firefox/addon/web-developer/
Description: Adds a toolbar with a slew of options essential for anything webby. CSS, Forms, Images, Cookies, Viewing Source – instantly get Xray vision into any web page.

iMacros for Firefox

Download: https://addons.mozilla.org/en-US/firefox/addon/imacros-for-firefox/?src=collection&collection_id=da0ecd99-2289-7ab0-7d57-e7c489c845c3
Description: Automate Firefox. Record and replay repetitious work. If you love the
Firefox web browser, but are tired of repetitive tasks like visiting the
same sites every days, filling out forms, and remembering passwords,
then iMacros for Firefox is the solution you’ve been dreaming of!
***Whatever you do with Firefox, iMacros can automate it.***

Colorzilla

Download: https://addons.mozilla.org/en-US/firefox/addon/colorzilla/
Description: With ColorZilla you can get a color reading from any point in your
browser, quickly adjust this color and paste it into another program.
You can Zoom the page you are viewing and measure distances between any
two points on the page. The built-in palette browser allows choosing
colors from pre-defined color sets and saving the most used colors in
custom palettes.

Basic end-user usage could be grabbing the color code for the blue from a clients logo and matching it up to another design element.

Firebug

Download: http://getfirebug.com/
Description: Firebug integrates with Firefox to put a wealth of web development tools
at your fingertips while you browse. You can edit, debug, and monitor
CSS, HTML, and JavaScript live in any web page.

Learning to use Firebug is a whole different topic but it is possible for non-developers to get working with it to quickly id and delegate issues due to Javascript or CSS issues, broken images, etc.

Firebug also is required for Yahoo YSlow and the Google Pagespeed Firefox Plugins

SharePoint 2010 Get Current Username / Logged in User

Have been exploring the SharePoint Client Object Model and in particular the Javascript Object Model

While there are methods to get the current user info, you can also simply borrow the logged in username from the top right of the screen:


<script type="text/javascript">// <![CDATA[
 var Username = document.getElementById("zz16_Menu").innerHTML ;
 var end = Username.indexOf("<");
 var nameOnly = Username.substring(8, end);
 document.write(nameOnly);

// ]]></script>

This technique is a little complex for my liking however, so here’s a snappier way to grab the current login name (using Jquery):


var Username = $("#zz16_Menu").text();
document.write(Username);

Note that the #zz16 identifier will vary based on your Master page. Use the Firefox Web Developer tools or Internet Explorer F12 tools to find out what the ID should be on your SharePoint site.

Using this type of technique is definitely more brittle than actually using a CAML query however in my mind would be more performant than actually doing a lookup in the DB. Would love to know if someone knows the scoop on that..

Update 05/12/2011

As my colleague Colin pointed out – the name that appears on the top right can really be anything and can change – for example if a user gets married and their name changes. A better approach would be to retireve the value programmatically using SPServices ( http://spservices.codeplex.com/wikipage?title=$%28%29.SPServices.SPGetCurrentUser ). As of version v0.6.1, you can also request the ID of the user by specifying fieldName: “ID”.  Much more stable to use in most scenarios:

$().SPServices.SPGetCurrentUser({
	fieldName: "ID",
	debug: false
});