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.

 

Advertisements

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 🙂 !!!!