Saturday, November 21, 2015

Client-side People Picker control for Sharepoint

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);
})

function sharePointReady() {
    context = new SP.ClientContext.get_current();
    web = context.get_web();
    getUser().done(function (user) {
        var schema = {};
        schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
        schema['SearchPrincipalSource'] = 15;
        schema['ResolvePrincipalSource'] = 15;
        schema['AllowMultipleValues'] = false;
        schema['MaximumEntitySuggestions'] = 50;
        schema['Width'] = '280px';

        var users = new Array(1);
        var defaultUser = new Object();
        defaultUser.AutoFillDisplayText = user.get_title();
        defaultUser.AutoFillKey = user.get_loginName();
        defaultUser.Description = user.get_email();
        defaultUser.DisplayText = user.get_title();
        defaultUser.EntityType = "User";
        defaultUser.IsResolved = true;
        defaultUser.Key = user.get_loginName();
        defaultUser.Resolved = true;
        users[0] = defaultUser;
        SPClientPeoplePicker_InitStandaloneControlWrapper('peoplePickerDiv', users, schema);
    });
}

function getUser() {
    var dfd = $.Deferred(function () {
        user = web.get_currentUser();
        context.load(user);
        context.executeQueryAsync(
            function () {
                dfd.resolve(user);
            }),
            function () {
                dfd.reject(args.get_message());
            };
    });
    return dfd.promise();
}

Thursday, November 12, 2015

JSLink Urls

JSLink URLs and Tokens
When you are constructing your JSLink URL there are a number of tokens you can take advantage of:
  • ~site – reference to the current SharePoint site (or “Web”)
  • ~sitecollection – reference to the current SharePoint site collection (or “Site”)
  • ~layouts – version specific reference to the web application Layouts folder (so it will automatically swap out /_layouts/14 or /_layouts/15 for you)
  • ~sitecollectionlayouts – reference to the layouts folder in the current site collection (e.g. /sites/team/_layouts/15)
  • ~sitelayouts – reference to the layouts folder in the current site (e.g. /sites/teams/subsite/_layouts/15)

Friday, November 6, 2015

Export to Excel using javascript

http://www.c-sharpcorner.com/UploadFile/65794e/export-from-html-table-using-jquery/

Thursday, November 5, 2015

How to get spfielduser value in REST call ?


use below kind of query to get the SPFieldUserValue in REST based call

url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/Items?$select=Title,EmployeePhone,LeaveCategory,EmployeeLocation,EmployeeName/Title&$expand=EmployeeName&$filter="+ restQuery,

Monday, November 2, 2015

CRUD Operations using JSOM

Add :- 

function Add() {
    var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle('List1');//Get SPList by Title
    var itemCreateInfo = new SP.ListItemCreationInformation();

    var oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', 'Value'); //Title is the field and Value is the value for field
    oListItem.update();

    clientContext.load(oListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));

    //Function when the execution of the query successed
    function onQuerySucceeded(sender, args) {
        alert('Data ADDED successfully');
    };
    //Function to run when the execution falis
    function onQueryFailed(sender, args) {
        alert('Cannot ADD');
    };

};

Update :- 
function Update() {
    var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle('List1');//Get SPList by Title

    var oListItem = oList.getItemById(1);//Get the list item by id
    oListItem.set_item('Title', 'New Value');
    oListItem.update();
    clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));

    //Function when the execution of the query successed
    function onQuerySucceeded(sender, args) {
        alert('Data UPDATED successfully');
    };
    //Function to run when the execution falis
    function onQueryFailed(sender, args) {
        alert('Cannot UPDATE');
    };
};

Delete :-

function Delete() {
    var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle('List1');//Get SPList by Title

    var oListItem = oList.getItemById(1);//Get the list item by id
   oListItem.deleteObject();
    clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));

    //Function when the execution of the query successed
    function onQuerySucceeded(sender, args) {
        alert('Data DELETED successfully');
    };
    //Function to run when the execution falis
    function onQueryFailed(sender, args) {
        alert('Cannot DELETE');
    };
};

Monday, October 5, 2015

Get Field values using CSOM

Using the Javascript Client Object Model, you can get values from a listitem. 

How to use the JSOM is described here Code Project

Title – SP.ListItem.get_item(‘Title‘);

ID – SP.ListItem.get_id();

Url -SP.ListItem.get_item(‘urlfieldname‘).get_url()

Description – SP.ListItem.get_item(‘descriptionfieldname‘).get_description();

Current Version – SP.ListItem.get_item(“_UIVersionString“);

Lookup field – SP.ListItem.get_item(‘LookupFieldName’).get_lookupValue(); // or get_lookupID();

Created By – SP.ListItem.get_item(“Author“).get_lookupValue();

Modified by – SP.ListItem.get_item(“Editor“).get_lookupValue();

Choice Field – SP.ListItem.get_item(‘ChoiceFieldName‘);

Created Date – SP.ListItem.get_item(“Created“);

Modified Date – SP.ListItem.get_item(“Modified“); -> case sensitive does not work with ‘modified’

File  – SP.ListItem.get_file();

File Versions -  File.get_versions();.

Content Type – SP.ListItem.get_contentType();

Parent List – SP.ListItem.get_parentList();

Note:  (‘LookupFieldName’).get_lookupValue() sometimes returns an array of data, especially when your lookup allows multiple values.
In that case you will need to iterate the array and get each value individually.

 SP.ListItem.get_item(‘LookupFieldName’)[0].get_lookupValue(); - this will get the first item in the array.

For Arrays:


       for(var i = 0; i < oListItem.get_item("LookupFieldName").length; i++)
 {
      alert(oListItem.get_item("LookupFieldName")[i].get_lookupId()); // or get_lookupValue()
 } 

Wednesday, September 30, 2015

Angular js lectures

One of the best video tutorials i have ever seen for angulat js

http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/1/section/1/video/1

CSOM code to fetch the property bag value

You can add the property to web property bag from designer.


Below is the code that you can use to get the added property

ExecuteOrDelayUntilScriptLoaded(getWebProperties, "sp.js");

var webProperties;

function getWebProperties() {
    var clientContext = new SP.ClientContext.get_current();
    webProperties = clientContext.get_web().get_allProperties();
    clientContext.load(webProperties);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.getWebPropertiesSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function getWebPropertiesSucceeded() {

          //debugger; //use this to force a break here
    //returns an object with all properties.  
          //Use the quick watch to expand this out to see all of them.
    var allProps = webProperties.get_fieldValues();

    var customProp = "";

         //make sure the property is there before using it.
    if(webProperties.get_fieldValues().YammerAccessToken != undefined)
    {
        var customProp = webProperties.get_fieldValues().YammerAccessToken;
    }
    alert(customProp);
}

function onQueryFailed(args, sender)
{

     //handle errors here
 alert("Error : " + args.get_message());
}
getWebProperties();

Monday, August 24, 2015

KQL or FQL does not contain starts with query

Sharepoint search query KQL does not support StartsWith in sharepoint. So to achieve it, you will have get the results using name:word* and change the result set to show actual data based on javascript etc..

Monday, August 10, 2015

After and Before Properties in Sharepoint Event receivers

Below are the list of differences in Item Properties
List
ListBeforePropertiesAfterPropertiesproperties.ListItem
ItemAddingNo valueNew valueNull
ItemAddedNo valueNew valueNew value
ItemUpdatingOriginal valueNew valueOriginal value
ItemUpdatedOriginal valueNew valueNew value
ItemDeletingNo valueNo valueOriginal value
ItemDeletedNo valueNo valueNull
Document Library
LibraryBeforePropertiesAfterPropertiesproperties.ListItem
ItemAddingNo valueNo valueNull
ItemAddedNo valueNo valueNew value
ItemUpdatingOriginal valueNew valueOriginal value
ItemUpdatedOriginal valueNew valueNew value
ItemDeletingNo valueNo valueOriginal value
ItemDeletedNo valueNo valueNull
It will help somebody for sure.

Wednesday, April 29, 2015

How to use SPSiteDataQuery in sharepoint

Below is the example how we can use spsitedataquery in sharepoint

using (SPSite site = new SPSite(ServerText.Text))
{
    using (SPWeb web = site.OpenWeb())
    {
        // Fetch using SPSiteDataQuery
        SPSiteDataQuery query = new SPSiteDataQuery();
        query.Lists = "<Lists ServerTemplate=\"105\" />";
        query.ViewFields = "<FieldRef Name=\"Title\" />" +  /* Title is LastName column */
                "<FieldRef Name=\"FirstName\" Nullable=\"TRUE\" Type=\"Text\"/>";
        query.Webs = "<Webs Scope=\"SiteCollection\" />";

        DataTable dataTable = web.GetSiteData(query);
        dataGridView3.DataSource = dataTable;
    }
}

Thursday, April 9, 2015

SharePoint URL Shortcuts

Sandboxed Solution Gallery:
/_catalogs/solutions/Forms/AllItems.aspx

Workflow history hidden list:
/lists/Workflow History

Filter toolbar for Lists and libraries (Added by Asimaili):
?Filter=1

Site usage page (Added by @Dnyag):
/_layouts/usage.aspx

Site content and structure  page (Added by @Dnyag):
/_layouts/sitemanger.aspx

Site settings page (Added by Aowworld):
/_layouts/settings.aspx

View all site content page (Site content) (Added by Aowworld):
/_layouts/viewlsts.aspx

Manage site collection features - CASE SENSITIVE 
/_layouts/ManageFeatures.aspx?Scope=Site

Manage site features :
/_layouts/ManageFeatures.aspx

 Get the version of the SharePoint server (Patch level) :
 /_vti_pvt/Service.cnf

Web Part Maintenance Page :
?Contents=1

Show Page in Dialog View :
?isdlg=1

Application page for registering SharePoint apps :
/_layouts/15/appregnew.aspx

Save Site as a template : 
/_layouts/savetmpl.aspx

Sign in as a different user :
/_layouts/closeConnection.aspx?loginasanotheruser=true

Enable SharePoint designer :
/_layouts/SharePointDesignerSettings.aspx

Welcome Page (Default page settings) :
/_layouts/AreaWelcomePage.aspx

Change Site Master Page :
/_layouts/ChangeSiteMasterPage.aspx

Page Layouts and Site Templates :
/_Layouts/AreaTemplateSettings.aspx

Master Pages library :
/_catalogs/masterpage/Forms/AllItems.aspx

User Information List :
_catalogs/users/simple.aspx

Quick Deploy List :
Quick%20Deploy%20Items/AllItems.aspx

Open Page in Edit Mode :
?ToolPaneView=2

Taxonomy Hidden List (MMS) :
Lists/TaxonomyHiddenList/AllItems.aspx

User Information List :
_catalogs/users/simple.aspx

Force displaying the user profile in the site collection :
/_layouts/userdisp.aspx?id={UserID}&Force=True

View size of all lists and libraries :
/_layouts/storeman.aspx

Wednesday, April 1, 2015

how to get the current ui culture using CSOM

use the below line of code to get the current UI culture

_spPageContextInfo.currentCultureName

Tuesday, March 31, 2015

Trick to know the loaded Jquery file version

Ever wanted to check the version of the jquery file...

try this simple trick..
open console window of the broweser
paste jQuery.fn.jquery and hit enter.


Thursday, March 26, 2015

Why SPServices?

The Client Object Model only works in SharePoint 2010 and does not work for anonymous users. SPServices works the same in both SharePoint 2007 and 2010 and works just fine with anonymous users as long as anonymous users have access to the pages and the scripts. As far as just calling the Web Services directly? Well, that’s basically what SPServices does except it takes care of the heavy lifting for you and wraps the Web Service methods in easy to use functions. So, if you prefer to manually write SOAP envelopes and all that fun stuff, have at it.