How to set O365 PageLayout Associated Content Type field

Here is a code snippet to set your page layouts associated content type. This one was a bit weird when I first tried to set it.

 private static void SetPageLayoutMetadata(Web web, File uploadFile, string title, string publishingAssociatedContentType)
{
// Speficy that the page layout is a page layout and not a master page
var parentContentTypeId = ""0x01010007FF3E057FA8AB4AA42FCB67B453FFC100E214EEE741181F4E9F7ACC43278EE811""; //Page Layout
var gallery = web.GetCatalog(116);
web.Context.Load(gallery, g => g.ContentTypes);
web.Context.ExecuteQuery();

var contentTypeId = gallery.ContentTypes.FirstOrDefault(ct => ct.StringId.StartsWith(parentContentTypeId)).StringId;
var item = uploadFile.ListItemAllFields;
web.Context.Load(item);

item["ContentTypeId"] = contentTypeId;
item["Title"] = title;
item["PublishingAssociatedContentType"] = publishingAssociatedContentType;

item.Update();
web.Context.ExecuteQuery();
} 

Two important things:

  • parentContentTypeId: This is the ID that tells O365 that this page layout is actually page layout, this is a static id which is defined in the code
  • publishingAssociatedContentType: This is your actual content type to which you want to associate your page layout to: Example of the format:;#my content type name;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D00A3428808D7DE6A4RABF83921AFB25424;#
    • So the format should be in the following way:

public static String BuildPublishingAssociativeContentTypeId(ContentType contentType)
{
String contentTypeAssociativeID = null;
if(contentType != null)
{
contentTypeAssociativeID = String.Format(";#{0};#{1};#", contentType.Name, contentType.StringId);
}

return contentTypeAssociativeID;
}

O365 OfficeDev PnP CSOM tools installation

This post will assume you have Visual Studio installed with Microsoft Office 365 API tools for Visual Studio.

  • Create a new Visual Studio project, lets say a console application.
  • Press on your project the second mouse button and select “Manage NuGet Packages…”
  • In the new window search for online packages and type in pnp or officedevpnpcore or similar. Then install the OfficeDevPnp.Core.Online package.

OfficePnp1

  • Wait for the installation to complete. After this you are ready to use CSOM to operate on your desired O365 site.

OfficePnp2

As you can see from the image above the nuget package will install all of what you need. You do not have to worry about much. Easy, right :)?

Links to know:

https://github.com/OfficeDev/PnP

https://channel9.msdn.com/blogs/OfficeDevPnP/Getting-Started-with-PnP-Provisioning-Engine

https://github.com/OfficeDev/PnP-Partner-Pack

http://dev.office.com/patterns-and-practices-resources

http://dev.office.com/blogs/new-sharepoint-csom-version-released-for-Office-365

https://www.nuget.org/packages/Microsoft.SharePointOnline.CSOM

https://lionadi.wordpress.com/2015/06/22/office-365-o365-client-application-registration-authentication-and-authorization/

https://lionadi.wordpress.com/2015/07/02/o365-csom-client-side-object-model-examples/

https://lionadi.wordpress.com/2015/09/16/o365-csom-getting-user-profile-information-without-possible-errors/

https://lionadi.wordpress.com/tag/o365/

SharePoint CORS fix

This is possible fix for the a possible calls made from one application to your SharePoint side that is located in another domain.

In your SharePoint application add the following custom headers to enable requests from a different domain. Just change the header: Access-Control-Allow-Origin to point to the application who is making a call to your SharePoint application.

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name=”Access-Control-Allow-Credentials” value=”true” />
        <add name=”Access-Control-Allow-Origin” value=”http://source-application.com​&#8221; />
        <add name=”Access-Control-Request-Method” value=”GET,POST,HEAD,OPTIONS” />
      </customHeaders>
    </httpProtocol>​
</system.webServer>​

Also if you are making an AJAX call add the following parameter to the call:
xhrFields: { withCredentials: true }

 

Sample code:

jQuery.ajax({
 url: requestUri,
 type: 'GET',
 dataType: 'json',
 headers: requestHeaders,
 xhrFields: { withCredentials: true },
 success: function (data)
 { 

 },
 error: function ajaxError(response) {
 console.log(response.status + ' ' + response.statusText);
 }
 });

Other possible parameters for the AJAX call:

crossDomain: true
And for CORS support:
$.support.cors = true;

A bit more detail can be found here in this post:
https://blog.kenaro.com/2014/03/18/cross-site-scripting-with-sharepoint-2013-rest-calls/

Tutorial guide: Learn Python basics

Hi ok, here are my own notes on the basics of Python. I am working on a Udemy course on data science and got excited about Python(it has been while since I’ve done something cool with Python, so I am excited 🙂 ). This is based on the Udemy course https://www.udemy.com/data-science-and-machine-learning-with-python-hands-on

Where it goes, hope it helps.

You can run python code as scripts or as a python notebook.

 

Running a script from a command prompt:

python “your script file location and name”

 

Basic basics

 

List definition:

listOfNumbers = [1, 2, 3, 4, 5, 6]

 

Iteration through a list of items:

for number in listOfNumbers:

print number,

if (number % 2 == 0):

print “is even”

else:

print “is odd”

 

#Notice: In python you differentiate between blocks of code by whitespace, or a tab. Not the same as let say Java or C# where the char { and } are used to differentiate a block of code. Pay attention to you formatting, indentation.

 

#Notice: The char , (comma) is used to tell that something is going to continue on the same print line, within the same block of code. See example above.

 

#Notice: Colons : differentiate clauses.

 

Importing modules

 

import numpy as np

 

A = np.random.normal(25.0, 5.0, 10)

print A

 

Data structures

 

Lists

 

Defining a list(Notice: The brackets [] define an mutable list):

x = [1, 2, 3, 4, 5, 6]

 

Printing the length of a list:

print len(x)

 

Sub setting lists:

 

First 3 elements(counting starts from zero):

x[:3]

 

Last 3 elements:

x[3:]

 

Last two elements from starting from the end of the list:

x[-2:]

 

Extend the list with a new list :

x.extend([7,8])

 

Add a new item to the list:

x.append(9)

 

Python is a weekly typed language which allows you to put whatever you want in a list:

 

Creating a multidimensional list:

y = [10, 11, 12]

listOfLists = [x, y]

listOfLists

 

Sort a list(descending):

z = [3, 2, 1]

z.sort()

 

Sort a list(ascending):

z.sort(reverse=True)

 

Tuples

 

Are just like lists but immutable.

You can not extend them append them, sort them etc. You can not change them.

 

Example:

 

#Tuples are just immutable lists. Use () instead of []

x = (1, 2, 3)

len(x)

 

y = (4, 5, 6)

 

listOfTuples = [x, y]

 

Tuples common usage for data science or data processing:

Is to use it to assign variables to input data that as it is read in.

 

This example creates variable with values from a “source” where data is split by the comma.

#Notice: It is important that you have the same about of variables in your tuple as you are retrieving/assigning from the data “source”.

(age, income) = “32,120000”.split(‘,’)

print age

print income

 

Dictionaries

 

A way to define a “lookup” table:

 

# Like a map or hash table in other languages

captains = {}

captains[“Enterprise”] = “Kirk”

captains[“Enterprise D”] = “Picard”

captains[“Deep Space Nine”] = “Sisko”

captains[“Voyager”] = “Janeway”

 

print captains[“Voyager”]

 

print captains.get(“Enterprise”)

 

for ship in captains:

print ship + “: ” + captains[ship]

 

If something is not found the result will be none:

print captains.get(“NX-01”)

 

Functions

 

Let you repeat a set of operation over and over again with different parameters.

 

Notice: use def to define a function and  () chars to define the parameters and use the return keyword to return value from the function.

 

def SquareIt(x):

return x * x

 

print SquareIt(2)

 

Pass functions around as parameters

#Notice: You have to make sure that what you are typing is correct because there is no strong typing in Python. Typing the wrong function name will cause errors.

 

#You can pass functions around as parameters

def DoSomething(f, x):

return f(x)

 

print DoSomething(SquareIt, 3)

 

Lambda functions

Is Functional programming: You can inline a function into a function

 

#Notice: lambda keyword is telling that you are defining a inline function to be used where you put it. In the example below inside a function parameter named x followed by a colon : character followed by what the function actually does. To pass in multiple parameters to a lambda function use the comma , to separate the variables.

 

#Lambda functions let you inline simple functions

print DoSomething(lambda x: x * x * x, 3)

 

Boolean Expressions

 

Valye is false

print 1 == 3

 

Value is true(or keyword check which is true)

print (True or False)

 

Check if something is a certain value( Use the is keyword)

print 1 is 3

 

If else clauses

 

if 1 is 3:

print “How did that happen?”

elif 1 > 3:

print “Yikes”

else:

print “All is well with the world”

 

Looping

 

Normal looping

for x in range(10):

print x,

 

Continue and Break

 

#Process only the first 5 items but skip the number one

for x in range(10):

if (x is 1):

continue

if (x > 5):

break

print x,

 

While

 

x = 0

while (x < 10):

print x,

x += 1