Add welcome pop up for first time users of your site using AngularJs Material


Hi Guys,

We really do only have one chance for putting a first impression for end users on our website. User’s will never land back to your website if there is nothing interesting found on web site. Same logic works for SharePoint sites too. When a visitor lands on your site for the first time (and maybe the last), how you welcome them will have a big impact. This can be accomplished with pop-up boxes, fullscreen welcome mats, live chat invitations, and more.

This post is all about a welcome popup on SharePoint site. In brief, I try my best to provide very easy solution of showing welcome pop up.

Requirement: One of my recent project client asked to show a welcome message. Server side webarts are not promoted by out clients because our site was built in SP online. It sounds very easy but complication added by showing this pop up only once per user.

Solution: As a solution, i suggested to achieve this using Content editor web part. Just place some quick JS code on the landing page and with the help of a list we are able to detect if user is first time user or not. So here is the components of this solution:

  1. A list “Users” which stores list of first time users
  2. Content editor web part.
  3. Site Assets library to refer the local references like Angular, Jquery, css etc.

Let me go through step by step implementation of this solution.

Step I: Create a “Users” list

  1. Visit Site > Site contents.
  2. Click on New > Choose Custom List template> Name it as “FirstTimeUsers”.
  3. Once list is created. Navigate to newly created List settings > Add column
  4. Add column “User” of type “Person and Group”.
  5. Now with this list Title field is required. We can make this field hidden or optional if not required.

We are done with creating a list which stores information about first time users. We will be updating using rest api calls and each time when user logged on to site. His/her entries will be added to this list only.

Step II: Add references for angular, material, jquery etc.

This step can be skipped in case you need to refer all required libraries from CDN. But I never recommend this way, rather download the latest files to Site assets library. It also reduces extra burden on your site to download these library each time from CDN.

  1. Navigate to the Site assets library.
  2. Create a folder called “CustomFiles”.
  3. Create another folder “AngularJS”.
  4. Download files angular.min.js, angular-animate-min.js, angular-aria.min.js, angular-material.min.css, angular-material.min.js, angular-messages.min.js, jquery-3.3.1.min.js
  5. Upload these files to AngularJs folder.   

Step III: Create angularJS app files

  1. Create two files named as: dialog.tmpl.html and dialogApp.js
  2. Copy following code to dialog.tmpl.html file: dialog_tmpl_html
  3. Copy following code to dialogApp.js: dialogapp_js
  4. Now change the <Site URL> with the url of your site.

These two files are required for angularJS to initialize and configure to show dialog box. The html file can be used to modify contents of dialog box.

Step IV: Add content editor webpart on homepage.

  1. Navigate to the page where you need to show pop up
  2. Edit this page and click on add webpart under any zone
  3. Under “Media and content” find “Content Editor” web part. and add it.
  4. Now Edit this web part and under ribbon find “Format text” tab and “Edit Source” option under it.
  5. Now past following code here:

http://SiteURL/SiteAssets/customfiles/angularjs/angular.min.js

http://SiteURL/SiteAssets/customfiles/angularjs/angular-animate.min.js

http://SiteURL/SiteAssets/customfiles/angularjs/angular-aria.min.js

http://SiteURL/SiteAssets/customfiles/angularjs/angular-messages.min.js

http://SiteURL/SiteAssets/customfiles/angularjs/angular-material.min.js

http://SiteURL/SiteAssets/customfiles/dialogApp.js
http://SiteURL/SiteAssets/customfiles/angularjs/jquery-3.3.1.min.js
<link href=”<SiteURL>/SiteAssets/customfiles/angularjs/angular-material.min.css” rel=”stylesheet”/>

​​​​​​​

</div>

That is it. Just save your page and Publish it.

Step V: Test your pop up.

Now log on with separate users on the home page and check if there is entry created under “FirstTimeUsers” list.

Let me explain here a little about the ajax calls here. The code under dialogApp.js files first get the information of the logged on user. Get user information SharePoint using REST Api. Then using REST api, it tries to find out its entry under “FirstTimeUsers” list. Here is the rest call:

/_api/web/lists/getByTitle(‘FirstTimeUsers’)/items?$select=User/EMail&$expand=User&$filter=User/EMail eq ‘<email_of_user>’

In case, it found any entry popup is not shown to user. But if it has found any entry then pop up is shown and on close event of the pop up another rest query will insert entry to the FirstTimeUsers List.

That is all about it. Don’t forget to hit like and kindly rate this article.

Happy SharePointing !!!

 

AngularJS: Export Json object to Excel using AlaSQL


Hello,

I have spent significant time developing AngularJS and Angular 2 applications. But this requirement is quite new to me. Well, user wants to export to excel feature on one of our application page where we are using filtered data based upon some parameters. The design decision was on me whether to choose server side function to convert Json object in to CSV format and then export it to excel.

But I decided to choose another approach, not to involve server in exporting a Json data. I was not aware about ALASQL but later explored and found its very useful for me to implement this solution. Here I am explaining how to implement it.

What you need to import :

Just an intro about these two libraries:

AlaSQL is an open source SQL database for Javascript with a strong focus on query speed and data source flexibility for both relational data and schemaless data. It works in your browser, Node.js, and Cordova.

This library is designed for:

  • Fast in-memory SQL data processing for BI and ERP applications on fat clients
  • Easy ETL and options for persistency by data import / manipulation / export of several formats
  • All major browsers, Node.js, and mobile applications

Where js-xlsx is used to support for AngularJS export library. Both of these two has support to NG2 you can find more details about it here.

There are two ways to achieve the export:

  1. From Json object
    • alasql(‘SELECT * INTO XLS(“test.xls”,?) FROM ?’,[customStyle,$scope.items]);
  2. From html(like table)
    • alasql(‘SELECT * INTO XLSX(“myinquires.xlsx”,{headers:true})  FROM HTML(“#HtmltagID”,{headers:true})’);

It is very easy to implement. Please refer to my plnkr code to see the examples.

http://plnkr.co/edit/2UKA8yPl9Uiarr2uSwEd?p=preview

Hope this blog is beneficial for you.

 

AngularJS: Bind UI Select selection sequentially


Hello,

I felt lucky to work with angularJS with the integration with SharePoint(as backend) in my recent project. There was a requirement to have two drop-downs on a single page application where on selection of one; other drop-down value will be automatically filtered.  I am going to share with you guys that how I have implemented.  I understand that this may not be Ideal way of doing it but I am sure that it is quickest solution that I did in code to achieve this requirement.

HTML: The below html will generate two dropdowns and populate with country and states data.

<h3>Countries</h3>
<ui-select ng-model="ctrl.country.selected" name="country" theme="bootstrap" title="Select a Country" >
<ui-select-match placeholder="Select or search a country in the list...">{{$select.selected.name}}</ui-select-match>
<ui-select-choices repeat="country in ctrl.countries | filter: $select.search">
<span ng-bind-html="country.name | highlight: $select.search"></span>
<small ng-bind-html="country.code | highlight: $select.search"></small>
</ui-select-choices>
</ui-select>
<h3>States</h3>
<ui-select ng-model="ctrl.state.selected" name="state" theme="bootstrap" title="Select a state">
<ui-select-match placeholder="Select or search a state in the list...">{{$select.selected.name}}</ui-select-match>
<ui-select-choices repeat="s in ctrl.states | countryFilter: { concode: ctrl.country.selected.code }">
<span ng-bind-html="s.name | highlight: $select.search"></span>
<small ng-bind-html="s.concode | highlight: $select.search"></small>
</ui-select-choices>
<ui-select-no-choice>
<span ng-if="ctrl.country.selected.name">&nbsp; No state found for '{{ctrl.country.selected.name}}' country !</span>
<span ng-if="!ctrl.country.selected.name">&nbsp; Please select country !</span>
</ui-select-no-choice>
</ui-select>

Custom Filter:

If you have notice in abouve html code, I have created a custom search filter which search the states dropdown data based on the countyr selected using first dropdown. Here is the code for the filter:

app.filter("countryFilter", function () {
return function (items, props) {
var out = [];
if (angular.isArray(items)) {
var keys = Object.keys(props);
items.forEach(function (item) {
var itemMatches = false;
for (var i = 0; i < keys.length; i++) {
var prop = keys[i];
var text = props[prop].toLowerCase();
//if (item[prop].toString().toLowerCase().indexOf(text) !== -1) {
if (item[prop].toString().toLowerCase() === text) {
itemMatches = true;
break;
}
}
if (itemMatches) {
out.push(item);
}
});
} else {
// Let the output be the input untouched
out = items;
}
return out;
};
});

Demo: Plunker Demo

Output:

untitled

Hope this post will help you creating synchronous drop down using UI-Select.

Happy Coding !!

SharePoint CSOM for beginners: Get Current User details


Hi Guys,

This blog is targeted to developers who are novice to the client side object model in SharePoint. SharePoint apps by default provides a basic stub for getting user details inside app. But sometimes it is required to add client side code in simple script file to get user information. I hope this information will also be helpful starters of client side object model.

Pre-requisites:

1) Any version of SharePoint installed: SP 2013, SP 2010 or SP Online

2) A web application and a root site collection inside it. It does not matter whether site is team site or any other type of site.(Note: In case of publishing site you need to enable sp.js file loading).

3) SharePoint Designer installed.

Step I: Create a custom script file

A script file is required in order to place CSOM code to be executed. Well, here depending upon usability user can chooses any one of these two locations to create this file:

List or Style library: It will be hard to update script file if it is placed under style library. Every time one have to update the file in SP Designer in order to make any changes or one have to upload the latest file each time in case of any update.

15 hive folder: This is my favorite place in order to do such kind of research. Create a dummy folder under “15/Template/layouts/dummy”.

I am referring second approach as it is very comfortable to update the files in 15 hive. Now open the dummy folder and create a JS file there with any name say, CSOMDemo.js. Let this file blank as of now.

Step II: Refer a custom script file

Once custom JS file is created, now next is to refer this file to master page so that it will be utilized by SharePoint. There are also many option to refer the file: Master page, Page layout(in case of publishing site), using content editor web part etc.

For this blog I am referring the script file to master page. In order to do same, Open the site using SP Designer and click on All Files > _catalogs >  masterpage > seattle.master(for team site). Then right click on the file and select the option “Edit File in Advanced Mode”.

Capture1                        Capture2

Now find out the head section add following lines:

<script type=”text/javascript” src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js “></script>
<script type=”text/javascript” src=”/_layouts/15/dummy/Script/CSOMDemo.js”></script>

 

Names can vary according to your naming conventions. But one these lines are placed in master page, all site pages will be registered and enabled with jQuery and custom scripts.

Step III: Write CSOM Code

Open the custom script file and paste the following code in side it.

var currentUser;
$( document ).ready(function() {
console.log(‘ready’);
url = window.document.location.href;

// In case of Publishing site please use following code line

// SP.SOD.executeFunc(‘sp.js’, ‘SP.ClientContext’, init);

ExecuteOrDelayUntilScriptLoaded(init,’sp.js’);

function init(){
var context = new SP.ClientContext.get_current();
var web = context.get_web();
currentUser = web.get_currentUser();
currentUser.retrieve();
context.load(web);
context.executeQueryAsync(
function(){
//On success function
console.log(‘init succeeded..’);
console.log(currentUser.get_loginName());
console.log(currentUser.get_id());
console.log( currentUser.get_title());
console.log(currentUser.get_email());
},
function(){ //On fail function
alert(‘Error: ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}
);
}
});

That all. Here is the result:

Capture3

 

Hope that code will be helpful for you.

Happy SharePointing 🙂

JQuery: Get Rid off SharePoint Spell Check


Hi Guys,

After spending 3-4 hours of struggle, I finally found way to get rid off irritating SharePoint Spell checker. It caught people picker too under the umbrella of spell check, but why, usually it does not required. Well again it may be the requirement.

But for my case, I don’t want it to watch any of my control on whole site. I tried to navigate to Manage Farm Features > Spell Check feature. Even after deactivating this feature it still working like a stubborn functionality. Then I realized that nothing is impossible for a developer. I have JQuery with me I can hide that control.

Resolution:

1) Hiding spell check from the Ribbon: in order to hide the spell check feature to end user, trick that worked for me is to add following line in my custom js:

$(‘a:has(img[src*=”images/spellingHH.png”])’).parents(“li”).hide();

2) Exclude fields from the spell check feature: I have created follwoing method to exclude people picker and other inputs fields from spell check:

function DisableSpellCheck() {
var tagclass = $(“input”).attr(‘class’);
if (tagclass !== undefined) {
tagclass = tagclass.replace(‘ ms-spellcheck-true’, ”);
}
$(“.input”).attr(‘class’, tagclass);

var $fld_in = $(“div.authorEdit input”);
var $fld_tx = document.getElementsByTagName(‘textarea’);

for ($i = 0; $i < $fld_in.length; $i++) {
var $inputName = $fld_in[$i].getAttribute(‘name’);
if ($inputName.indexOf(‘UserField’) != -1) {
$fld_in[$i].className = ‘ms-spellcheck-false’;
}
}
for ($i = 0; $i < $fld_tx.length; $i++) {
var $inputName = $fld_tx[$i].getAttribute(‘name’);
if ($inputName.indexOf(‘UserField’) != -1) {
$fld_tx[$i].setAttribute(“excludeFromSpellCheck”, “true”);
}
}
}

Note: “authorEdit” is the custom class added to the people picker.

If you add this line of code to your master page or document.ready function of the page layout it will solve this issue.

Hope this little trick might helpful.

Happy SharePointing :)!!

Jquery: Validate the mobile number field.


Hi,

Below is the very simple code which is capable to validate the mobile number field on any .net form.

jQuery(document).ready(function () {
jQuery(“#btnChangeNumber”).click(function () {
var mobileNo = jQuery(“#txtNewMobileNumber”).val();
if (mobileNo == “”) {
alert(‘Please enter mobile number.’);
return false;
}
else {
var rege = /^[0-9\+\-\(\)\s]*$/;
if (!rege.test(mobileNo)) {
alert(‘Please enter valid mobile number.’);
return false;
}
}

});
});

Enjoy 🙂 !!!!