Monday, 5 October 2015

Standard function to check for null, undefined, or blank variables in JavaScript?

Question

Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases:

function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}

Answer

You can just check if the variable has a truthy value or not. That means

if( value ) {
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

Sunday, 4 October 2015

What is “upstream” and “downstream”

Question

I've started playing with Git and have come across the terms "upstream" and "downstream". I've seen these before but never understand them fully. What do these terms mean in the context of SCMs and source code?

Answer (Simple)

In terms of source control, you're "downstream" when you copy (clone, checkout, etc) from a repository. Information flowed "downstream" to you.

When you make changes, you usually want to send them back "upstream" so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.

Answer (Git)

There are two different contexts for upstream/downstream in git: remotes, and time/history. Upstream/downstream with respect to remotes is, the downstream repo will be pulling from the upstream repo (changes will flow downstream naturally). Upstream/downstream with respect to time/history can be confusing, because upstream in time means downstream in history, and vice-versa (genealogy terminology works much better here - parent/ancestor/child/descendant).

Saturday, 3 October 2015

Angular CRUD operation helper service for sharepoint

Here we have some beautiful Angular Factory class Which help's us in any crud operation For Rest API in sharepoint

    "use strict";
    (function () {
        angular.module("docapp")
            .factory("baseSvc", ["$http", "$q", function ($http, $q) {
                var baseUrl = _spPageContextInfo.siteAbsoluteUrl;
                var getRequest = function (query) {
                    var deferred = $q.defer();
                    $http({
                        url: baseUrl + query,
                        method: "GET",
                        headers: {
                            "accept": "application/json;odata=verbose",
                            "content-Type": "application/json;odata=verbose"
                        }
                    })
                        .success(function (result) {
                            deferred.resolve(result);
                        })
                        .error(function (result, status) {
                            deferred.reject(status);
                        });
                    return deferred.promise;
                };
                var postRequest = function (data, url) {
                    var deferred = $q.defer();
                    $http({
                        url: baseUrl + url,
                        method: "POST",
                        headers: {
                            "accept": "application/json;odata=verbose",
                            "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
                            "content-Type": "application/json;odata=verbose"
                        },
                        data: JSON.stringify(data)
                    })
                        .success(function (result) {
                            deferred.resolve(result);
                        })
                        .error(function (result, status) {
                            deferred.reject(status);
                        });
                    return deferred.promise;
                };
                var updateRequest = function (data, url) {
                    var deferred = $q.defer();
                    $http({
                        url: baseUrl + url,
                        method: "PATCH",
                        headers: {
                            "accept": "application/json;odata=verbose",
                            "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
                            "content-Type": "application/json;odata=verbose",
                            "X-Http-Method": "PATCH",
                            "If-Match": "*"
                        },
                        data: JSON.stringify(data)
                    })
                        .success(function (result) {
                            deferred.resolve(result);
                        })
                        .error(function (result, status) {
                            deferred.reject(status);
                        });
                    return deferred.promise;
                };
                var deleteRequest = function (url) {
                    var deferred = $q.defer();
                    $http({
                        url: baseUrl + url,
                        method: "DELETE",
                        headers: {
                            "accept": "application/json;odata=verbose",
                            "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
                            "IF-MATCH": "*"
                        }
                    })
                        .success(function (result) {
                            deferred.resolve(result);
                        })
                        .error(function (result, status) {
                            deferred.reject(status);
                        });
                    return deferred.promise;
                };
                return {
                    getRequest: getRequest,
                    postRequest: postRequest,
                    updateRequest: updateRequest,
                    deleteRequest: deleteRequest
                };
            }]);
    })();

Ok How do we use it then ?

Answer is very simple. Just make another factory class accoding to your business logic
    (function () {
        'use strict';
        var app = angular.module('docapp');
        app.factory("taskSvc", ["baseSvc", function (baseService) {
            var listEndPoint = '/_api/web/lists/';
            var getAll = function () {
                var query = listEndPoint + "GetByTitle('Asana2')/Items?$select=Title,Category,ID,PriorityCod,Desc2,AssignedTo&$filter=Status ne 'compleated'";
                return baseService.getRequest(query);
            };

            var getTaskByUser = function (userID) {
                var query = listEndPoint + "GetByTitle('Asana2')/Items?$select=Title,Category,ID,PriorityCod,Desc2,AssignedTo&$filter=Status ne 'compleated' and AssignedTo eq '"+userID+"'";
                return baseService.getRequest(query);
            };

            var getCommentsById = function (ID) {
                var query = listEndPoint + "GetByTitle('Activities')/Items?$select=TaskID,ActivityType,Cmnt,ID,EntryDate,UserCmnt,ProfilePic&$filter=ActivityType eq '2' and TaskID eq " + ID + "";

                return baseService.getRequest(query);
            }
            var addNewTask = function (tsk) {
                var data = {
                    __metadata: { 'type': 'SP.Data.Asana2ListItem' },
                    Title: tsk.Title,
                    PriorityCod: tsk.PriorityCod.toString(),
                    Category:  tsk.CategoryCode.toString(),
                    Desc2: tsk.Description,
                    AssignedTo: tsk.AssignedUserId.toString()
                };

                //console.log(tsk.AssignedUserId);
                var url = listEndPoint + "GetByTitle('Asana2')/Items";
                return baseService.postRequest(data, url);
            };
            var updatePriority = function (updatePriorityTsk) {
                var data = {
                    __metadata: { 'type': 'SP.Data.Asana2ListItem' },
                    PriorityCod: updatePriorityTsk.PriorityCod.toString(),
                };
                var url = listEndPoint + "/GetByTitle('Asana2')/GetItemById(" + updatePriorityTsk.ID + ")";
                return baseService.updateRequest(data, url);
            };

            var updateUser = function (updateUserTsk) {
                var data = {
                    __metadata: { 'type': 'SP.Data.Asana2ListItem' },
                    AssignedTo: updateUserTsk.AssignedTo,
                };
                var url = listEndPoint + "/GetByTitle('Asana2')/GetItemById(" + updateUserTsk.ID + ")";
                return baseService.updateRequest(data, url);
            };

            //var updatePriority = function (updatePriorityTsk) {
            //    var data = {
            //        __metadata: { 'type': 'SP.Data.Asana2ListItem' },
            //        PriorityCod: updatePriorityTsk.PriorityCod.toString(),
            //    };
            //    var url = listEndPoint + "/GetByTitle('Asana2')/GetItemById(" + updatePriorityTsk.ID + ")";
            //    return baseService.updateRequest(data, url);
            //};

            var updateCategory = function (updateCategoryTsk) {
                var data = {
                    __metadata: { 'type': 'SP.Data.Asana2ListItem' },
                    Category: updateCategoryTsk.Category.toString(),
                };
                var url = listEndPoint + "/GetByTitle('Asana2')/GetItemById(" + updateCategoryTsk.ID + ")";
                return baseService.updateRequest(data, url);
            };

            var updateDesc = function (updateDescTsk) {
                var data = {
                    __metadata: { 'type': 'SP.Data.Asana2ListItem' },
                    Desc2: updateDescTsk.Desc2.toString(),
                };
                var url = listEndPoint + "/GetByTitle('Asana2')/GetItemById(" + updateDescTsk.ID + ")";
                return baseService.updateRequest(data, url);
            };

            var updateTitle = function (updateTitleTsk) {
                var data = {
                    __metadata: { 'type': 'SP.Data.Asana2ListItem' },
                    Title: updateTitleTsk.Title.toString(),
                };
                var url = listEndPoint + "/GetByTitle('Asana2')/GetItemById(" + updateTitleTsk.ID + ")";
                return baseService.updateRequest(data, url);
            };

            var compleateTask = function (ID) {
                var data = {
                    __metadata: { 'type': 'SP.Data.Asana2ListItem' },
                    Status: 'compleated',
                };
                var url = listEndPoint + "/GetByTitle('Asana2')/GetItemById(" + ID + ")";
                return baseService.updateRequest(data, url);
            };


            var addNewActivities = function (comment) {
                var data = {
                    __metadata: { 'type': 'SP.Data.ActivitiesListItem' },
                   // Title:'title',
                    ActivityType: '2',
                    Cmnt: comment.Cmnt,
                    UserCmnt: comment.User,
                    ProfilePic: 'img/Users/ryan-301.jpg',
                    TaskID: comment.tskid.toString(),


                };
                var url = listEndPoint + "GetByTitle('Activities')/Items";
                return baseService.postRequest(data, url);
            };
        

            return {
                getAll: getAll,
                getCommentsById: getCommentsById,
                addNewTask: addNewTask,
                addNewActivities: addNewActivities,
                updatePriority: updatePriority,
                updateCategory: updateCategory,
                updateDesc: updateDesc,
                updateTitle: updateTitle,
                compleateTask: compleateTask,
                updateUser: updateUser,
                getTaskByUser: getTaskByUser
            };


        }]);

    })();

And now use like this below.

        $scope.GetContractMaster = function () {
            clauseSvc.getAll()
              .then(function (response) {
                  $scope.ContractMst.rowData = response.d.results;
                 
              });
        };

        $scope.updateUser = function () {
            $scope.updateUserTsk = {
                ID: $scope.comment.tskid,
                AssignedTo: $scope.TaskDtl.AllUsers,
            };

            taskSvc.updateUser($scope.updateUserTsk)
            .then(function (response) {
                $scope.getMyTask();
            });
        };

and so on ;) Cheers ;)

Friday, 2 October 2015

Windows Task Scheduler SharePoint Backup Script

Create Windows PowerShell script

    Add-PSSnapin Microsoft.SharePoint.PowerShell 
    backup-spsite -identity $args[0] -path $args[1] -force

Create Batch Script to execute PowerShell script

    @echo off
    SET SOURCE_SITE=http://SPFarm:20045/ 
    SET DEST=C:\backup\Backup_site.bak
    echo "backup Started at" %DATE% >> C:\ backup\Log.txt
    powershell -command C:\Scripts\BackupSPSite.ps1  %SOURCE_SITE% %DEST%
    echo "Backup completed successfully at %DEST%" on %DATE% >> C:\ backup\Log.txt
    @echo on

Run Batch Script to execute PowerShell script

  • Run batch script to check successful backup and log creation at c:\backup.
  • Now run it from the Windows Task Scheduler. :)

Restore Sharepoint Site

EXAMPLE

    Restore-SPSite http://server_name/sites/site_name -Path C:\Backup\site_name.bak
This example restores a site collection from the backup file C:\Backup\site_name.bak to the site collection URL http://server_name/sites/site_name.

EXAMPLE

    Restore-SPSite http://server_name/sites/site_name -Path C:\Backup\site_name.bak -Force -DatabaseServer SQLBE1 -DatabaseName SQLDB1
This example restores a site collection backup from the backup file C:\Backup\site_name.bak, but overwrites the existing site collection at http://server_name/sites/site_name while specifying that the site collection must be stored in a specific content database.

EXAMPLE

    Restore-SPSite http://www.example.com -Path \\file_server\share\site_name.bak -HostHeaderWebApplication http://server_name
This example restores a site collection backup from the backup file \\file_server\share\site_name.bak to the host-named site collection http://www.example.com on the Web application http://server_name.

Backup Sharepoint Site

EXAMPLE

    Backup-SPSite http://server_name/sites/site_name -Path C:\Backup\site_name.bak
This example backs up a site collection at http://server_name/sites/site_name to the C:\Backup\site_name.bak file.

EXAMPLE

    Get-SPSiteAdministration http://server_name/sites/site_name | Backup-SPSite -Path C:\Backup\site_name.bak
This example backs up a site collection at http://server_name/sites/site_name to the C:\Backup\site_name.bak file. Same result as Example 1, but a different way of performing the operation.

EXAMPLE

    Backup-SPSite http://server_name/sites/site_name -Path C:\Backup\site_name.bak -UseSqlSnapshot
This example backs up a site collection using database snapshots to ensure backup integrity.

Build JSON Hierarchy from Structured Data

After a troublesome fight i almost figured how to convert a flat json file to a Hierarchical one.
  list = [
    {
      id: 1,
      title: 'home',
      parent: null
    },
    {
      id: 2,
      title: 'about',
      parent: null
    },
    {
      id: 3,
      title: 'team',
      parent: 2
    },
    {
      id: 4,
      title: 'company',
      parent: 2
    }
  ]

  function treeify(list, idAttr, parentAttr, childrenAttr) {
      if (!idAttr) idAttr = 'id';
      if (!parentAttr) parentAttr = 'parent';
      if (!childrenAttr) childrenAttr = 'children';
      var treeList = [];
      var lookup = {};
      list.forEach(function(obj) {
          lookup[obj[idAttr]] = obj;
          obj[childrenAttr] = [];
      });
      list.forEach(function(obj) {
          if (obj[parentAttr] != null) {
              lookup[obj[parentAttr]][childrenAttr].push(obj);
          } else {
              treeList.push(obj);
          }
      });
      return treeList;
  };

  console.log(JSON.stringify(treeify(list)));