Simple Angular WebPart using SharePoint Framework Preview

 

If you are not aware of SharePoint Framework, go through this article https://github.com/SharePoint/sp-dev-docs/wiki

Assumption

I hope you are aware of SharePoint Framework and your machine is ready for development.

In this article I am going  to explain how to create a very basic angular WebPart using SharePoint Framework

  • We are going to display the list items in this WebPart so create a list as shown below:

spfx1

  • Create a new project directory in your favorite location:

md SFX-Addin-MessageCenter

  • Navigate to the project directory

cd SFX-Addin-MessageCenter

  • Create a new Message Center web part by running the Yeoman SharePoint Generator:

yo @microsoft/sharepoint

You will be prompted with a series of questions:

  • Accept the default sfx-addin-message-center as your solution name and press Enter.
  • Select Use the current folder to place the files.

The next set of prompts will ask specific information about your web part:

  • Type Message Center as your web part name and press Enter.
  • Accept the default Message Center description as your web part description and press Enter.
  • Accept the default No javascript web framework as the framework you would like to use and press Enter.

At this point, yeoman will install the required dependencies and scaffold the solution files along with the Message Center web part. This might take a few minutes.

Once the scaffold is complete, you should see the following message indicating a successful scaffold:

spfx2

  • In the console, type the following to open the web part project in Visual Studio Code:

code.

spfx3

  • To install angular and ngOfficeUIFabric from npm you should run in the command line:

npm i angular ng-office-ui-fabric -S

  • Next, to install Angular typings, in the command line run:

tsd install angular –save

  • To install combokeys you should run in the command line

tsd install combokeys –save

  • Now create a js file to write our angular controller logic in the below location.

SFX-Addin-MessageCenter\src\webparts\messageCenter\app\controller_home.js

  • Write the below code in the controller js file

spfx4

Note: Here you can change the logic, site url for REST API, list name, columns as per your requirement.

  • In order to load Office UI Fabric CSS from a CDN, we first need to load the ModuleLoader class, by adding the following import statement to the Web Part’s code:

import ModuleLoader from ‘@microsoft/sp-module-loader’;

  • To use Angular in your Web Part you need to add the following in MessageCenterWebPart.ts:

import * as angular from ‘angular’;

  • To use ngOfficeUIFabric in your Web Part you need to add the following in MessageCenterWebPart.ts:

import ‘ng-office-ui-fabric’;

  • When bootstrapping the Angular application, we need to get a reference to $injector. So declare it privately within MessageCenterWebPart

private $injector: ng.auto.IInjectorService;

  • In the Web Part’s constructor, we use the loadCss function to load Office UI Fabric CSS:

spfx5

  • Replace the render method with the below code

spfx6

  • At this point we are ready to validate our WebPart. Switch to your console, make sure you are still in the SFX-Addin-MessageCenter directory and type the following to build and preview your web part in workbench.aspx page you have uploaded when setup the environment:

gulp serve –nobrowser

  • Open workbench.aspx from document library and add the Message Center WebPart. If everything works fine, you should see the list items in the WebPart as shown below:

spfx7

In the next tutorial, we will deploy and load the web part assets from CDN instead of localhost.

Fix for __REQUESTDIGEST value undefined issue- SharePoint Hosted App / Regular Page without Master Page

If you did not set master page on your  SharePoint pages(example: Angualr JS based page), your will get undefined error when you access $(“#__REQUESTDIGEST”).val(). To get digest value use the below code so that this can be passed when you call SharePoint REST APIs.

var formDigest; // Global Variable

$.ajax({
 url: <Pass App Web or Host Web Url based on requirement> + "/_api/contextinfo",
 type: "POST",
 headers: {
 "accept": "application/json;odata=verbose",
 "contentType": "text/xml"
 },
 success: function (data) {
 var requestdigest = data;
 formDigest = data.d.GetContextWebInformation.FormDigestValue;
 },
 error: function (err) { 
 console.log(JSON.stringify(err));
 }
 });

Like/Unlike SharePoint List Items from SharePoint Hosted App

To enable rating refer this article – https://support.office.com/en-us/article/Add-a-ratings-feature-to-your-library-5901fcfd-19ca-4f27-a65f-284654298552

Code to update like:

 

 function setLike(likeFlag)
 {
 SP.SOD.registerSod('reputation.js', '/_layouts/15/reputation.js');
 SP.SOD.executeFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function () {
 SP.SOD.executeFunc('sp.js', 'SP.ClientContext', UpdateLike(likeFlag));
 });
 }

 function UpdateLike(likeFlag) {
 var listId = "6d9e46c2-b396-4a4f-bc1f-6e265dfb6fe6"; //set list id and make sure rating is enabled in the list 
 var itemId = 3; //List Item Id 
 var ctx = new SP.ClientContext.get_current();
 Microsoft.Office.Server.ReputationModel.Reputation.setLike(ctx, listId, itemId, likeFlag); 
 ctx.executeQueryAsync(Function.createDelegate(this, this.RatingSuccess), Function.createDelegate(this, this.RatingFailure));
 }; 

 function RatingSuccess(sender, args) {
 alert('Rating updated successfully');
 } 

 function RatingFailure(sender, args) {
 alert('Failed:' + args.get_message()); 
 }

 
<button onclick="setLike(true)">Like</button>
<button onclick="setLike(false)">Unlike</button>

SharePoint 2013 – Call Search REST API from PowerShell Script

Add-Type -AssemblyName System.Web

$sServerPath = “http://<Site URL>”
$sQueryOptions = “selectproperties=’ManagedPropertyName’&clienttype=’ContentSearchRegular’&QueryTemplatePropertiesUrl=’spfile://webroot/queryparametertemplate.xml'”
$sUserName = “user name”
$sPassword =”password”
$sDomain=”domain name”
$WebRMethod=[Microsoft.PowerShell.Commands.WebRequestMethod]::Get

function Get-SPSearchResults
{
param ($keyword,$sUserName,$sPassword, $sDomain, $WebRMethod)
try
{
$spCredentials = New-Object System.Net.NetworkCredential($sUserName,$sPassword,$sDomain)
$enckeyword = [System.Web.HttpUtility]::UrlEncode(“‘$keyword'”)
$url = $sServerPath+”/_api/search/query?querytext=$enckeyword”+”&$sQueryOptions”

$spWebRequest = [System.Net.WebRequest]::Create($url)
$spWebRequest.Credentials = $spCredentials
$spWebRequest.Accept = “application/json;odata=verbose”
$spWebRequest.Method=$WebRMethod
$spWebResponse = $spWebRequest.GetResponse()
$spRequestStream = $spWebResponse.GetResponseStream()
$spReadStream = New-Object System.IO.StreamReader $spRequestStream
$spData=$spReadStream.ReadToEnd()
$results = $spData | ConvertFrom-Json
$results = $results.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results

for($i=0; $i -le $results.length-1; $i++)
{

$row = $results[$i]

for ($j=0; $j -le $row.Cells.results.length-1; $j++)
{

if ($row.Cells.results[$j].Key -eq ‘Title’)
{
Write-Host $row.Cells.results[$j].Value -ForegroundColor Green
}
}
}
}
catch
{
Write-Host $_.Exception.Message -ForegroundColor Red
}
}

try
{
Get-SPSearchResults -keyword “ca” -sUserName $sUserName -sPassword $sPassword -sDomain $sDomain -WebRMethod $WebRMethod
}
catch
{
Write-Host “Problem in running the REST API. Failed with error : ” + $_.Exception.Message -ForegroundColor Red
}

CustomActions not supported in the new SharePoint Online experience

Summary

CustomActions that deploy script, JSLinks, and additional web parts on the page are currently not supported in the new experience. Environments that require these unsupported features should continue using classic mode for the time being.

Affected Software Versions

This functionality is introduced gradually to organizations that have opted in to the SharePoint Online(SPOL) First Release program. This means that you may not yet see this feature immediately as the change is being pushed by Microsoft User by User.

Fix / Resolution

Microsoft is working on the long term plan for this. It does not mean that Microsoft would not support this in future. Microsoft is looking for few different options around these kind of customizations, but unfortunately plans have not yet been locked, so Microsoft can’t share exact final outcome yet.

Interim Workaround

Document Library Level

Flip the impacted document libraries back to classic mode via Library Settings -> Advanced Settings (or in a more heavy-handed approach to configure the classic mode at the tenant level).

Site Contents Page
Thankfully (for now at least) Microsoft gives us a link in the lower left-hand corner “Return to classic SharePoint” that will revert the experience back to the same old lovable customizable SharePoint experience. Tenant level single switch to turn on the classic mode is not available for Site Contents Page.

References

https://veenstra.me.uk/tag/return-to-classic-sharepoint/

You can see the product group response in this user voice request: https://sharepoint.uservoice.com/forums/329214-sites-and-collaboration/suggestions/13385364-allow-javascript-customization-and-css-branding-th and vote

https://www.yammer.com/itpronetwork/#/Threads/show?threadId=721245585

 

Filter on subdirectories in Google Analytics

Business Requirement

Modify the google Analytics to distinguish SharePoint root site traffic from Team and Sites managed path.

At the overview level where we see users and sessions this traffic is combined.  With separate collections, we can better measure the traffic we are looking to measure at a high level.

Solution

In google analytics we have subdirectory filters, and it’s really flexible with regular expressions.

For example, page path matches regex /legal/

Steps to Configure

  • Create a new in google analytics view

g1

  • Click  Filters on the newly created view
  • Click Add Filter Button
  • Provide a filter name and Select Predefined-Filter – Exclude – traffic to the subdirectories – that begin with – /teams/

g2.png

  • Click Add Filter Button
  • Provide a filter name and Select Predefined-Filter – Exclude – traffic to the subdirectories – that begin with – /sites/

g3.png

Notes:

  1. Do not touch or modify the out of the box All Website Data View
  2. We can create only 25 views in Google Free Account.
  3. This configuration will capture the data from the day when we setup this filter in the new view. To refer the old data, we still need to use the All Website Data view.
  4. Make sure the permissions are configured properly under user management for the new view.

SharePoint Page within Salesforce using IFrame

Recently I got a request to display a plain SharePoint ASPX page stored in SPOL publishing site within Salesforce. When I tried this I came across an error “This content cannot be displayed in a frame”. The reason for this issue is SharePoint prevents cross-domain IFRAMING of pages as a security measure to prevent clickjacking.

Tried to follow the below approach but no luck

http://crmbook.powerobjects.com/system-administration/sharepoint-document-management/beyond-basic-integration/displaying-an-office-365-sharepoint-page-in-iframe/

Since I was framing the ASPX page outside SharePoint I have to include additional two lines of code (refer the first two lines in the below image) on the ASPX page to enable IFRAMING. This solution worked for me. Please feel free to share if you have any other better idea.

AllowIframe

References:

https://msdn.microsoft.com/library/office/fp179925.aspx

https://blogs.msdn.microsoft.com/officeapps/2012/12/12/iframing-sharepoint-hosted-pages-in-apps

 

Follow

Get every new post delivered to your Inbox.

Join 27 other followers