Wednesday 18 December 2013

SharePoint Get Specific Folder List Items

You can also check whether item is folder or list item using "FileSystemObjectType"

var context = SP.ClientContext.get_current();
var web = context.get_web();

//doc is a document library server relative url
var folder = web.getFolderByServerRelativeUrl("Documents/Wildlife");

//var parentFolder = folder.get_parentFolder();
//context.load(parentFolder);

context.load(folder);
context. executeQueryAsync(function(){

var query = new SP.CamlQuery();
query.set_folderServerRelativeUrl(folder.get_serverRelativeUrl());
var allItems = list.getItems(query);
context.load(allItems, "Include(Title, FileSystemObjectType, File)");

context.executeQueryAsync(function(){
debugger;
var itemsEnumerator = allItems.getEnumerator();
while(itemsEnumerator.moveNext()){
var item = itemsEnumerator.get_current();
var fileType = item.get_fileSystemObjectType();
//get the detailed information

 var title = item.get_item("Title")

}
}, function(sender, args){debugger;});

}, function(sender, args){debugger;});
Read More

Thursday 12 December 2013

SharePoint Upload File to Document Library using Client Side Object Model

"use strict";

var JJ = window.JJ || {};
JJ.Jsom = JJ.Jsom || {};

JJ.Jsom.Libs = function () {

    var deferreds = new Array(),

    upload = function (library, filename, file) {
        deferreds[deferreds.length] = $.Deferred();
debugger;
        getFileBuffer(file).then(
            function (buffer) {
                var bytes = new Uint8Array(buffer);
                var content = new SP.Base64EncodedByteArray(); //base64 encoding
                for (var b = 0; b < bytes.length; b++) {
                    content.append(bytes[b]);
                }
                var ctx = new SP.ClientContext.get_current();

var oList = ctx.get_web().get_lists().getByTitle(library);

fileCreateInfo = new SP.FileCreationInformation();
fileCreateInfo.set_url(filename);
fileCreateInfo.set_content(content);
fileCreateInfo.set_overwrite(true);
               
this.newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);

ctx.load(this.newFile);
ctx.executeQueryAsync(
Function.createDelegate(this, function(){alert('Done');}),
Function.createDelegate(this, function(){alert(arguments[1].get_message());})
);

            },
            function (err) {
                deferreds[deferreds.length - 1].reject(err);
            }
         );

        return deferreds[deferreds.length - 1].promise();

    },

    getFileBuffer = function (file) {
        var deferred = $.Deferred();
var reader = new FileReader();
reader.onload = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(file);
return deferred.promise();
    };

    return {
        upload: upload,
    };

}();

$(document).ready(function(){
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){});
$("#s4-bodyContainer").prepend('<input id="inputFile" type="file" /><input id="uploadDocumentButton" type="Button" value="Upload Document"/>');

$("#uploadDocumentButton").unbind('click').click(function () {
debugger;
if (document.getElementById("inputFile").files.length === 0) {
alert("Select a file!");
return;
}

var parts = document.getElementById("inputFile").value.split("\\");
var filename = parts[parts.length - 1];
var file = document.getElementById("inputFile").files[0];

JJ.Jsom.Libs.upload("Documents", filename, file);
});
});

Read More

Monday 9 December 2013

SharePoint Get List AttachMents

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
debugger;
 var ctx=new SP.ClientContext("http://nit-hv5-idm2:11111/sites/hr/referral");
  var list = ctx.get_web().get_lists().getByTitle("Job Opening");
 var query = new SP.CamlQuery();
     query.set_viewXml('');
 var listFields = list.getItems(query);
 ctx.load(listFields);
ctx.executeQueryAsync(Function.createDelegate(this, function(sender,args){
debugger;var i=0;
   var listEnumerator = listFields.getEnumerator();
  while (listEnumerator.moveNext()) {
if(i++ == 0){
    var oField = listEnumerator.get_current();
    var attachments = oField.get_attachmentFiles();
    ctx.load(attachments);

ctx.executeQueryAsync(Function.createDelegate(this, function(sender, args){
debugger;
var enums = attachments.getEnumerator();
while (enums.moveNext()) {
var attacha = enums.get_current();
console.log(attacha.get_serverRelativeUrl());
}
 
console.log(attachments);
 

}), Function.createDelegate(this, function(){}));  

}
 }
}), Function.createDelegate(this, function(){}));
});

Read More

Monday 14 October 2013

SAS Scan Equivalent Implementation in SQL using CHARINDEX

//SQL SERVER
CREATE TABLE A 
(
     Name varchar(40) 
    );

INSERT INTO A
(Name)
VALUES
('1-nikhil-s-a--sada'),
('55--sunil-s-a--sada'),
('-2--asd-ww');


CHARINDEX(charachter, field)
SUBSTRING(field, tart position, length upto)

//To get 1st
CHARINDEX('-', Name)

//TO get 2nd
SELECT       CHARINDEX('-', Name, CHARINDEX('-', Name) + 1) 
from A

//TO GEt 3rd
SELECT  CHARINDEX('-', Name, CHARINDEX('-', Name, CHARINDEX('-', Name) + 1) + 1) 
from A

//TO GEt 4th
SELECT  CHARINDEX('-', Name, CHARINDEX('-', Name, CHARINDEX('-', Name, CHARINDEX('-', Name) + 1) + 1) + 1)
from A

//Length 3-2
SELECT  (CHARINDEX('-', Name, CHARINDEX('-', Name, CHARINDEX('-', Name) + 1) + 1)-CHARINDEX('-', Name, CHARINDEX('-', Name) + 1)) -1
from A

//Length 4-3
SELECT (CHARINDEX('-', Name, CHARINDEX('-', Name, CHARINDEX('-', Name, CHARINDEX('-', Name) + 1) + 1) + 1) - CHARINDEX('-', Name, CHARINDEX('-', Name, CHARINDEX('-', Name) + 1) + 1) ) -1 
from A

//To get string between 2 and 3rd '-'
select substring(Name,CHARINDEX('-', Name, CHARINDEX('-', Name) + 1)+1,(CHARINDEX('-', Name, CHARINDEX('-', Name, CHARINDEX('-', Name) + 1) + 1)-CHARINDEX('-', Name, CHARINDEX('-', Name) + 1)) -1)
from A

//To get string between 3 and 4th '-'
select substring(Name,CHARINDEX('-', Name, CHARINDEX('-', Name, CHARINDEX('-', Name) + 1) + 1)  +1 , (CHARINDEX('-', Name, CHARINDEX('-', Name, CHARINDEX('-', Name, CHARINDEX('-', Name) + 1) + 1) + 1) - CHARINDEX('-', Name, CHARINDEX('-', Name, CHARINDEX('-', Name) + 1) + 1) ) -1 )
from A

Read More

Wednesday 25 September 2013

SharePoint CSOM Javascript Custom Employee SpotLight WebPart

<div class="carousel-wrapper">
  <div class="carousel-title">Know Your Friend</div>
  <div class="emp-carousel">
    <ul id="SpotlightContainer" class="bjqs">
      <!--<li> <img src="images/img1.jpg" />
        <div class="text">
          <h3>Maria Goretti</h3>
          <h5>(Marketing Lead)</h5>
          <p> It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum </p>
        </div>
        <a href="#" class="knowmore">Know more</a> </li>-->
     
    </ul>
  </div>
</div>

<script type="text/javascript" src="_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/SP.UserProfiles.js" ></script>
<script src="/js/carousel.min.js"></script>
<link rel="stylesheet" href="/css/carousel.css">
<script type="text/javascript">

var profilePropertyNames = ["PreferredName", "PictureURL", "FirstName", "Designation"];
var Spot={
ctx: null,
listname: 'Spotlight',
listitems:'',
spotUsers:[],
userProperties: [],
finalData: [],
Spot: function () {
        //SP.SOD.executeFunc('sp.js', 'SP.ClientContext', Spot.load);
        Spot.Load();//write this line in main js load method
        Spot.ctx.executeQueryAsync(Function.createDelegate(this, function(){
Spot.onLoad();//write this line in main js onLoad method
}),
Function.createDelegate(this, Spot.QueryFailed ));
     
    },
    Load:function(){
   Spot.ctx = new SP.ClientContext.get_current();
   var list = Spot.ctx.get_web().get_lists().getByTitle(Spot.listname);
var query = new SP.CamlQuery();
   query.set_viewXml('');
Spot.listitems= list.getItems(query);
Spot.ctx.load(Spot.listitems);
   },
    onLoad:function(){
    var listEnumerator, title, userId, userName, loginName, pictureUrl, users=[], i=0, spotdescription, data=[];
    listEnumerator = Spot.listitems.getEnumerator();
while (listEnumerator.moveNext()) {
title = listEnumerator.get_current().get_item("Title");
userId= listEnumerator.get_current().get_item("UserName").get_lookupId();
spotdescription = listEnumerator.get_current().get_item("Description");
data.push({
        'userId': userId,
        'title': title,
        'spotdescription': spotdescription
       });
users[i] = Spot.ctx.get_web().getUserById(userId);
   Spot.ctx.load(users[i++]);
}//End while

/**/  Spot.ctx.executeQueryAsync(Function.createDelegate(this, function(){
      for( i=0; i < users.length;i++){
       console.log(users[i].get_loginName().split('|')[1]);
       console.log(users[i].get_id());
       Spot.spotUsers.push({
        'userId': users[i].get_id(),
        'userName': users[i].get_loginName().split('|')[1],
        'title': data[i].title,
        'spotdescription': data[i].spotdescription
       });
      }
   
      Spot.GetAllUserProperties();

/**/  }), Function.createDelegate(this, this.onFail));

    },
    QueryFailed : function(sender, args){
alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
},
GetAllUserProperties:function(){
var peopleManager = new SP.UserProfiles.PeopleManager(Spot.ctx);
for(var i=0 ; i < Spot.spotUsers.length ; i++){
     Spot.GetUserProperties(Spot.ctx, peopleManager, Spot.spotUsers[i].userId, Spot.spotUsers[i].userName, profilePropertyNames);
}
},
GetUserProperties:function(clientContext, peopleManager, userId, targetUser, profilePropertyNames){
var userProfilePropertiesForUser = new SP.UserProfiles.UserProfilePropertiesForUser(
 clientContext,
 targetUser,
 profilePropertyNames);
var userProfileProps = peopleManager.getUserProfilePropertiesFor(userProfilePropertiesForUser);
Spot.ctx.load(userProfilePropertiesForUser);
Spot.ctx.executeQueryAsync(
  function () {
  var jsonContent=[], jsonData = '{[';
  for(var j=0; j< profilePropertyNames.length; j++){
  var data='{"' + profilePropertyNames[j] + '":"' + userProfileProps[j] + '"}' ;
  jsonContent.push(data);
  }
  if(profilePropertyNames.length){
  Spot.userProperties.push({ 'userId': userId, 'prop': jsonContent });
  }
 
  Spot.SyncData();
},
  function () { Spot.QueryFailed });
},

SyncData: function(){
var users = Spot.spotUsers,
props = Spot.userProperties,
sync = [];
$.grep(users, function( a ) {

       $.grep(props, function( b ) {

if(a.userId == b.userId){
sync.push({ 'userId': a.userId, 'title' : a.title,'spotdescription':a.spotdescription, 'prop': b.prop });
}

});

});

Spot.finalData = sync;
Spot.BindToHTML();
},

BindToHTML: function(){
var html='', imgUrl, userName, desig, desc, spotdescription, title, props=[];

$.grep(Spot.finalData, function( p ) {
props=[];
for(var i=0; i< p.prop.length; i++){
props.push($.parseJSON(p.prop[i]));
}
imgUrl = props[1].PictureURL;
userName = props[0].PreferredName;
desig = props[3].Designation;
spotdescription = p.spotdescription;
desc = 'Temp Desc';
summary = 'Temp Summary';
title = p.title;

html += '<li><img src="'+ imgUrl +'" />' +
        '<div class="text">' +
          '<h3>' + userName + '</h3>' +
          '<h5>(' + desig + ')</h5>' +
          '<p>' + spotdescription + '</p>' +
        '</div>' +
        '<a href="' + spotdescription + '" class="knowmore">Know more</a>' +
       '</li>';
});
$('#SpotlightContainer').html(html);

$('.emp-carousel').bjqs({
animtype      : 'fade',
responsive    : false,
randomstart   : false
});

}
};

</script>
Read More

Monday 23 September 2013

Get Multiple User's Multiple User Profile properties using CSOM

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
var ctx=new SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle("Spotlight Employee");
var query = new SP.CamlQuery();
query.set_viewXml('');
this.listitems=list.getItems(query);
ctx.load(listitems);

ctx.executeQueryAsync(Function.createDelegate(this, function(){
   var listEnumerator = listitems.getEnumerator();
var ids=[], users=[], user, i=0;
while (listEnumerator.moveNext()) {
var oField = listEnumerator.get_current();
var id = oField.get_item("UserName").get_lookupId();
users[i] = ctx.get_web().getUserById(id);
ctx.load(users[i++]);
}//End while

ctx.executeQueryAsync(Function.createDelegate(this, function(){
for( i=0; i < users.length;i++){
console.log(users[i].get_loginName());
                                                                console.log(users[i].get_title());
}

}), Function.createDelegate(this, this.onFail));

}), Function.createDelegate(this, this.onFail));

});
Read More

Friday 20 September 2013

Get Multiple User Properties in SharePoint 2013

var users=["domain\\kalpeshp", "domain\\sachinka", "domain\\nikhils"];

function GetUserProperties(clientContext, peopleManager, targetUser, profilePropertyNames){
 var userProfilePropertiesForUser = new SP.UserProfiles.UserProfilePropertiesForUser(
  clientContext,
  targetUser,
  profilePropertyNames);
 var userProfileProps = peopleManager.getUserProfilePropertiesFor(userProfilePropertiesForUser);

 clientContext.load(userProfilePropertiesForUser);
 clientContext.executeQueryAsync(
  function () { console.log(userProfileProps[0] + " works in " + userProfileProps[1] + " as a " + userProfileProps[2]); },
  function () { console.log("Failure") });
 }


function GetAllUserProperties(){
 var targetUser = "domain\\kalpeshp";

 // Create the client context and get the PeopleManager instance.
 var clientContext = new SP.ClientContext.get_current();
 var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);

 // Get user profile properties for the target user.
 // Specify the properties to retrieve and create the UserProfilePropertiesForUser object.
 // Then get the requested properties by using the getUserProfilePropertiesFor method.
 var profilePropertyNames = ["PreferredName", "Department", "Title"];

 for(var i=0; i<users.length;i++){
     GetUserProperties(clientContext, peopleManager, users[i], profilePropertyNames);
 }
}
Read More

SharePoint 2013 Working with User Profiles & JavaScript CSOM

SharePoint 2013 has added a variety of functionality to the Client API. One of them is the ability to fetch User Profile data. Now you can directly query the user profiles and get the required data from the client site. This can be really useful if you are building apps.

If you want to use the REST API to work with user profiles, MSDN has a decent documentation on it here:
http://msdn.microsoft.com/en-us/library/jj163800.aspx
In this post, I will show you how to work with User Profiles using the JavaScript Client Object Model

Before we get started with the code, lets make couple of things sure. First,  you will need a reference to the following JavaScript files in your page:

1234
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
<script src="/_layouts/15/SP.Runtime.js"></script>
<script src="/_layouts/15/SP.js"></script>
<script src="/_layouts/15/SP.UserProfiles.js"></script>
view rawupScripts.html hosted with ❤ by GitHub

(jQuery is not required but I have added it because we will need it for the $.ajax function when doing REST queries)

Second thing, you will need the domain\username of the user you want to get the user profile data for. This can be easy to get if you are in an On-Prem environment. But if you are working with SharePoint Online, this can be quite tricky. Your username might not always be in the domain\username format. It is stored in the LoginName property if you are querying the Site User Information List:

https://yoursite.sharepoint.com/sites/pubsite/_api/Web/GetUserById(17)

and it is stored in the AccountName property if your querying the User Profile Service:

https://yoursite.sharepoint.com/sites/pubsite/_api/SP.UserProfiles.PeopleManager/GetMyProperties

In SharePoint Online, it will most probably be in the following format:


i:0#.f|membership|vardhaman@yoursite.onmicrosoft.com


Quick Note: If you are using the REST API, you will need to encode the username before you use it in your call. The encodeURIComponent( ) function can be helpful here.

Enough talking. Lets jump into some code right away:


1) Get Multiple User Profile Properties:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
(function($){
 
$(document).ready(function(){
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');
});
var userProfileProperties = [];
function loadUserData(){
//Get Current Context
var clientContext = new SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Properties to fetch from the User Profile
var profilePropertyNames = ["PreferredName","PictureURL"];
//Domain\Username of the user (If you are on SharePoint Online)
var targetUser = "i:0#.f|membership|vardhaman@yoursite.onmicrosoft.com";
//If you are on On-Premise:
//var targetUser = domain\\username
//Create new instance of UserProfilePropertiesForUser
var userProfilePropertiesForUser = new SP.UserProfiles.UserProfilePropertiesForUser(clientContext, targetUser, profilePropertyNames);
userProfileProperties = peopleManager.getUserProfilePropertiesFor(userProfilePropertiesForUser);
//Execute the Query.
clientContext.load(userProfilePropertiesForUser);
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
var messageText = "\"Preffered Name\" property is " + userProfileProperties[0];
messageText += "\"PictureURL\" property is " + userProfileProperties[1];
alert(messageText);
}
function onFail(sender, args) {
alert("Error: " + args.get_message());
}
})(jQuery);
view rawupMult.js hosted with ❤ by GitHub


2) Get Single User Profile Property:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
(function($){
 
$(document).ready(function(){
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');
});
var userProfileProperty;
function loadUserData(){
//Get Current Context
var clientContext = new SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Property to fetch from the User Profile
var propertyName = "PreferredName";
//Domain\Username of the user (If you are on SharePoint Online)
var targetUser = "i:0#.f|membership|vardhaman@yoursite.onmicrosoft.com";
//If you are on On-Premise:
//var targetUser = domain\\username
//Create new instance of UserProfileProperty
userProfileProperty = peopleManager.getUserProfilePropertyFor(targetUser, propertyName)
//Execute the Query. (No load method necessary)
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
var messageText = "\"Preferred Name\" property is " + userProfileProperty.get_value();
alert(messageText);
}
function onFail(sender, args) {
alert("Error: " + args.get_message());
}
})(jQuery);
view rawupsing.js hosted with ❤ by GitHub


3) Get User Profile Properties of the Current User:

1234567891011121314151617181920212223242526272829303132333435363738
(function($){
$(document).ready(function(){
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');
});
var userProfileProperties;
function loadUserData(){
//Get Current Context
var clientContext = new SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Get properties of the current user
userProfileProperties = peopleManager.getMyProperties()
clientContext.load(userProfileProperties);
//Execute the Query.
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
alert(userProfileProperties.get_displayName());
}
function onFail(sender, args) {
alert("Error: " + args.get_message());
}
})(jQuery);
view rawsp15_up_current.js hosted with ❤ by GitHub


4) Get Properties of Multiple Users in Single Request:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
(function($){
 
$(document).ready(function(){
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');
});
 
var userProfileProperties = [];
//Array containing domain\usernames of multiple users. You can get the usersnames any way you want.
var targerUsers = ["i:0#.f|membership|vardhaman@yoursite.onmicrosoft.com","i:0#.f|membership|demouser1@yoursite.onmicrosoft.com"];
//If you are on On-Premise:
//var targerUsers = ["domain\\username","domain\\demouser1"];
function loadUserData(){
//Get Current Context
var clientContext = new SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Property to fetch from the User Profile
var propertyName = "PreferredName";
for(var i=0;i<targerUsers.length;i++){
//Create new instance of UserProfileProperty
userProfileProperties[i] = peopleManager.getUserProfilePropertyFor(targerUsers[i], propertyName);
}
//Execute the Query. (No load method necessary)
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
var messageText = "";
for(var i=0;i<userProfileProperties.length;i++){
messageText += "\"Preffered Name\" property is " + userProfileProperties[i].get_value();
}
alert(messageText);
}
function onFail(sender, args) {
alert("Error: " + args.get_message());
}
 
})(jQuery);
view rawuponecall.js hosted with ❤ by GitHub


For this last example, Let's observe the XML which is sent to the server:

1234567891011121314151617181920
<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="15.0.0.0" ApplicationName="Javascript Library">
<Actions>
<ObjectPath Id="1" ObjectPathId="0"></ObjectPath>
<Method Name="GetUserProfilePropertyFor" Id="2" ObjectPathId="0">
<Parameters>
<Parameter Type="String">i:0#.f|membership|vardhaman@yoursite.onmicrosoft.com</Parameter>
<Parameter Type="String">PreferredName</Parameter>
</Parameters>
</Method>
<Method Name="GetUserProfilePropertyFor" Id="3" ObjectPathId="0">
<Parameters>
<Parameter Type="String">i:0#.f|membership|demouser1@yoursite.onmicrosoft.com</Parameter>
<Parameter Type="String">PreferredName</Parameter>
</Parameters>
</Method>
</Actions>
<ObjectPaths>
<Constructor Id="0" TypeId="{cf560d69-0fdb-4489-a216-b6b47adf8ef8}"></Constructor>
</ObjectPaths>
</Request>
view rawup.xml hosted with ❤ by GitHub


With this, we can confirm that only one call was made to the server to retrieve the properties of multiple users. This way, you can even retrieve multiple properties of multiple users in one call.
Read More

Translate

Total Pageviews

Powered By Blogger · Designed By Seo Blogger Templates