Tuesday, October 7, 2014

SharePoint 2013: List operation using AngularJS Part 6

This post will explain you about how to add/Delete List. I have added some validation rules which may help you setup in HTML page using "required" tag of AngularJS

Service:
    this.AddList = function (listName) {
        var item =JSON.stringify({
            "__metadata": { "type": "SP.List" },
            "AllowContentTypes": "true",
            "BaseTemplate": "104",
            "ContentTypesEnabled": "true",
            "Description": "List created by AngularJS service call",
            "Title": listName
        });
        var config = {
            headers: {
                "Content-Type": "application/json;odata=verbose",
                "ACCEPT": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            }
        };
        return $http.post(siteUrl + "/_api/web/lists", item, config);
    };
    this.GetListByName = function (listName) {
        var config = {
            headers: {
                "ACCEPT": "application/json;odata=verbose"
            }
        };
        return $http.get(siteUrl + "/_api/web/lists?$filter=Title eq '" + listName+"'", config);
    };

    this.DeleteList = function (data) {
        var config = {
            contentType: "application/json;odata=verbose",
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "DELETE",
                "If-Match": data.__metadata.etag
            }
        };
        return $http.post(data.__metadata.uri, null, config);
    };


Controller:
$scope.AddList = function () {
        ListService.AddList($scope.listName)
        .success(function () {
            alert("list created");
            $scope.$broadcast("RefillList");
        })
        .error(function () {
            alert("fail to add list");
        });
    };
    $scope.DeleteList = function () {
        ListService.GetListByName($scope.listName)
        .success(function (data) {
            var result = data.d.results[0];
            ListService.DeleteList(result)
            .success(function () {
                alert("list deleted");
                $scope.$broadcast("RefillList");

            })
            .error(function () {
                alert("failed to delete list");
            });
        })
        .error(function () {
            alert("error");
        });
    };
    $scope.$on('RefillList', function () {
        ListService.GetLists()
        .success(function (data) {
            var results = data["d"]["results"];
            $scope.lists = results;
        })
        .error(function () {
            alert("error while getting items");
        });
    });


HTML:
<ng-form name="listForm">
<div> Total List</div>
    <input ng-model="listName" name="listName" required placeholder="List Name" />
    <span class="error" ng-show="listForm.listName.$error.required">Required!</span>
    <input type="button" ng-click="AddList()" value="Add List" ng-disabled="!listForm.$valid" /> 
    <input type="button" ng-click="GetLists()" value="GetLists" />
    <input type="button" ng-click="DeleteList()" value="DeleteList" ng-disabled="!listForm.$valid"/>

<ul>
    <li ng-repeat="list in lists">
        <a ng-click="GetListItems(list.Title)">{{list.Title}}</a>
        </li>
    </ul>

    <ul>
    <li ng-repeat="listItem in listItems">
        <a ng-click="GetListItemsById(listItem.Id,listItem.Title)">{{listItem.Title}}</a>
    </li>
</ul>
    </ng-form>
<ng-form name="itemForm">
<input ng-model="listName" name="listName" placeholder="List Name" required />
    <span class="error" ng-show="itemForm.itemForm.$error.required"></span>
    <input ng-model="itemId" name="itemId" ng-readonly="true" placeholder="Id" />
    <input ng-model="iTitle" placeholder="Title" required name="iTitle"  />
    <input type="button" ng-click="AddListItem()" value="AddListItem" ng-disabled="!itemForm.$valid" />
    <input type="button" ng-click="UpdateListItem()" value="UpdateListItem" ng-disabled="!itemForm.$valid" />
    <input type="button" ng-click="DeleteListItem()" value="DeleteListItem" ng-disabled="!itemForm.$valid" />
</ng-form>
<div ng-hide="true">
    {{jsonData}}
</div>
<div ng-hide="true">
    {{listItemJSON}}
</div>
    

Monday, October 6, 2014

SharePoint 2013: List operation using AngularJS Part 5

This post will explain you about how to delete list item. 
Add Below function to Service file

 this.DeleteListItem = function (data) {
        var config = {
            contentType: "application/json;odata=verbose",
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "DELETE",
                "If-Match": data.__metadata.etag
            }
        };
        return $http.post(data.__metadata.uri, null , config);
    };

Add Below code to Controller file.

 $scope.DeleteListItem = function () {
        ListService.GetListItemsById($scope.listName, $scope.itemId)
        .success(function (data) {
            var result = data.d.results[0];
            ListService.DeleteListItem(result)
            .success(function () {
                alert("item deleted");
                $scope.$broadcast("RefillData");
            })
            .error(function () {
                alert("delete failed");
            });
        })
        .error(function () {
            alert("error");
        });
    };

Update below code from HTML file

List Name : <input ng-model="listName" />ID: <input ng-model="itemId" ng-readonly="true" /> Title : <input ng-model="iTitle" /><input type="button" ng-click="AddListItem()" value="AddListItem" /><input type="button" ng-click="UpdateListItem()" value="UpdateListItem" /><input type="button" ng-click="DeleteListItem()" value="DeleteListItem" />


SharePoint 2013: List operation using AngularJS Part 4

There are some changes in Add/Retrieve list item methods from previous posts. Please make a note about that. This post will explain you about how to update list item.

HTML:

<div> Total List</div>
<input type="button" ng-click="GetLists()" value="GetLists" />
<ul>
    <li ng-repeat="list in lists">
        <a ng-click="GetListItems(list.Title)">{{list.Title}}</a>
        </li>
    </ul>

    <ul>
    <li ng-repeat="listItem in listItems">
        <a ng-click="GetListItemsById(listItem.Id,listItem.Title)">{{listItem.Title}}</a>
    </li>
</ul>
List Name : <input ng-model="listName" />ID: <input ng-model="itemId" ng-readonly="true" /> Title : <input ng-model="iTitle" /><input type="button" ng-click="AddListItem()" value="AddListItem" /><input type="button" ng-click="UpdateListItem()" value="UpdateListItem" />
<div ng-hide="true">
    {{jsonData}}
</div>
<div ng-hide="true">
    {{listItemJSON}}
</div>

Controller: 

var listModule = angular.module('listModule', []);
listModule.controller('listController', ['$scope', 'ListService', function ($scope, ListService) {
    $scope.GetLists = function () {
        ListService.GetLists()
        .success(function (data) {
            $scope.jsonData = JSON.stringify(data);
            var results = data["d"]["results"];
            $scope.lists = results;
        })
        .error(function () {
            alert("error");
        });
    };
    $scope.GetListItems = function (listName) {
        $scope.listName = listName;
        ListService.GetListItems(listName)
        .success(function (data) {
            $scope.listItemJSON = JSON.stringify(data);
            var results = data["d"]["results"];
            $scope.listItems = results;
        })
        .error(function () {
            alert("error");
        });
    };
    $scope.GetListItemsById = function (listId,listTitle) {
        
        $scope.itemId = listId;
        $scope.iTitle = listTitle;
    };

    $scope.AddListItem = function () {
        ListService.AddItem($scope.listName, $scope.iTitle)
        .success(function () {
            $scope.$broadcast('RefillData');
         })
        .error(function () {
            alert("fail");
        });
    };
    $scope.UpdateListItem = function () {
        ListService.GetListItemsById($scope.listName, $scope.itemId)
        .success(function (data) {
            var result = data.d.results[0];
            ListService.UpdateListItem(result, $scope.listName, $scope.iTitle)
            .success(function () {
                $scope.$broadcast('RefillData');
            })
            .error(function () {
                alert("update failed");
            });
        })
        .error(function () {
            alert("error");
        });
    };
    $scope.$on('RefillData', function () {
        ListService.GetListItems($scope.listName)
        .success(function (data) {
            var results = data["d"]["results"];
            $scope.listItems = results;
        })
        .error(function () {
            alert("error while getting items");
        });
    });
}]);

Service: 

var listServiceModule = angular.module('listServiceModule', []);
listServiceModule.service('ListService', ['$http', function ($http) {
    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
    this.GetLists = function () {
        var config = {
                headers: {
                    "ACCEPT": "application/json;odata=verbose"
                }
        };
        return $http.get(siteUrl + "/_api/web/lists", config);
    };

    this.GetListItems = function (listName) {
        var config = {
            headers: {
                "Accept": "application/json;odata=verbose"
            }
        };
        return $http.get(siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items", config);
    };

    this.GetListItemsById = function (listName,itemId) {
        var config = {
            headers: {
                "Accept": "application/json;odata=verbose"
            }
        };
        return $http.get(siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$filter=Id eq " + itemId, config);
    };

    
    this.AddItem = function (listName, iTitle) {
        var item = JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'Title': iTitle });
        var config = {
            headers: {
                "Content-Type": "application/json;odata=verbose",
                "ACCEPT": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            }
        };
        return $http.post(siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items", item, config);
    };

    this.UpdateListItem = function (data, listName, iTitle) {
        var item = JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'Title': iTitle });
        var config = {
            contentType: "application/json;odata=verbose",
            headers: {
                "Accept": "application/json;odata=verbose",
                "Content-Type": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": data.__metadata.etag
            }
        };
        return $http.post(data.__metadata.uri, item, config);
    };
}]);

Friday, October 3, 2014

SharePoint 2013: List operation using AngularJS Part 3

This post will explain you about how to retrieve List/ List Items and add List Item.

There is one more important point needs to understand in AngularJS boradcast/emit/on event. Here we have only one controller but this will help you to broadcast or emit event from parent to child or child to parent. Its just like a listener.

HTML:

<div> Total List</div>
<input type="button" ng-click="GetLists()" value="GetLists" />
<ul>
    <li ng-repeat="list in lists">
        <a ng-click="GetListItemsByName(list.Title)">{{list.Title}}</a>
        </li>
    </ul>

    <ul>
    <li ng-repeat="listItem in listItems">
        {{listItem.Title}}
    </li>
</ul>


List Name : <input ng-model="listName" /> Title : <input ng-model="iTitle" /><input type="button" ng-click="AddListItem()" value="AddListItem" />


<div>
    {{jsonData}}
</div>
<div>
    {{listItemJSON}}
</div>

Controller:

var listModule = angular.module('listModule', []);
listModule.controller('listController', ['$scope', 'ListService', function ($scope, ListService) {
    $scope.GetLists = function () {
        ListService.GetLists()
        .success(function (data) {
            $scope.jsonData = JSON.stringify(data);
            var results = data["d"]["results"];
            $scope.lists = results;
        })
        .error(function () {
            alert("error");
        });
    };
    $scope.GetListItems = function () {
        ListService.GetListItems($scope.listName)
        .success(function (data) {
            $scope.listItemJSON = JSON.stringify(data);
            var results = data["d"]["results"];
            $scope.listItems = results;
        })
        .error(function () {
            alert("error");
        });
    };
    $scope.GetListItemsByName = function (listName) {
        $scope.listName = listName;
        ListService.GetListItems(listName)
        .success(function (data) {
            $scope.listItemJSON = JSON.stringify(data);
            var results = data["d"]["results"];
            $scope.listItems = results;
        })
        .error(function () {
            alert("error");
        });
    };
    $scope.AddListItem = function () {
        ListService.AddItem($scope.listName, $scope.iTitle)
        .success(function () {
            $scope.$broadcast('RefillData');
         })
        .error(function () {
            alert("fail");
        });
    };
    $scope.$on('RefillData', function () {
        ListService.GetListItems($scope.listName)
        .success(function (data) {
            var results = data["d"]["results"];
            $scope.listItems = results;
        })
        .error(function () {
            alert("error while getting items");
        });
    });
}]);

Service:

var listServiceModule = angular.module('listServiceModule', []);
listServiceModule.service('ListService', ['$http', function ($http) {
    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
    this.GetLists = function () {
        var config = {
                headers: {
                    "ACCEPT": "application/json;odata=verbose"
                }
        };
        return $http.get(siteUrl + "/_api/web/lists", config);
    };

    this.GetListItems = function (listName) {
        var config = {
            headers: {
                "Accept": "application/json;odata=verbose"
            }
        };
        return $http.get(siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items", config);
    };
    
    this.AddItem = function (listName, iTitle) {
        var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
        var itemType = GetItemTypeForListName(listName);
        var item = {
            "__metadata": { "type": itemType },
            "Title": iTitle
        };
        var config = {
            headers: {
                "Content-Type": "application/json;odata=verbose",
                "ACCEPT": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            }
        };
        return $http.post(siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items", item, config);
    };
}]);

Functions:

function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
}


Thursday, October 2, 2014

SharePoint 2013: List operation using AngularJS Part 2

Below example explains you about how to get List Items using AngularJS service.

HTML Code:
<input ng-model="listName" /> : <input type="button" ng-click="GetListItems()" value="GetListItems" />
<ul>
    <li ng-repeat="listItem in listItems">
        {{listItem.Title}}
    </li>
</ul>
<div>
    {{listItemJSON}}
</div>

Controller File:
var listModule = angular.module('listModule', []);
listModule.controller('listController', ['$scope', 'ListService', function ($scope, ListService) {
    $scope.GetLists = function () {
        ListService.GetLists()
        .success(function (data) {
            $scope.jsonData = JSON.stringify(data);
            var results = data["d"]["results"];
            $scope.lists = results;
        })
        .error(function () {
            alert("error");
        });
    };
    $scope.GetListItems = function () {
        ListService.GetListItems($scope.listName)
        .success(function (data) {
            $scope.listItemJSON = JSON.stringify(data);
            var results = data["d"]["results"];
            $scope.listItems = results;
        })
        .error(function () {
            alert("error");
        });
    };
}]);


Service File:
var listServiceModule = angular.module('listServiceModule', []);
listServiceModule.service('ListService', ['$http', function ($http) {
    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
    this.GetLists = function () {
        
        var config = {
                headers: {
                    "ACCEPT": "application/json;odata=verbose"
                }
        };
        return $http.get(siteUrl + "/_api/web/lists", config);
    };

    this.GetListItems = function (listName) {
        var config = {
            headers: {
                "Accept": "application/json;odata=verbose"
            }
        };
        return $http.get(siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items", config);
    };
  
}]);

SharePoint 2013: List operation using AngularJS Part 1

If you want to create structure for AngularJS  based project, Please follow my previous post to create it. Here I am mentioning module vise information. I have developed Service in AngularJS to get all list from SharePoint site.


HTML Code :

<div> Total List</div>

<input type="button" ng-click="GetLists()" value="GetLists" />

<ul>

    <li ng-repeat="list in lists">

        {{list.Title}}

        </li>

    </ul>

<br />

<div>

    {{jsonData}}

</div>

Config.js

var configModule = angular.module('configModule', [

    'ngRoute',

    'listModule',

    'listServiceModule'

]);

Controller File :

var listModule = angular.module('listModule', []);

listModule.controller('listController', ['$scope', 'ListService', function ($scope, ListService) {

    $scope.GetLists = function () {

        ListService.GetLists()

        .success(function (data) {

            $scope.jsonData = JSON.stringify(data);

            var results = data["d"]["results"];

            $scope.lists = results;

        })

        .error(function () {

            alert("error");

        });

    };

}]);

Service File :

var listServiceModule = angular.module('listServiceModule', []);

listServiceModule.service('ListService', ['$http', function ($http) {

    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;

    this.GetLists = function () {

       

        var config = {

                headers: {

                    "ACCEPT": "application/json;odata=verbose"

                }

        };

        return $http.get(siteUrl + "/_api/web/lists", config);

    };

}]);

Common Function File :

function GetItemTypeForListName(name) {

    return "SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";

}

Friday, September 12, 2014

AngularJS: How to implement Service

Here is the simple implementation for Calculator service. I have added two services in controller.js file from previous example and register it in app.js file.


controller.js

/* Define Service */
var appService = angular.module('appService',[]);
appService.service('mathService',function(){
    this.add = function(a,b){
        return a+b;
    };
    this.multiply = function(a,b){
        return a*b;
    };
});
appService.service('calculatorService', function(mathService){
    this.square = function(a){
        return mathService.multiply(a,a);
    };
});


app.js

var configModule = angular.module('configModule',[
    'ngRoute',
    'phoneDetailModule',
    'phoneListModule',
    'appFilter',
    'appService'

]);



HTML Code to invoke that service

Enter a number:
<input type="number" ng-model="number" />
<button ng-click="doSquare()">Square</button>

Thursday, September 11, 2014

AngularJS: How to implement Custom Filter

You can customize/create filter as per your requirement. You have to configure that filter into configuration module.

You just need to add below code in controller.js (this is just for demo purpose) file and add one line in app.js file from previous example.

controller.js 

/* Define Filter */
var appFilter = angular.module('appFilter',[]).filter('checkmark',function(){
    return function(input){
        return input? '\u2713':'\u2718';
    };
});


app.js

var configModule = angular.module('configModule',[
    'ngRoute',
    'phoneDetailModule',
    'phoneListModule',
    'appFilter'
]);

configModule.config(['$routeProvider',function($routeProvider){
    $routeProvider.
        when('/phones',{
            templateUrl: 'Partials/PhoneDetail.html',
            controller: 'PhoneDetailController'
        }).
        when('/phones/:phoneId',{
            templateUrl: 'Partials/PhoneList.html',
            controller: 'PhoneListController'
        }).
        otherwise({
            redirectTo: '/phones'
        });
}]);

AngularJS: How to implement ngRoute

ngRoute is core part for angularjs library. Application can route through ngRoute and it's configure in Module configuration file.

Below is the best and simple implementation for ngRoute.

Index.html

<!doctype html>
<html ng-app="configModule">
<head>
    <title>My Angular App</title>


    <script src="JS\app.js"></script>
    <script src="JS\controller.js"></script>

</head>
<body>

<div ng-view></div>

</body>
</html>

app.js

var configModule = angular.module('configModule',[
    'ngRoute',
    'phoneDetailModule'
]);

configModule.config(['$routeProvider',function($routeProvider){
    $routeProvider.
        when('/phones',{
            templateUrl: 'Partials/PhoneDetail.html',
            controller: 'PhoneDetailController'
        }).
        when('/phones/:phoneId',{
            templateUrl: 'Partials/PhoneList.html',
            controller: 'PhoneListController'
        }).
        otherwise({
            redirectTo: '/phones'
        });
}])


controller.js


var phoneDetailModule = angular.module('phoneDetailModule',[]);
phoneDetailModule.controller('PhoneDetailController',['$scope','$http',function($scope,$http){
    $http.get('JS/phones.json').success(function(data){
         $scope.phones = data;
        });
    $scope.orderPro = 'age';
}]);
phoneDetailModule.controller('PhoneListController',['$scope','$routeParams',function($scope,$routeParams){
 $scope.phoneId = $routeParams.phoneId;
}]);


PhoneDetail.html

<div>
    Search : <input ng-model="query">
</div>
<div>
    <select ng-model="orderPro">
        <option value="name">Alphabetical</option>
        <option value="age">Newest</option>
    </select>
</div>
<ul>
    <li ng-repeat="phone in phones | filter:query | orderBy:orderPro">
        {{phone.name}}
        <p>
            {{phone.snippet}}
        </p>
        <img ng-src="{{phone.imageUrl}}" style="max-width: 50px" >

    </li>
</ul>


PhoneList.html

Detail view for <span>{{phoneId}}</span>

Wednesday, September 10, 2014

AngularJS: Minification Issue

If you think about minification for all function, It may break your functionality.  Below is best example for controller.

var appModule = angular.module('appModule',[]);

appModule.controller('appController', function ($scope, $http) {
    $http.get('js/phones.json').success(function(data){
            $scope.phones = data;
        }
    );
    $scope.orderPro = 'age';
});

Minification will convert your arguments in variable. Below are two different solutions for this problem.

Solution #1

appModule.controller('appController',['$scope','$http',function($scope,$http){
 $http.get('js/phones.json').success(function(data)
 {
     $scope.phones = data;
 });
    $scope.orderPro='age';
}]);


Solution #2

function appController($scope,$http){
    $http.get('js/phones.json').success(function(data){
        $scope.phones = data;
    });
    $scope.orderPro='age';
}
appController.$inject= ['$scope','$http'];
appModule.controller('appController',appController);

AngularJS: introduction to $http.get method

There is no change in HTML file as described in previous lesson.

JS File code:

var appModule = angular.module('appModule',[]);
appModule.controller('appController', function ($scope, $http) {
    $http.get('js/phones.json').success(function(data){
            $scope.phones = data;
        }
    );
    $scope.orderPro = 'age';

});

Phone.json:

[
    {"name":"iPhone","snippet":"Good Phone from json","age":1 },
    {"name":"Windows","snippet":"Above Average Phone from json","age":3 },
    {"name":"Android","snippet":"Average Phone from json","age":2 }
]


AngularJS: Getting Started

HTML File code:

<!doctype html>
<html ng-app="appModule">
<head>
    <title>My Angular App</title>
    <script src="JS\app.js"></script>

</head>
<body ng-controller="appController">
<div>
    Search : <input ng-model="query">
</div>
<div>
    <select ng-model="orderPro">
        <option value="name">Alphabetical</option>
        <option value="age">Newest</option>
    </select>
</div>
<ul>
    <li ng-repeat="phone in phones | filter:query | orderBy:orderPro">
        {{phone.name}}
        <p>
            {{phone.snippet}}
        </p>
    </li>
</ul>
</body>
</html>


JS File Code :


var appModule = angular.module('appModule',[]);

appModule.controller('appController',function($scope){

$scope.phones = [
    {'name':'iPhone','snippet':'Good Phone','age':1 },
    {'name':'Windows','snippet':'Above Average Phone','age':3 },
    {'name':'Android','snippet':'Average Phone','age':2 }
];
    $scope.orderPro = 'age';

});

Wednesday, September 3, 2014

SharePoint 2007 : How to get User Information in HTML

You can get user profile information in HTML page by querying below url and iterate through each element using jQuery.

{Web Application URL}/_layouts/userdisp.aspx?force=true

Friday, August 8, 2014

WCF Self Hosted Service using http Binding

Create Project based on WCF Service Library. This project will come with Service implementation by default as below

IService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFSelfHostingService
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}


Service.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFSelfHostingService
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in App.config.
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}



Create Console Application and replace code as below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using WCFSelfHostingService;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8080/MyService/Service1");

            ServiceHost host = new ServiceHost(typeof(Service1), baseAddress);

            host.AddServiceEndpoint(typeof(WCFSelfHostingService.IService1),
                                new WSHttpBinding(), baseAddress);
            host.Open();
            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();

            // Close the ServiceHost.
            host.Close();

        }
    }
}


Create Windows Form Application and add code as below in form load event

private IService1 channel = null;
var endPoint = new EndpointAddress("http://localhost:8080/MyService/Service1");
            channel = ChannelFactory<IService1>.CreateChannel(new NetTcpBinding(), endPoint);
            string temp = channel.GetData(10);


WCF Self Hosted Service using Net Tcp Binding

Create Project based on WCF Service Library. This project will come with Service implementation by default as below

IService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFSelfHostingService
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}


Service.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFSelfHostingService
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in App.config.
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}



Create Console Application and replace code as below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using WCFSelfHostingService;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("net.tcp://localhost:8080/MyService/Service1");

            ServiceHost host = new ServiceHost(typeof(Service1), baseAddress);

            host.AddServiceEndpoint(typeof(WCFSelfHostingService.IService1),
                                new NetTcpBinding(), baseAddress);
            host.Open();
            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();

            // Close the ServiceHost.
            host.Close();

        }
    }
}


Create Windows Form Application and add code as below in form load event

private IService1 channel = null;
var endPoint = new EndpointAddress("net.tcp://localhost:8080/MyService/Service1");
            channel = ChannelFactory<IService1>.CreateChannel(new NetTcpBinding(), endPoint);
            string temp = channel.GetData(10);

Thursday, August 7, 2014

JavaScript: Create an array with distinct random numbers with in a specified range

function getDistinctRandomIntForArray(array, range) { var n = Math.floor((Math.random() * range)); if (array.indexOf(n) == -1) { return n; } else { return getDistinctRandomIntForArray(array, range); } } function generateArrayOfRandomInts(count, range) { var array = []; for (i = 0; i < count; ++i) { array[i] = getDistinctRandomIntForArray(array, range); }; return array; }

Tuesday, June 10, 2014

SharePoint 2013: How to override user permission in SharePoint App

Each app has a manifest.xml file where the developer can define a list of resources that the app
needs access to using the AppPermissionRequests element. The following code snippet shows an
example of this element used in a provider-hosted app:

<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/sitecollection"
Right="Read"/>
Right="Write">
<Property Name="BaseTemplateId" Value="101"/>
</AppPermissionRequest>
<AppPermissionRequest Scope="http://sharepoint/userprofilestore/feed"
Right="Post"/>
<AppPermissionRequest Scope="http://exchange/calendars" Right="Schedule"/>
</AppPermissionRequests>

Note the highlighted line in the code snippet. The app permission requests enable the app-only
policy, which means that only the app, and not the current user, requires the needed permissions. If
an app-only policy is not used, both the app and the current user require the necessary permissions
to complete a task such as accessing the entire site collection or writing to a list. The result would be
a context that contains both the app and the user identities.

Friday, May 23, 2014

SharePoint 2013: Organization App using Google Chart plugin

This example will get records from SharePoint List and display as chart for people organization.


Create Project using SharePoint App template.

Replace Default.aspx code as below

<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>

<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>

<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>

    <!-- Add your CSS styles to the following file -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />

    <!-- Add your JavaScript to the following file -->

    <script type='text/javascript' src='https://www.google.com/jsapi'></script>
    <script type="text/javascript" src="../Scripts/App.js"></script>
    <script type='text/javascript'>

   </script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Organization Chart
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">

    <div>
        <p id="message">
            <!-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        </p>
    </div>

    <div id='chart_div'></div>
    <div id='Div1'></div>       
</asp:Content>


Replace App.js code by below code :

'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var collList;
var clientContext;
var oWeb;
var oLists;
var oList;
var oListItems;
var oItems = "";
var hostweburl;
var appweburl;

hostweburl = getQueryStringParameter("SPHostUrl");
appweburl = getQueryStringParameter("SPAppWebUrl");
hostweburl = decodeURIComponent(hostweburl);
appweburl = decodeURIComponent(appweburl);

getUserName();
//retrieveListItems();

function drawChart() {
   
}

function retrieveListItems() {
    //clientContext = new SP.ClientContext.get_current();
    var appContextSite = new SP.AppContextSite(
    context,
    hostweburl
);
    //oWeb = appContextSite.get_web();
    oList = appContextSite.get_web().get_lists().getByTitle('OrgChart');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(
        '<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
        '<Value Type=\'Number\'>1</Value></Geq></Where></Query>' +
        '<RowLimit>25</RowLimit></View>'
    );
    oListItems = oList.getItems(camlQuery);
    context.load(oListItems);
    context.executeQueryAsync(
        Function.createDelegate(this, onListSuceeded),
        Function.createDelegate(this, onListFailed)
        );
}
function onListSuceeded(sender, args) {
    //    alert("onListSuceeded");
    var EnumerateListItems = oListItems.getEnumerator();
    oItems = "data.addRows([ ";
    while (EnumerateListItems.moveNext()) {
        var oListItem = EnumerateListItems.get_current();
        var Name = oListItem.get_item('Name');
        var userName = "";
        if (Name != null)
            userName = Name.get_lookupValue();

        var ManagerName = oListItem.get_item('ManagerName');
        var managerName = "";
        if (ManagerName != null)
            managerName = ManagerName.get_lookupValue();

        oItems += "['" + userName + "','" + managerName + "',''],";
    }
    oItems = oItems.substring(0, oItems.length - 1);
    oItems += " ]);";
    //alert("from inside function " + oItems);
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Name');
    data.addColumn('string', 'Manager');
    data.addColumn('string', 'ToolTip');
    eval(oItems);
    var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
    chart.draw(data, { allowHtml: true });
    //$("#Div1").text(oItems);
}
function onListFailed(sender, args) {
    alert("onListFailed");
}
function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}
// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    //$('#message').text('Hello ' + user.get_title());
    $('#message').text('Hello Rakesh Patel');
}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}
google.load('visualization', '1', { packages: ['orgchart'] });
google.setOnLoadCallback(retrieveListItems);



Create List as per the attachment.