O365, SharePoint 2010, 2013, 2016: Updating List item by using JSOM

Applies to :

  • SharePoint Online – O365
  • SharePoint 2010
  • SharePoint 2013
  • SharePoint 2016

Below is the source code to update list item by using JSOM,

var CurrPageUrl;
var PageName;
var webUrl; 
var listName = "PageHitCounts";
var itemId = 1;
var tempPN;
var success = "success";
var failure = "failure";
var siteUrl="My Site URL";
var pagename;
var item;

$(document).ready(function() 
{
CurrPageUrl=window.location.href;
pagename =  CurrPageUrl.substring(CurrPageUrl.lastIndexOf("/") + 1, CurrPageUrl.lastIndexOf("."));
PageName = pagename;
ExecuteOrDelayUntilScriptLoaded(PageHitOnpageLoad, "sp.js");
 });
 function PageHitOnpageLoad()
 {
var clientContext = new SP.ClientContext.get_current();
var selectedItems = SP.ListOperation.Selection.getSelectedItems(clientContext);
     var oList = clientContext.get_web().get_lists().getByTitle("PageHitCounts");
         
     var camlQuery = new SP.CamlQuery();
     camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' + 
         '<Value Type=\'Number\'>1</Value></Geq></Where></Query></View>');
     this.collListItem = oList.getItems(camlQuery);
     clientContext.load(collListItem);
     clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed)); 
} 

function onQuerySucceeded(sender, args) 
{
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();        
     while (listItemEnumerator.moveNext()) 
     {
         var oListItem = listItemEnumerator.get_current();
         listItemInfo += oListItem.get_item(PageName);
         var count = +listItemInfo + +1;
         oListItem.set_item(PageName, count);
         oListItem.update();
         clientContext.ExecuteQuery();
     }
}

function onQueryFailed(sender, args) 
{
  alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Hope this help.

Awarded Gold: Microsoft Technet Guru Competition – July 2016

 gold_tnwinnergoodninja
 technetgurucompetitionwinner
 Awarded Gold in the SharePoint 2010 / 2013 Technical Guru category – July 2016
 SharePoint 2010 / 2013 Technical Guru – July 2016 
0640_NinjaAwardTinyGold Amjad Khan SharePoint SharePoint Online: Create Site Columns, Content Type and Associate with Custom List or Library at site collection level using PowerShell and CSOM John Naguib: “Excellent article”
Ed Price: “I love the diagrams, description at the top, and the download to the code! It would be good to break the long code block up into sections to explain what the code does more. Great formatting with Headers and the TOC!”
0841.NinjaAwardTinySilver Shantha Kumar T Work with host web data using PnP JS library in the SharePoint Hosted Add-In John Naguib: “Incredible to have such topic discussed, excellent”
Ed Price: “Valuable scenario, great descriptions, and good use of images and code! It could benefit from a References section at the end with more resources to dig into.”
7827.NinjaAwardTinyBronze Waqas Sarwar SharePoint 2016 Managing Alternate Access Mapping Using PowerShell (Real World Example) Ed Price: “Good use of a See Also section. This is very clear and easy to read! Includes kudos from Arleta in the comments (“Nice article. Thanks!”). It’s a great scenario that’s well written!”
John Naguib: “Nice article”

 

O365 and SharePoint: Remove the WebPart from a site by using PowerShell

As we aware the WebpartManager class is helpful in Server side object model. The question popped-up in my mind “Is this possible by using PowerShell scripting?“.

I found answer as “Yes”.

Below is the code snippet to remove webpart from a site by specifying webpartId and site url,

$siteURL = “ht tp://sharePoint/sites/specialsite”; # first constant: site URL
$webpartId = “<guid of your choice for webpart>; # second argument: webpart GUID
$pagepath = “/default.aspx” # change page name or page path here
$pageURL = $siteURL + $pagepath
write-host “Processing site: “, $siteURL
Write-host “Processing page: ” , $pageURL
write-host “Processing webpart ID: ” , $webpartID
$site=new-object Microsoft.SharePoint.SPSite($siteURL)
$web=$site.Openweb()
$webpartmanager=$web.GetLimitedWebPartManager($pageURL, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$webpartmanager.DeleteWebPart($webpartmanager.Webparts[$webpartId])
$web.Update()
$web.Dispose()
write-host “Finished.”

O365 and SharePoint: List of WebParts in all sites of Web Application by using PowerShell

As we aware the WebpartManager class is helpful in Server side object model. The question popped-up in my mind “Is this possible by using PowerShell scripting?“.

I found answer as “Yes”.

Below is the code snippet to achieve the same,

$oContentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService;
[Microsoft.SharePoint.Administration.SPWebApplicationCollection]$waCollection = $oContentService.WebApplications;
$log = “.\results.txt” # output file name and path
$pagepath = “/default.aspx” # you can change page name or page path
“Site URL; WebPart Title ; Webpart ID” | out-file $log
$waCollection1 = $waCollection | where-object {$_.IsAdministrationWebApplication -eq $FALSE}
foreach ($wa in $waCollection1)
{
foreach ($obj in $wa.Sites)
{
write-host “Processing site: ” , $siteURL
$siteURL = $obj.URL

$site=new-object Microsoft.SharePoint.SPSite($siteURL)

$pageURL = $siteURL + $pagepath
$web=$site.Openweb()
$webpartmanager=$web.GetLimitedWebPartManager($pageURL, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
foreach ($webpart in $webpartmanager.WebParts)
{
$siteURL + “; ” + $webpart.Title + ” ; ” + $webpart.ID | out-file $log -append
}
}

SharePoint / Office 365 Migration: 7 – Important considerations

Migration

1. Take inventory

Migrations are like a journey into the unknown. Our best recommendation is to first make sure that you know what you are taking with you on this journey. This helps plan better to avoid common pitfalls and issues.

Getting a good idea of what is being migrated can be tricky. You may have lots of data accumulated over years and it may not be stored in a nice and structured way. Audit and analyse what data and files you have and in what format. Getting an idea of sizes is a good starter to understand the scope of the project.

Also it is a good idea to identify any special cases, regulatory requirements, security exceptions and files which don’t fit the normal 80% use cases. Being aware of these would empower you into better planning for your migrations.

 

2. House Keeping

Migrations are like moving home. You pack your stuff and move it elsewhere. However this is also a perfect opportunity to do some house keeping. You may not need some of the data and files you have accumulated over years. Some may be a perfect case for archiving. Then there is the case of duplicates. Identifying duplicates can be tricky but can be worth the effort. If done correctly, you can save some money my reducing your storage needs for the migration.

The biggest challenge is to find the correct owners of the data and get some approval on things which are not needed. That is always tricky. Also your business will have changed shape over years as it has evolved and this may be a good time to restructure some of the data organization to better reflect the shape of the organization going forward.

Another common tip to do at this stage is to think about data classification. Are there any tags you can apply to your files as additional metadata? E.g. Proposals, Quotes, Research Papers, Marketing Materials etc. You can also review security at this stage and decide if you want to add additional security classification to your files e.g. Confidential, Internal, Public. This will tremendously impact the findability of your data via logical data filtering and search.

 

3. Planning

Once you are armed with what you are taking with you on your journey and have better selected and restructured your files, you need to then consider where you are going. You need to draw up a migration plan on how you plan to get to your destination. You also need to consider how do you handle any special cases identified and how are you going to transform the data into a new restructured system.

Effective planning is the key to a successful migration. Perform some tests to get an idea of your migration speeds, network and system speeds to realistically get an idea of a timescale. Also consider how much impact a migration will have on your peak time load and if migrations will have to be done off peak hours to provide the quality of service needed for the day to day business activities.

 

4. Communication Plan

You are not alone on this journey into the unknown. You are steering the ship, however the whole organization is along with you on this journey. This step is vital for better user adoption of the new system. Create a communication plan on how you can effectively manage this change and inform your organization about it. I have seen a lot of people ignore this, however we consider this a very vital step to better user adoption.

 

5. Tools

Drag and drop migrations are rarely a reality. Due to the sheer volume of data in any migration project, key success relies on using automation. Consider using tools to help you with the various phases and take a lot of the pain away.Automate the inventory phase to get a good understanding of what you have.

The more detailed data you can get, the better your house keeping and planning will be. Finding duplicates can be a lot easy with a suitable tool. Automate the actual migration effort. These specialized migration tools can handle a lot of common issues and smoothen the process of moving the data over. We strongly recommend to use specialist tools to ensure a quick and smooth migration.

 

6. Testing

Test as much as possible. It is not physically practical to test every item, however along with manual testing, utilise some automated testing tools if possible to validate the migrations as much as possible. We utilise a bespoke tool at Toolagento add an additional layer of safety over manual testing. We cannot stress the importance of this phase more. This is a very vital phase as you don’t want to discover 6 months down the line that you are missing some data.

 

7. Cut over plan

Consider planning this very carefully. How do you plan to make the switch over to the live system. Are you going to go for a big bang migration or would gradual rollouts be good for you. How do you plan to synchronize the data, test it and get go live acceptance. Migrations are slow projects and can take days to complete. So having an effective cut over plan right from the start is really useful. This will ensure that you will have a relatively smooth transition instead of a bumpy ride.

Finally do not forget to celebrate when you have completed your migration, as you deserve it. Migrations are complicated projects and you deserve to pat yourself for steering the ship successfully across this journey.

O365: SPO Cmdlets for PowerShell

Below is the list of few important Cmdlets,

  • Site Groups
  • Users
    • Add-SPOUser – Add a user to an existing Site Collection Site Group.
    • Get-SPOUser – Get an existing user.
    • Remove-SPOUser – Remove an existing user from the Site Collection or from an existing Site Collection Group.
    • Set-SPOUser – Set whether an existing Site Collection user is a Site Collection administrator or not.
    • Get-SPOExternalUser – Returns external users from the tenant’s folder.
    • Remove-SPOExternalUser – Removes a collection of external users from the tenancy’s folder.
  • Site Collections
    • Get-SPOSite – Retrieve an existing Site Collection.
    • New-SPOSite – Create a new Site Collection.
    • Remove-SPOSite – Move an existing Site Collection to the recycle bin.
    • Repair-SPOSite – If any failed Site Collection scoped health check rules can perform an automatic repair then initiate the repair.
    • Set-SPOSite – Set the Owner, Title, Storage Quota, Storage Quota Warning Level, Resource Quota, Resource Quota Warning Level, Locale ID, and/or whether the Site Collection allows Self Service Upgrade.
    • Test-SPOSite – Run all Site Collection health check rules against the specified Site Collection.
    • Upgrade-SPOSite – Upgrade the Site Collection. This can do a build-to-build (e.g., RTM to SP1) upgrade or a version-to-version (e.g., 2010 to 2013) upgrade. Use the -VersionUpgrade parameter for a version-to-version upgrade.
    • Get-SPODeletedSite – Get a Site Collection from the recycle bin.
    • Remove-SPODeletedSite – Remove a Site Collection from the recycle bin (permanently deletes it).
    • Restore-SPODeletedSite – Restores an item from the recycle bin.
    • Request-SPOUpgradeEvaluationSite  – Creates a copy of the specified Site Collection and performs an upgrade on that copy.
    • Get-SPOWebTemplate – Get a list of all available web templates.
  • Tenants
    • Get-SPOTenant – Retrieves information about the subscription tenant. This includes the Storage Quota size, Storage Quota Allocated (used), Resource Quota size, Resource Quota Allocated (used), Compatibility Range (14-14, 14-15, or 15-15), whether External Services are enabled, and the No Access Redirect URL.
    • Get-SPOTenantLogEntry – Retrieves company logs (as of B2 only BCS logs are available).
    • Get-SPOTenantLogLastAvailableTimeInUtc – Returns the time when the logs are collected.
    • Set-SPOTenant – Sets the Minimum and Maximum Compatibility Level, whether External Services are enabled, and the No Access Redirect URL.
  • Apps
  • Connections

O365 – SharePoint Online: Alpaca JS based Apps development

Introduction

This article is primarily intended for creating a simple Apps based on Alpaca JS framework for O365 SharePoint Online.

Alpaca Demo

Download Source Code

Click here for Source code 

What is Alpaca JS framework?

Alpaca provides the easiest way to generate interactive HTML5 forms for web and mobile applications. It uses JSON Schema and simple Handlebars templates to generate great looking user interfaces on top of Twitter Bootstrap, jQuery UI, jQuery Mobile and HTML5.

Everything you need is provided out of the box. Alpaca comes pre-stocked with a large library of controls, templates, layouts and features to make rendering JSON-driven forms easy. It is designed around an extensible object-oriented pattern, allowing you to implement new controls, templates, I18N bundles and custom data persistence for your projects.

Alpaca is open-source and provided to you under the Apache 2.0 license. It is supported by Cloud CMS and is in use by organizations and within projects all around the world.

Steps to create the Alpaca based Apps for SharePoint Online

Step I

Create the HTML file by using the below source code,

<!DOCTYPE html>

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head>

<title>User Details</title>
<meta charset=”utf-8″ />
http://code.jquery.com/jquery-1.11.1.min.js
http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.0/handlebars.js
<!– alpaca –>
<link type=”text/css” href=”http://code.cloudcms.com/alpaca/1.5.17/bootstrap/alpaca.min.css&#8221; rel=”stylesheet” />

<style>
form {
padding-left: 2%;
width: 60%;
}
</style>
</head>
<body>

$(function () {
$(“#form1”).alpaca({
“schema”: {
“title”: “User Details”,
“description”: “Fill User Details”,
“type”: “object”,
“properties”: {
“Name”: {
“type”: “string”,
“title”: “Name”,
“id”: “txtName”,
“required”: true
},
“Password”: {
“type”: “string”,
“title”: “Password”,
“format”: “password”,
“required”: true
},
“Email Address”: {
“type”: “string”,
“title”: “Email Address”,
“format”: “email”,
“required”: true
},
“Cell Number”: {
“type”: “number”,
“title”: “Cell Number”,
“maxLength”: 10,
“minLength”: 10,
“required”: true
},
}
},
“options”: {
“form”: {
“attributes”: {
“action”: “http://httpbin.org/post&#8221;,
“method”: “post”
},
“buttons”: {
“submit”: {
“click”: function () {
this.ajaxSubmit().done(function () {
$.ajax({
url: “”,
type: “”,
dataType: “json”
});
});
alert(” User Name : ” + $(‘[name=”Name”]’)[0].value + “\n Email Address : ” + $(‘[name=”Email Address”]’)[0].value + “\n Cell Number : ” + $(‘[name=”Cell Number”]’)[0].value);

}
}
}
},
}
});
});

<link type=”text/css” href=”http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css&#8221; rel=”stylesheet” />
http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js

http://code.cloudcms.com/alpaca/1.5.17/bootstrap/alpaca.min.js

</body>
</html>

Step II

Click here for: Step by step creating Content Editor webpart and associate with HTML

Step III

Final result will be as below,

Alpaca Demo