Commands

Add and Retrieve property bag by CSOM

My Share Points

This blog will tell you how to add and retrieve web property bag through SharePoint CSOM.

I tried use Add method to insert a new property; however, it does not really add the new property.

Add Property

private int SetProperty(ClientContext clientContext, int flag)
{
  Web web = clientContext.Site.RootWeb;
  /* Add successfully, but not persistantly. Cannot find this new property when retrieve property bag  clientContext.Load(web, w=>web.AppProperties);
  clientContext.ExecuteQuery();

  if (!web.AllProperties.FieldValues.ContainsKey("Customized"))
  {
     web.AllProperties.FieldValues.Add("Customized", flag);
  }
  else
  {
     web.AllProperties["Customized"] = flag;
  }
  */// Correct Approach
  var allProperties = web.AllProperties;
  allProperties["CIBCCustomized"] = flag;

  web.Update();
  clientContext.ExecuteQuery();

  return flag;
}

Retrieve Property

private int GetFlag(ClientContext clientContext)
{
  Web web = clientContext.Site.RootWeb;
  clientContext.Load(web, w => w.AllProperties);
  clientContext.ExecuteQuery();

  if (!web.AllProperties.FieldValues.ContainsKey("Customized"))
  {
    return 0;
  }
  else
  {
    return (int)web.AllProperties["Customized"];
  }
}

View original post

Advertisements
Commands

Basic method to write CSOM functions

When writing down CSOM code which is the “IN” things now a days, one has to be very cautious while forming the structure of the functions. I have faced many issues due to lack of understanding for this and thus thought of writing it down thus it would help everyone.

If two independent asynchronous calls are made then it creates an issue as this causes 2 threads that execute independently and thus the required function is fails to load. So, it is advisable to make nested calls rather than independent ones.

The following is the basic structure of the that one should keep in mind while writing the CSOM functions.

function function1(){
    //Your logic
    context.executeQueryAsync(onQuerySucceeded1,onQueryFailed);
}
function onQuerySucceeded1(sender, args) {  
      //success function1

      //Call the second function here
      function2();
      context.executeQueryAsync(onQuerySucceeded2,onQueryFailed);
}
function onQuerySucceeded2(sender, args) {  
      //success function2         
}
function onQueryFailed(sender, args) {  
      console.log("Error");
}

 

Commands

Powershell Scripts using CSOM for basic list operations.

Many a times when we are supposed do deploy our changes on the production box we do not have access to the server and at that we would need require powershell script to deploy.

The following are the functions to perform the basic list operations using powershell scripts with client object model.

Creating a list with two columns and sample data:

Add-Type –Path “C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll”
Add-Type –Path “C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll”
# Authenticate with the SharePoint Online site.
$siteUrl = “siteurl”

# Connect to SharePoint Online and get ClientContext object.
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$credentials = Get-Credential
$Context.Credentials = $credentials

#Create list with “custom” list template
$ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$ListInfo.Title = $ListTitle
$ListInfo.TemplateType = “100”
$List = $Context.Web.Lists.Add($ListInfo)
$List.Description = $ListTitle
$List.Update()
$Context.ExecuteQuery()

#Retrieve site columns (fields)
$SiteColumns = $Context.Web.AvailableFields
$Context.Load($SiteColumns)
$Context.ExecuteQuery()

#Grab city and company fields
$City = $Context.Web.AvailableFields | Where {$_.Title -eq “City”}
$Company = $Context.Web.AvailableFields | Where {$_.Title -eq “Company”}
$Context.Load($City)
$Context.Load($Company)
$Context.ExecuteQuery()

#Add fields to the list
$List.Fields.Add($City)
$List.Fields.Add($Company)
$List.Update()
$Context.ExecuteQuery()

#Add fields to the default view
$DefaultView = $List.DefaultView
$DefaultView.ViewFields.Add(“City”)
$DefaultView.ViewFields.Add(“Company”)
$DefaultView.Update()
$Context.ExecuteQuery()

Get all list items

function GetListItems()
{
# Connect to SharePoint Online and get ClientContext object.
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$credentials = Get-Credential
$clientContext.Credentials = $credentials
# Get the list items
$list=$clientContext.Web.Lists.GetByTitle(“PS Custom List”)
$camlQuery= [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
$itemColl=$list.GetItems($camlQuery)
$clientContext.Load($itemColl)
# Execute the query
$clientContext.ExecuteQuery();
# Loop through all the items and display the title field
foreach($item in $itemColl)
{
Write-Host -ForegroundColor Green $item[“Title”]
}
}

Add new item to the list

function AddNewitem()
{
# Connect to SharePoint Online and get ClientContext object.
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$credentials = Get-Credential
$clientContext.Credentials = $credentials
# Get the list by title
$list=$clientContext.Web.Lists.GetByTitle(“PS Custom List”)
# Add new item to the list
$creationInfo= New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$newItem=$list.AddItem($creationInfo)
# Set the title value for the new item
$newItem[“Title”]=”test item”;
# Update the item
$newItem.Update();
$clientContext.Load($newItem)
# Execute the query
$clientContext.ExecuteQuery();
# Display the new item field value
Write-Host -ForegroundColor Green $newItem[“Title”]
}

Note : You can also accept the input from the user as below:

$ListTitle = read-host “Enter list title:”

Commands

Return SPListItems using CSOM and PowerShell without writing CAML

Get List Items from list using CSOM and SharePoint Powershell

SharePointRyan

I recently tweeted about my triumph when trying to accomplish returning all SharePoint List Items without the use of CAML or LINQ. The reason I wanted to do this might be strange, but I’ll try to explain my process and methodology and why I got to a point of wanting to make SharePoint do things it didn’t want to do. 🙂

As a very advanced SharePoint Scripter, I do a TON of PowerShell. If you’ve read this blog, follow me on Twitter or talk to me in person you probably knew that. Having said that, there are times when I want to iterate through all list items – either looking for a match or just to return all values. It’s not super common but it happens. Well it’s a very easy thing to do with server side code (read: PowerShell and the Microsoft.SharePoint.PowerShell snap-in).

Getting List Items using standard PowerShell

View original post 610 more words

Commands

Introduction to Bootstrap and its use to create Responsive sites in SharePoint 2013

Responsive websites are the latest trend in today’s world. A single website is visited from many different devices of different sizes so it becomes very important to consider this point when designing your website. The design of the website has to be consistent regardless the device from where it is viewed. Thus, the concept of “responsive” websites has come up.

The responsive design can be defined as an approach to design a webpage that makes use of flexible layouts, flexible images and style sheets. SharePoint has also started to adopt this funda now. The most widely used method to create a responsive site is using Bootstrap.

Bootstrap is an open source framework to assist one to create responsive sites. The following are some introductory points that would help anyone who has just started using Bootstrap.

  • Bootstrap uses of certain HTML elements and CSS properties that require the use of the HTML5 doctype. Include it at the beginning of all your projects.
  • The viewport tag helps to create mobile friendly site. It has to be embedded in the <head> as shown below:
    • <meta name="viewport" content="width=device-width, initial-scale=1">
    • If you want to disable the zoom then use is as :
    • <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
      
    •  The bootstrap framework divides the entire screen into columns and rows. There are 12 columns available. Also there are inbuilt classes available which we can user during development.Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding.
    • Use rows to create horizontal groups of columns.
    • Content should be placed within columns, and only columns may be immediate children of rows.
    • Predefined grid classes like .row and .col-xs-4 are available for quickly making grid layouts.
    • Columns create gutters (gaps between column content) via padding. That padding is offset in rows for the first and last column via negative margin on .rows.

This is an introduction. I shall write more about this as I implement it practically day by day.

Reference: http://getbootstrap.com/css/

Commands

Fetching Data from Managed Metadata column using CSOM – javascript

There are many situations where we have a requirement to access data from a list column of type managed metadata. The managed columns are of two types – Single values columns and multi valued columns. The following code will assist you to fetch the values from managed metadata columns.

Accessing value from Single valued Column:

var listItemEnumeratorlistReady = collListItems.getEnumerator(),

while (listItemEnumeratorlistReady.moveNext()) {
swItem = listItemEnumeratorlistReady.get_current();
var documentType = swItem.get_item(“DocumentType”)[“Label”];
}

Accessing value from Multi valued Column:

var listItemEnumeratorlistReady = collListItems.getEnumerator(),

while (listItemEnumeratorlistReady.moveNext()) {

swItem = listItemEnumeratorlistReady.get_current();

var taxEnumerator = swItem.get_item(‘DocumentType’);

if (typeof taxEnumerator !== “undefined” && taxEnumerator !== null) {
if (taxEnumerator._Child_Items_.length > 0)
{
var tempArray = new Array();
if (taxEnumerator._Child_Items_.length == 1)// If single value
{
var documentType =  taxEnumerator._Child_Items_[0].Label;
}
else// If multi value
{
for (var i = 0; i < taxEnumerator._Child_Items_.length ; i++)
{
documentType = taxEnumerator._Child_Items_[i].Label;
}
}
}
}

Commands

Text Formulas for the Calculated Column

Some really useful stuff for writing calculated columns formalae

SharePoint Diva

This is a continuation of an attempt to group the information needed for Calculated Columns in a meaningful way. Some items appear on more than one list since this exercise can be subjective.

Examples of common formulas: Text formulas

Other Text Functions:

AND function Returns the logical value TRUE if all of the arguments are TRUE; returns FALSE if one or more arguments is FALSE.
ASC function For Double-byte character set (DBCS) languages, changes full-width (double-byte) characters to half-width (single-byte) characters.
AVERAGEA function Calculates the average (arithmetic mean) of the values in the list of arguments.
CHAR function Returns the character specified by a number.
CHOOSE function Uses index_num to return a value from the list of value arguments.
CLEAN function Removes all nonprintable characters from text.
CODE function Returns a numeric code for the first character in a text string.
CONCATENATE function Use the CONCATENATE function to join several text…

View original post 453 more words