Convert IP Address to numeric (JS)

I’ve been using some fancy functions in SQL to convert to/from an IP Address and Mask – but have needed to do the same within JavaScript.

This is a requirement based on some MySQL functions – eg. INET_NTOA and INET_ATON.

This first one will take an input value – eg. 255.240.0.0 – and return a number (BIGINT / INT64 for calculations – or storing in a database – as we’re needing to do.

    function convertIpToNumeric(ipAddress) {
        var arrIp = ipAddress.split(".");

        var segment1 = parseInt(arrIp[0]);
        var segment2 = parseInt(arrIp[1]);
        var segment3 = parseInt(arrIp[2]);
        var segment4 = parseInt(arrIp[3]);

        //reverse order calc 
        //eg. 255.255.240.0     <-- start at the end
        // 0 + (240*256) + (255*65536) + (255*16777216)
        var calc = segment4 + (segment3 * 256) + (segment2 * 65536) + (segment1 * 16777216);

        return calc;

    }

And – if needing to do the opposite – you can use the following function.

This will take an input value – eg. 167772161 – and return the resultant IP Address :

function convertNumericToIp(bigNumber) {

    var Octet1 = Math.floor(bigNumber / 16777216)
    var RestOfIP = bigNumber - (Octet1 * 16777216)

    var Octet2 = Math.floor(RestOfIP / 65536)
    var RestOfIP = RestOfIP - (Octet2 * 65536)

    var Octet3 = Math.floor(RestOfIP / 256)
        
    var Octet4 = RestOfIP - (Octet3 * 256)

    var returnValue = Octet1 + "." + Octet2 + "." + Octet3 + "." + Octet4; 

    return returnValue;

}

Turn OFF flag for HIDE PHYSICAL URL’s

We have a set of publishing pages that are not correctly showing if/when the following flag is set to ON :

image

This is to do with the SEO and vanity URL’s stuff – but we want this “OFF”.

Looking at the field via the REST URL, you can see the default value.    But, the field/column is actually a SEALED column, and so you can’t update it via the UI.

https://tenant.sharepoint.com/sites/MyFancySiteColl/_api/Web/AvailableFields(guid’50631c24-1371-4ecf-a5ae-ed41b03f4499′)

image 

So – it’s some fancy PowerShell to force this value (after connecting to O365) :

#get the fields at the root site level
$rootWeb = $clientContext.Web
$fields = $rootWeb.Fields
$clientContext.Load($fields)
$clientContext.ExecuteQuery()

#grab the field 
$fld = $fields.GetByInternalNameOrTitle("PublishingIsFurlPage")
$clientContext.Load($fld)
$clientContext.ExecuteQuery()

$fld

$fld.DefaultValue = $false
$fld.Update()
$clientContext.ExecuteQuery()

$rootWeb.Update()
$clientContext.ExecuteQuery()

After running this PowerShell, the field is SET when viewing the column via REST :

image

And now, when users create a page – regardless of PAGE LAYOUT – this value will be ticked to OFF by default – and standard URL’s will be used – too easy.

The main issue we had was with a Content Search WebPart that was NOT showing the pages that had the checkbox ON.   We needed users to make sure to set it off – making it DEFAULT to off was the best option.

🙂

SQL Server INET_ATON IP Address + CIDR

Most IT folk would understand that an IP Address is a 4-octset set – eg. 192.168.53.123

There’s another piece that is the subnet mask – eg.  255.255.252.0

These are usually managed as numerical values – BIGINT values (Int64).

Within MySQL, you can determine the IP Address to/from a number using the functions INET_ATON and INET_NTOA.

For an equivalent in SQL Server – you can use the following UDF’s :

Integer to IP Address :

CREATE FUNCTION [dbo].[IntegerToIPAddress] (@IP AS bigint)
RETURNS varchar(15)
AS
BEGIN
 DECLARE @Octet1 bigint
 DECLARE @Octet2 tinyint
 DECLARE @Octet3 tinyint
 DECLARE @Octet4 tinyint
 DECLARE @RestOfIP bigint
 
 SET @Octet1 = @IP / 16777216
 SET @RestOfIP = @IP - (@Octet1 * 16777216)
 SET @Octet2 = @RestOfIP / 65536
 SET @RestOfIP = @RestOfIP - (@Octet2 * 65536)
 SET @Octet3 = @RestOfIP / 256
 SET @Octet4 = @RestOfIP - (@Octet3 * 256)
 
 RETURN(CONVERT(varchar, @Octet1) + '.' +
        CONVERT(varchar, @Octet2) + '.' +
        CONVERT(varchar, @Octet3) + '.' +
        CONVERT(varchar, @Octet4))
END

IP Address to Integer

CREATE FUNCTION [dbo].[IPAddressToInteger] (@IP AS varchar(15))
RETURNS bigint
AS
BEGIN
 RETURN (CONVERT(bigint, PARSENAME(@IP,1)) +
         CONVERT(bigint, PARSENAME(@IP,2)) * 256 +
         CONVERT(bigint, PARSENAME(@IP,3)) * 65536 +
         CONVERT(bigint, PARSENAME(@IP,4)) * 16777216)
 
END

Yet another piece of the puzzle is related to a CIDR – which looks like this :  192.30.250.00/18

It’s an acronym for “Classless Inter-Domain Routing” – I had to look it up too…!

I’ve created another function that determines the “/18” for a given numeric sequence (in T-SQL).

CREATE FUNCTION [dbo].[CIDRFromMask] (@mask AS BIGINT)
RETURNS VARCHAR(5)
AS
BEGIN

	 DECLARE @maskCalc BIGINT
	 SELECT @maskCalc = dbo.IPAddressToInteger('255.255.255.255') - @mask + 1

	 DECLARE @logCalc int
	 SELECT @logCalc = (32 - LOG(@maskCalc, 2))

	 RETURN '/' + CAST(@logCalc AS VARCHAR(5))

END

This helped me with the retrieval of an IP Address – and CIDR – fairly complex, but easy to use in the end – eg.  255.255.252.0/22

select dbo.IntegerToIPAddress('4294966272') + dbo.CIDRFromMask('4294966272')

image

A Web Part with this ID has already been added to this page.

Within a SharePoint site that we’ve upgraded, we have an error showing when users navigate to a page :

image

Using some PowerShell, I was able to list the specific webparts on the page :

$web = Get-SPWeb http://intranet/Services/Finance 
$list = $web.Lists["Pages"] 
  
#get the page (listitem) 
$item = $list.Items[0] 
 
#get the webpart manager 
$wpm = $item.File.GetLimitedWebPartManager('Shared') 
 
$wpm.WebParts | select id, title 

And somehow, there is a duplicate GUID for a certain WebPart :

image

The next step is to remove one of those webparts from the page – following on from the PowerShell shown above :

#get the webpart using #3
$wp = $wpm.WebParts[3] 

#check which one we've got
$wp | select id, title
 
#delete from the page - and update 
$wpm.DeleteWebPart($wp) 
$item.Update()

 

That outta do it – and your users will be able to browse to the page.

NB.  You might have to checkout the page also – and then verify which webpart you need to remove – be careful !

Quick connect to O365 using PowerShell

I’ve been doing lots of posts about connecting to Office365, and a bunch of scripts, so I thought I’d share my easy script – just gotta update the URL, and PASSWORD.

** NB.  You need a folder with the DLL’s – this is my set of files :

image

This is the basic script – to add a reference to the necessary DLL’s (above) – and then define the user/password – and make a connection – and then load the WEB object.

$path =  'C:\o365';

$urlSite = 'https://[tenant].sharepoint.com/sites/[SITECOLLECTION]'

$user = '[USER]@[TENANT].onmicrosoft.com';
$password = 'Password1234';

[Reflection.Assembly]::LoadFile('$path\Libraries\Microsoft.SharePoint.Client.dll')
[Reflection.Assembly]::LoadFile('$path\Libraries\Microsoft.SharePoint.Client.Runtime.dll')

add-type -Path $path'\Libraries\Microsoft.SharePoint.Client.dll'
add-type -Path $path'\Libraries\Microsoft.SharePoint.Client.Runtime.dll'

$passwordSecureString = ConvertTo-SecureString -string $password -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $user, $passwordSecureString

$spoCtx = New-Object Microsoft.SharePoint.Client.ClientContext($urlSite)
$spoCredentials = New-Object -TypeName Microsoft.SharePoint.Client.SharePointOnlineCredentials -argumentlist $user, $passwordSecureString
$spoCtx.Credentials = $spoCredentials
$spoCtx.RequestTimeout = '500000'

$web = $spoCtx.web
$spoCtx.Load($web)
$spoCtx.ExecuteQuery();

Please let me know if that’s helpful – feel free to copy+use – I’ve used this a LOT in quick testing scripts…

🙂

SetDefaultPageLayout CSOM

As part of my new Office 365 site collection provisioning (via PowerShell), I’d like to be able to set the ‘default page layout’ :

image

BUT – within the object model for SharePoint.Client.Publishing, there are only a handful of methods for the PublishingWebClass – and so I can’t use CSOM or POWERSHELL to set the default page layout.

Click here to see on MSDN :

image

But – after a quick poke into the DLL for SharePoint.Publishing.DLL (using ILSPY), I could see that the functionality is just to add a property – which is EASY via CSOM…>!

image

image

And – sure enough, if you look using the REST endpoint, there it is :

https://tenant.sharepoint.com/sites/D001N/_api/web/AllProperties

image

It looks like the value that I need – for the Page Layout of “ArticleLeft” is :

<layout guid=”8520f570-356b-462d-8976-1e58b936c65e” url=”_catalogs/masterpage/ArticleLeft.aspx” />

Unfortunately – that GUID is different, as you move to another site collection – even for the same page layout – doh !

Another look at ILSPY shows that the GUID is the ID of the listitem :

image

So – the PowerShell needs to determine the specific item for the page layout I want – and then construct the little XML chunk – and update the property for __DefaultPageLayout.

There’s a REST call that shows these guys :

https://tenant.sharepoint.com/sites/D001N/_api/Web/GetFolderByServerRelativeUrl(‘/sites/D001N/_catalogs/masterpage’)/Files

And – you can actually grab the specific file :

https://tenant.sharepoint.com/sites/D001N/_api/Web/GetFileByServerRelativeUrl(‘/sites/D001N/_catalogs/masterpage/ArticleLeft.aspx’)?$select=UniqueId

image

But – from a POWERSHELL command line, this is what you need – once you’ve established a context to the specific site collection :

$rootWeb = $spoCtx.web
$spoCtx.Load($rootWeb)
$spoCtx.ExecuteQuery();

$spoCtx.Load($rootWeb.AllProperties)
$spoCtx.ExecuteQuery(); 

$defaultPageLayout = '_catalogs/masterpage/ArticleLeft.aspx'

#get the page item - and grab the GUID of it
$urlRelative = $rootWeb.ServerRelativeUrl + "/" + $defaultPageLayout
$pageLayoutFile = $rootWeb.GetFileByServerRelativeUrl($urlRelative) 
$spoCtx.Load($pageLayoutFile)
$spoCtx.ExecuteQuery();

$pageGuid = $pageLayoutFile.UniqueId;

#set the xmlchunk for the property
$xmlPageLayout = "<layout guid='{0}' url='{1}' />"
$xmlPageLayout = $xmlPageLayout.Replace("{0}", $pageGuid);
$xmlPageLayout = $xmlPageLayout.Replace("{1}", $defaultPageLayout);

$rootWeb.AllProperties["__DefaultPageLayout"] = $xmlPageLayout;
$rootWeb.Update()
$spoCtx.ExecuteQuery(); 

That works nicely – phew !     🙂

Add SharePoint Group to Library (Break Permissions)

I’ve had some back and forth hiccups when getting some security provisioning for a SharePoint library.

The basic premise was to break-inheritance – and only allow the “OWNERS” group to have permission (full control).

Seems easy enough – but I was getting errors like :

The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

Or this one, which was annoying, and tripping me up :

Cannot add a role assignment with empty role definition binding collection.

It turns out that I was actually doing “too many” of the ExecuteQuery statements – which I didn’t actually need.   

So – I had success, using this code – and through I’d share it in case you have the same problem – or for my own future reference :

// ==================================================================
// set the OWNERS group to have permissions to the [submitted work] library
// ==================================================================
List submittedWorkLib = clientCtx.Web.Lists.GetByTitle('Submitted Work');
clientCtx.Load(submittedWorkLib);
clientCtx.ExecuteQuery();

//break security/permissions for the library
submittedWorkLib.BreakRoleInheritance(false, false);
clientCtx.Load(submittedWorkLib);
clientCtx.ExecuteQuery();

//add the owners group
string workspaceOwnersGroup = web.Title + &quot; Owners&quot;;
LogHelper.WriteToLog(log, &quot;Add the workspace owners group to library : &quot; + workspaceOwnersGroup);

clientCtx.Load(web.RoleDefinitions);
clientCtx.ExecuteQuery();

var role = web.RoleDefinitions.FirstOrDefault(r =&gt; r.Name == &quot;Full Control&quot;);
clientCtx.Load(role);
clientCtx.ExecuteQuery();

clientCtx.Load(web.SiteGroups);
clientCtx.ExecuteQuery();

var group = web.SiteGroups.FirstOrDefault(g =&gt; g.Title == workspaceOwnersGroup);
clientCtx.Load(web.SiteGroups);
clientCtx.Load(group);
clientCtx.ExecuteQuery();

var roleDefBinding = new RoleDefinitionBindingCollection(clientCtx);
roleDefBinding.Add(role);
submittedWorkLib.RoleAssignments.Add(group, roleDefBinding);

clientCtx.ExecuteQuery();

Let me know if that helps – thanks !

Other references :