another technical blog...technically

Wednesday, July 29, 2015

Publishing by search: what about video in HTML field?

I think the title it's someway self-explaing: we know that when you add a video to a HTML field, SharePoint doesn't use HTML5 video tag, but it installs a web part which show the video itself using a player.
A video, in SharePoint, it's not simply a file, but a folder which contains that video file, maybe its renditions and other stuff i'm not interested in.
Video and assets generally are in a Asset Site which could be accessed from catalog, public site and many others.
If we want to simply use HTML5 video tag, we first need to find the correct video file, then we have to create a reusable content with these features:
  • User can select the video using the OOB AssetPicker
  • Reusable content automatically finds the video file
  • Reusable content automatically generates HTML5 video tag
So, let's first declare a reusable content for video with this HTML code


Why in the world i'm using an img tag?
Because i want the user to have a placeholder like this


Then include a JS (in master page or page layout: up to you) which:
  1. Binds a click event to every asset_video class object 
  2. On click opens OOB Asset Picker and let user choose an asset
  3. On Asset Picker close event, finds the video URL using REST
  4. Writes the HTML5 tag using the URL
 Below some code you can use
jQuery(document).ready(function () {
    initAddVideoTemplate();
    SP.SOD.executeOrDelayUntilScriptLoaded(function () {
        SP.SOD.executeOrDelayUntilScriptLoaded(function () {
            var ctx = SP.ClientContext.get_current();
            var site = ctx.get_site();
            ctx.load(site);
        }, "cui.js");
    }, "sp.js");
});

// Adds a listener on every HTML element with class "asset_video"
// You can add your own classes in this obj array, lister for all elements will be created
// The listener will make asset picker to be opened when you click on a asset_video
function initAddVideoTemplate() {
    var count = 0;
    var obj = { 'asset_video': '' }
    jQuery.each(obj, function (index, value) {
        jQuery('body').on('click', 'img[class="' + index + '"]', function () {
            var className = this.className;
            var idOldVideo = "reusableContentInsertVideo-" + rc_generateUUID();
            this.setAttribute('id', idOldVideo);
            if (!count) {
                jQuery.getScript('/_layouts/15/AssetPickers.js', function () { insertVideo(idOldVideo, className, value); });
                count += 1;
            } else insertVideo(idOldVideo, className, value);
        });
    });
};

// Asset picker configuration
function insertVideo(idOldVideo, className, value) {
    var assetPicker = new AssetPickerConfig("");
    assetPicker.ClientID = "";
    assetPicker.DefaultAssetLocation = "";
    assetPicker.DefaultAssetImageLocation = "";
    assetPicker.CurrentWebBaseUrl = "";
    assetPicker.AllowExternalUrls = "";
    assetPicker.ManageHyperlink = false;
    assetPicker.AssetUrlClientID = idOldVideo;
    assetPicker.AssetType = "Media";
    assetPicker.ReturnItemFields = 'Title,Name,Label,SourceUrl,FileRef';
    assetPicker.ReturnCallback = function () {
  
  // Self explaining variable names
        var video_AbsoluteUrl = arguments[0];
        var video_FolderName = arguments[1];

        var pathArray = video_AbsoluteUrl.split('/');

        var assetSite_Url;
        var assetList_DocLib;

        if (pathArray.length >= 5) {
            assetSite_Url = pathArray[0] + "//" + pathArray[2];
            assetList_DocLib = pathArray[3];

   // Helps you to rebuild the folder relative URL
            for (i = 4; i < pathArray.length - 1; i++) {
                assetList_DocLib = assetList_DocLib + "/" + pathArray[i];
            }

            // Finds the HTML img tag to substitute
            var idCalled = jQuery(this).attr('AssetUrlClientID');

            if (undefined !== arguments &&
    arguments.length > 3 &&
    assetSite_Url !== undefined &&
    assetList_DocLib !== undefined) {

    // REST url generation
    // Using URL and folder, you can request the first file of the video folder, which is the default video rendition
                restUrl = assetSite_Url + "/_api/Web/GetFolderByServerRelativeUrl('/" + assetList_DocLib + "/" + video_FolderName + "')/Files?$select=ServerRelativeUrl,Name&top=1";

                jQuery.ajax({
                    url: restUrl,
                    type: "GET",
                    crossDomain: true,
                    dataType: "json",
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: function (data) {
                        // If success, generate che HTML
                        var response = data.d.results;
                        if (response.length > 0) {
                            var videoUrl = assetSite_Url + response[0].ServerRelativeUrl;
                            var fileName = response[0].Name;
                            var extension = fileName.split('.').pop();

                            if (jQuery("#" + idCalled).length > 0)
                                jQuery("#" + idCalled).first().replaceWith("");
                        }
                    },
                    error: function (data) {
                        alert('Error');
                    }
                });
            }
        }
        else {
            alert("Error");
        }
    };

    var imageAsset = new LinkAsset("");
    imageAsset.LaunchModalAssetPicker(assetPicker);
};

// Generate a ID 
function rc_generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
    });
    return uuid;
};

Strategy: catalog connection with managed metadata multivalue field

Everybody knows about SharePoint catalog connection... maybe

What if you have a pre-existing catalog connection and your customer asks you to switch from a single value field (generally ItemCategory) to a multivalue field?

In a ideal world you should quote this and say "don't do it, don't even think about it"

In a business world you'll say "Yes, why not?".
I tried to convert the single value field in a multivalue field... trust me... don't try this if you don't like strange side effects.

AS IS
This is the typical product catalog configuration:
  • A product catalog site which is used as backend website
  • Contents are crawled by search service application
  • Public sites connect to indexed catalog


Solution
To understand next steps, mind every link under categories navigation term is allowed.
Let's assume you have a term set like that
  • Category 1
    • Subcategory 11
    • Subcategory 12
  • Category 2 
    • Subcategory 21
The catalog connection automatically creates these category friendly urls:

http://site/category1
http://site/category1/subcategory11
http://site/category1/subcategory11
http://site/category2
http://site/category2/subcategory21

So let's assume i have a product named Test, which is tagged on ItemCategory with term "Subcategory 11", i'll go to URL http://site/category1/subcategory11/test .

But what if i tell you that links like these below will not repond with a 404?
http://site/category1/test
http://site/category1/subcategory12/test
http://site/category2/test
http://site/category2/subcategory21/test

This behaviour will be extremely useful for us.

Editing product catalog
Because you don't want to destroy catalog connection, you just have to add a TaxonomyFieldTypeMulti field to the product catalog item content type

  
    
   
     TextField
     {024FECDC-E8A7-4DAC-BEB1-E9C373708BE5}
   
    
  

Link this new field to the term set you use to tag catalog items.
After that, you can create a event receiver in order to write the first  value entered in MultivalueItemCategory field in ItemCategory field (or the field you use for the catalog connection).
Create Content Search Web Part replacements
This is the most annoying part, we have to create a Web Part that we will use in category pages.
This web part does essentially three things:
  1. Recover the current navigation term
  2. Make a query searching che term related to the navigation term, in the MultivalueItemCategory we defined above
  3. Substitute Path values (catalog item friendly url) in order to make links relative to the current navigation term
  4. Show results
The core methods are About the single product page you can create a web part or a page layout, which has to contain methods similar to the previous web part.
This web part, must get the product using the navigation term and the friendly url segment and show the result.

Editing publishing site 
In pages document library, you have to create a category page (which contains the category CSWP replacement), and a product page (which contains the product CSWP replacement) and then edit target page settings for terms like this


And that's all folks.

Deleting a host named site collection... for real

A simple problem: you have to delete a host named site collection in order to recreate it.
When you try to recreate it, you get an error: SharePoint says the site collection already exists... if you restart the machine you'll be able to recreate it.
What if you cannot restart the machine whenever you want (read production environment).
$variable = Get-SPSite "http://already.deleted.site"
$variable
You'll get an output like this


Now recreate the site collection without problems ;)

Me, myself and I

My Photo
I'm just another IT guy sharing his knowledge with all of you out there.
Wanna know more?