Thursday, September 27, 2018

Hide Button Based on Class Name using jquery

Hi,

I was not able to hide the button using button id through jquery.

But was able to hide the button finally using jquery through class name.


Header Insert using jquery

Hi,

Below is the code snippet that has been used to insert Header based on span id using jquery

var varCurrentStatus = $("span[id='Current_x0020_Status']").closest("tr");
    $('<h2 id="ProjectDetails" style="background-color: yellow;font-weight: BOLD;">Project Details</h2>').insertBefore(varCurrentStatus);

MS Flow to move Documents along with Metadata from one site to another site

Hi,

Our requirement is to move documents along with file properties if column document Status of type choice is equal to Final

To achieve this first we have added “When a file is created or modified(properties only)” action,mentioned source url and selected document library

Step1
Step2
Now in yes block ,added “Get file content” action I am entering the source url in the Site Address, entering Identifier as dynamic content
Step3
Thereafter add “Create file” action, entered target library url and selected target library
Entered enter Filename with extension, File Content as dynamic content.
Step4
Add the “Update file properties” action, entered the target site url and selected the destination library.

There after entered ItemId, Tite etc. as the dynamic content

Step5
Entered the source site url and entered the Identifier as the dynamic content.
After this changing the document status to Final document was getting moved to destination library.
After moving,document was getting deleted from the source library.

Friday, February 2, 2018

Codification Web Part

Hi,

We had a requirement as below

1/ Upload the item to the target document library
2/ After adding the item in the list, the value should be auto incremented under the Chrono Column
3/ Upload the document in the target document library
4/ After uploading the document, the value should be auto incremented under the Chrono Column
5/ In the Chrono Config list of the root site, the updated value should be visible under Chrono Increment Value column w.r.t target library GUID
6/The Chrono field should be hidden in the target document library Editform.aspx
7/The Chrono field should be hidden in the target library Editform.aspx
8/After filling mandatory properties, click Save on the upload pop up dialog
9/The value under Codification should come up as per the format specified under FormatDigit column of MC2CodificationConfigList in root site

For this the below java script has been developed

<script language="javascript" type="text/javascript" src="/sites/MC2Mig-DevSite/Style%20Library/js/jquery.min.js"> 
</script>
<script language="javascript" type="text/javascript" src="/sites/MC2Mig-DevSite/Style%20Library/js/sputility.js"> 
</script>
<script language="javascript" type="text/javascript">
//Chrono Variables
var oList, oListItem, oConfigList, oConfigListcount, count = 0, autoincrementcount = 0;
var MC2ChronoConfigList = 'MC2ChronoConfigList';
var ChronoIncrementValue = 'ChronoIncrementValue';
var ChronoFieldColumnName = 'ChronoFieldColumnName';

//Codification Variables
var oCodificationConfigList,oCodificationList
var MC2CodificationConfigList = 'MC2CodificationConfigList';
var SourcePrefixColumnName = 'SourcePrefix';
var SourcePostfixColumnName = 'SourcePostfix';
//var MC2ChronoConfigList = 'MC2ChronoConfigList';
var TargetColumnName='TargetColumn';
var Codification='Codification';
var strChronoColumnValue;
var strSourcePrefixValue;
var strSourcePostfixValue;
var strTargetColumnValue;
var strChronoUpdatedValue;

var strFormatDigitValue;

$(document).ready(function () {
    try { 
                                //alert('entered into ready function');
                                //Get the Chrono Field Auto Increment column details to hide
        getChronoColumnandHide(_spPageContextInfo.siteAbsoluteUrl, "{" + WPQ2FormCtx.ListAttributes.Id + "}");                
                               
                                if(WPQ2FormCtx.FormControlMode == 2)
                                {
                                                //SPUtility.HideSPField('Codification');
                                                //SPUtility.HideSPField(Codification);
                                                getCodificationColumnandHide(_spPageContextInfo.siteAbsoluteUrl, "{" + WPQ2FormCtx.ListAttributes.Id + "}");                   
                                }
    }
    catch (ex) {
        console.log(ex);
    }
});
function getCodificationColumnandHide(webUrl, listGUID) {
    try {
                                //alert('getCodificationColumnandHide');
        var fullUrl = webUrl + "/_api/web/lists/getByTitle('" + MC2CodificationConfigList + "')/items?$select=" + TargetColumnName + "&$filter= Title eq '" + listGUID + "'";
                                //alert(fullUrl);
        $.ajax({
            url: fullUrl,
            type: "GET",
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
            },
            success: onQueryConfigCodificationSucceeded,
            error: onQueryConfigCodificationFailed
        });
    }
    catch (ex) {
        console.log(ex);
    }
}
function onQueryConfigCodificationSucceeded(data) {
    if (data.d.results.length != 0) {
                //console.log(data.d.results[0].TargetColumn);                 
                                //alert(data);
        SPUtility.GetSPField(data.d.results[0].TargetColumn).Hide();
    }
}
function onQueryConfigCodificationFailed() {
    alert("An error has occurred.");
}
function getChronoColumnandHide(webUrl, listGUID) {
    try {
        var fullUrl = webUrl + "/_api/web/lists/getByTitle('" + MC2ChronoConfigList + "')/items?$select=" + ChronoFieldColumnName + "&$filter= Title eq '" + listGUID + "'";
        $.ajax({
            url: fullUrl,
            type: "GET",
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
            },
            success: onQueryConfigChronoSucceeded,
            error: onQueryConfigChronoFailed
        });
    }
    catch (ex) {
        console.log(ex);
    }
}
function onQueryConfigChronoSucceeded(data) {
    if (data.d.results.length != 0) {
        SPUtility.GetSPField(data.d.results[0].ChronoFieldColumnName).Hide();
    }
}
function onQueryConfigChronoFailed() {
    alert("An error has occurred.");
}

// PreSaveAction Operation
// success: The function to execute if the call is sucessfull
// failure: The function to execute if the call fails
function PreSaveAction() {
    try {
        //WPQ2FormCtx.FormControlMode = 2 - Denotes current form is Edit Form
        //WPQ2FormCtx.FormControlMode = 3 - Denotes current form is New Form
        //WPQ2FormCtx.ListAttributes.ListTemplateType == 101 - Denotes current list is of type Document Library
        //WPQ2FormCtx.ListAttributes.ListTemplateType == 100 - Denotes current list is of type Generic List
                               

        if (WPQ2FormCtx.ListAttributes.ListTemplateType == 101) {                                
            GetMC2ChronoConfigListData()
                                                GetMC2CodificationConfigListData()
        }
        else if (WPQ2FormCtx.ListAttributes.ListTemplateType == 100) {
            if (WPQ2FormCtx.FormControlMode == 3) {
                GetMC2ChronoConfigListData()
            }
            else {               
                return true;
            }
        }
    }
    catch (ex) {
        console.log(ex);
    }

}
function GetMC2CodificationConfigListData()
{

//Get Client Context and Web object. 
    clientContext = new SP.ClientContext.get_current();
    var oWeb = clientContext.get_web();
    oCodificationConfigList = clientContext.get_site().get_rootWeb().get_lists().getByTitle(MC2CodificationConfigList);
    //CamlQuery to fetch records w.r.t List Guid
    var camlQuery = new SP.CamlQuery();
    var listGUID = "{" + WPQ2FormCtx.ListAttributes.Id + "}";
                //alert(listGUID);
    camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'Title\'/>' + '<Value Type=\'Text\'>' + listGUID + '</Value></Eq></Where></Query><RowLimit>10</RowLimit></View>');
    oCodificationConfigListcollListItemColl = oCodificationConfigList.getItems(camlQuery);
    clientContext.load(oCodificationConfigListcollListItemColl);
    clientContext.load(oCodificationConfigList);
    clientContext.executeQueryAsync(onQueryCodificationReadSucceeded, onQueryCodificationReadFailed);

}
function onQueryCodificationReadSucceeded(sender, args) {
    if (oCodificationConfigListcollListItemColl.get_count() != 0) {
                               
        var oCodificationConfigListItem = oCodificationConfigListcollListItemColl.get_item(0);                            
        var strTitle = oCodificationConfigListItem.get_item('Title');                  
                                strSourcePrefixValue=oCodificationConfigListItem.get_item(SourcePrefixColumnName);
                                strSourcePostfixValue=oCodificationConfigListItem.get_item(SourcePostfixColumnName);
                                strTargetColumnValue=oCodificationConfigListItem.get_item(TargetColumnName);
                                strFormatDigitValue=oCodificationConfigListItem.get_item('FormatDigit');                           
                                getChronoColumnValue(_spPageContextInfo.siteAbsoluteUrl, "{" + WPQ2FormCtx.ListAttributes.Id + "}");                                      
                               
        oCodificationConfigListItem.update();
        clientContext.load(oCodificationConfigList);
        clientContext.executeQueryAsync(OnCodificationSuccess, OnCodificationFailure)
                               
    }
  
}

function getChronoColumnValue(webUrl, listGUID) {
    try {
                                //alert('entered into getChronoColumnValue');
                   var fullUrl = webUrl + "/_api/web/lists/getByTitle('" + MC2ChronoConfigList + "')/items?$select=" + ChronoIncrementValue + "&$filter= Title eq '" + listGUID + "'";                    
                               
        $.ajax({
                                                async: false,                      
            url: fullUrl,
            type: "GET",
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
            },
            success: onQueryGetConfigChronoSucceeded,
            error: onQueryGetConfigChronoFailed
        });                 
    }
    catch (ex) {
        console.log(ex);
    }
}
function onQueryGetConfigChronoSucceeded(data) {
    if (data.d.results.length != 0) {               
                                strChronoUpdatedValue = data.d.results[0].ChronoIncrementValue;                                                                       
    }
}

function onQueryGetConfigChronoFailed() {
    alert("An error has occurred.");
}

function OnCodificationSuccess(sender, args) {

if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null) {
      throw new TypeError('can\'t convert ' + this + ' to object');
    }
    var str = '' + this;
    count = +count;
    if (count != count) {
      count = 0;
    }
    if (count < 0) {
      throw new RangeError('repeat count must be non-negative');
    }
    if (count == Infinity) {
      throw new RangeError('repeat count must be less than infinity');
    }
    count = Math.floor(count);
    if (str.length == 0 || count == 0) {
      return '';
    }
    // Ensuring count is a 31-bit integer allows us to heavily optimize the
    // main part. But anyway, most current (August 2014) browsers can't handle
    // strings 1 << 28 chars or longer, so:
    if (str.length * count >= 1 << 28) {
      throw new RangeError('repeat count must not overflow maximum string size');
    }
    var rpt = '';
    for (var i = 0; i < count; i++) {
      rpt += str;
    }
    return rpt;
  }
}  
               
                var strCodificationSourcePrefixValue=SPUtility.GetSPField(strSourcePrefixValue).GetValue();       
                var strCodificationSourcePostfixValue=SPUtility.GetSPField(strSourcePostfixValue).GetValue();   
               
                var chronosubstring=strFormatDigitValue.match("C(.*)d");
                var newchronosubstring = chronosubstring[1];
               
                var getchronoformatdigit=newchronosubstring.substring(newchronosubstring.lastIndexOf(":")+1,newchronosubstring.lastIndexOf("."));
                //alert(getchronoformatdigit);
               
                strFormatDigitValue = strFormatDigitValue.replace("{SourcePrefix}",strCodificationSourcePrefixValue)
                strFormatDigitValue = strFormatDigitValue.replace("{SourcePostfix}",strCodificationSourcePostfixValue);
               
                //var getChronoFormatDigitIndex=strFormatDigitValue.indexOf(":")+1;  
                //var getchronoformatdigit=strFormatDigitValue.charAt(getChronoFormatDigitIndex);   
                var chronoformatvalue= String("0".repeat(getchronoformatdigit) + strChronoUpdatedValue).slice(-getchronoformatdigit);                 
                strFormatDigitValue = strFormatDigitValue.replace("{Chrono:"+getchronoformatdigit+".d}",chronoformatvalue);
               
                SPUtility.GetSPField(strTargetColumnValue).SetValue(strFormatDigitValue);
               
                form.SubmitClientForm();
}
function OnCodificationFailure(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
function onQueryCodificationReadFailed(sender, args) {
    alert('An error has occurred. ' + args.get_message() + '\n' + args.get_stackTrace());

}

function GetMC2ChronoConfigListData() {
    //Get Client Context and Web object. 
    clientContext = new SP.ClientContext.get_current();
    var oWeb = clientContext.get_web();
    oConfigList = clientContext.get_site().get_rootWeb().get_lists().getByTitle(MC2ChronoConfigList);
    //CamlQuery to fetch records w.r.t List Guid
    var camlQuery = new SP.CamlQuery();
    var listGUID = "{" + WPQ2FormCtx.ListAttributes.Id + "}";
    camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'Title\'/>' + '<Value Type=\'Text\'>' + listGUID + '</Value></Eq></Where></Query><RowLimit>10</RowLimit></View>');
    oConfigListcollListItemColl = oConfigList.getItems(camlQuery);
    clientContext.load(oConfigListcollListItemColl);
    clientContext.load(oConfigList);
    clientContext.executeQueryAsync(onQueryReadSucceeded, onQueryReadFailed);
}

// Auto Increment Operation
// success: The function to execute if the call is sucessfull
// failure: The function to execute if the call fails
//Method to Compare List Guid from Config List and update Auto Increment Value
function onQueryReadSucceeded(sender, args) {

    if (oConfigListcollListItemColl.get_count() != 0) {
        var oConfigListItem = oConfigListcollListItemColl.get_item(0);
        var strTitle = oConfigListItem.get_item('Title');
        var strChronoIncrementValue = oConfigListItem.get_item(ChronoIncrementValue);
       var strChronoFieldColumnName = oConfigListItem.get_item(ChronoFieldColumnName);
        var currValue = SPUtility.GetSPField(strChronoFieldColumnName).GetValue();
        if (!currValue) {
            SPUtility.GetSPField(strChronoFieldColumnName).SetValue(strChronoIncrementValue + 1)
            oConfigListItem.set_item(ChronoIncrementValue, strChronoIncrementValue + 1);
            oConfigListItem.update();
            clientContext.load(oConfigList);
            clientContext.executeQueryAsync(OnSuccess, OnFailure)
        }
        else
        {
            //form.SubmitClientForm();
        }
    }
    else {
        alert("An error has occurred.");
    }
}
function onQueryReadFailed(sender, args) {
    alert('An error has occurred. ' + args.get_message() + '\n' + args.get_stackTrace());

}

function OnSuccess(sender, args) {
    //form.SubmitClientForm();
}
function OnFailure(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
Output

Chrono Configuration List






Target Document Library

Thursday, February 1, 2018

Codification Deployment script

Hi,

Before deployment of Codification, below is the required configuration in the site

1/ Check if Chrono config list exists, if not, create it with columns ChronoFieldColumnName and ChronoIncrementValue
2/ Check if target document library exists, if not, report error and stop execution
3/ populate Chrono config list with details from the target list i.e. add Target list GUID under Title Column, text ‘Chrono’ under ChronoFieldColumnName
4/ Check if Codification config list exists, if not, create it with columns SourcePrefix,SourcePostfix,TargetColumn,FormatDigit,WebUrl,SiteUrl,LibraryName
5/ Add the chrono, BU, Entity and Codification fields in target document library
6/ if doc lib, set sets settings to enforce display of edit form after doc creation
if list make the field mandatory
7/ Add the content editor web part to the document library->editform.aspx
8/Assign  the txt link to the content editor link


// Codification.bat
@ECHO OFF
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\DeploymentScript\CodificationDeploymentScript\CodificationScript.ps1'"
PAUSE

// CodificationInputs.xml
<?xml version="1.0" encoding="utf-8"?> 
<Inputs> 
  <ConnectSPConfigOnline SiteURL="siteurl" UserName="username" Password="password"></ConnectSPConfigOnline> 
  <ConnectSPOnline SiteURL="siteurl " UserName="username" Password="password"></ConnectSPOnline>   
  <ChronoConfigList Title="MC2ChronoConfigList" URL="MC2ChronoConfigList" Template="GenericList" ChronoFieldColumnName="ChronoFieldColumnName" ChronoIncrementValueColumnName="ChronoIncrementValue"/>
  <CodificationConfigList Title="MC2CodificationConfigList" URL="MC2CodificationConfigList" Template="GenericList" SourcePrefixColumnName="SourcePrefix" SourcePostfixColumnName="SourcePostfix" TargetColumnColumnName="TargetColumn" FormatDigitColumnName="FormatDigit" FormatDigitColumnValue="{SourcePrefix} {Chrono:4.d} {SourcePostfix}" WebUrlColumnName="WebUrl" SiteUrlColumnName="SiteUrl" LibraryColumnName="LibraryName"/>
  <ChronoConfigListFields>
   <ChronoConfigListField Title="ChronoFieldColumnName" InternalName="ChronoFieldColumnName" Group="ListGroup" Type="Text"/>     
   <ChronoConfigListField Title="ChronoIncrementValue" InternalName="ChronoIncrementValue" Group="ListGroup" Type="Number"/>     
  </ChronoConfigListFields> 
  <ChronoTargetLists>
   <ChronoTargetList Title="subsitecdoclib" URL="subsitecdoclib" Template="DocumentLibrary" ContentType="Item" ListFieldTitle="Chrono" ListFieldInternalName="Chrono" ListFieldGroup="ListGroup" ListFieldType="Number" ListFieldIncrementValue="1"/>     
</ChronoTargetLists>   
<CodificationConfigListFields>
   <CodificationConfigListField Title="SourcePrefix" InternalName="SourcePrefix" Group="ListGroup" Type="Text"/>     
   <CodificationConfigListField Title="SourcePostfix" InternalName="SourcePostfix" Group="ListGroup" Type="Text"/>     
   <CodificationConfigListField Title="TargetColumn" InternalName="TargetColumn" Group="ListGroup" Type="Text"/>     
   <CodificationConfigListField Title="FormatDigit" InternalName="FormatDigit" Group="ListGroup" Type="Text"/>
   <CodificationConfigListField Title="WebUrl" InternalName="WebUrl" Group="ListGroup" Type="Text"/>  
   <CodificationConfigListField Title="SiteUrl" InternalName="SiteUrl" Group="ListGroup" Type="Text"/>  
   <CodificationConfigListField Title="LibraryName" InternalName="LibraryName" Group="ListGroup" Type="Text"/>  
</CodificationConfigListFields> 
<CodificationTargetLibs>  
   <CodificationTargetLib Title="subsitecdoclib" URL="subsitecdoclib" Template="DocumentLibrary" ContentType="Item" ListFieldGroup="ListGroup" ListFieldType="Text" ListSourcePostfixFieldTitle="Entity" ListSourcePostfixFieldInternalName="Entity" ListTargetColumnFieldTitle="Codification" ListTargetColumnFieldInternalName="Codification" ListSourcePrefixFieldTitle="BU" ListSourcePrefixFieldInternalName="BU"/>
</CodificationTargetLibs>   
<AddWebParts>
 <AddWebPart Title="CodificationWebPart" RelativePageUrl="/sites/MC2Mig-DevSite/subsitec/subsitecdoclib/Forms/EditForm.aspx" WebPartPath="C:\JB\DeploymentScript\CodificationDeploymentScript\CodificationWebPart.webpart" ContentLink="/sites/MC2Mig-DevSite/Style%20Library/js/Codification.txt"/>    
</AddWebParts>
</Inputs>

Output
############################################################## Logging #########################################
  
$date= Get-Date -format MMddyyyyHHmmss 
start-transcript -path .\Log_$date.doc  

################################################### Get input parameters from XML ###############################  

$outChronoItems = New-Object System.Collections.Generic.List[System.Object]

$outCodificationItems = New-Object System.Collections.Generic.List[System.Object]

# Get content from XML file 
[xml]$xmlData=Get-Content ".\CodificationInputs.xml" 

# ConnectSPOnline node 
[System.Xml.XmlElement]$connectSPOnline = $xmlData.Inputs.ConnectSPOnline 
$siteURL=$connectSPOnline.SiteURL 
$userName=$connectSPOnline.UserName 
$password=$connectSPOnline.Password 

# ConnectSPConfigOnline node 
[System.Xml.XmlElement]$connectSPConfigOnline = $xmlData.Inputs.ConnectSPConfigOnline 
$siteConfigURL=$connectSPConfigOnline.SiteURL 
$userNameConfig=$connectSPConfigOnline.UserName 
$passwordConfig=$connectSPConfigOnline.Password 


#Get Codification Config list details
[System.Xml.XmlElement]$configCodificationList = $xmlData.Inputs.CodificationConfigList 
$configCodificationListTitle=$configCodificationList.Title
$configCodificationListUrl=$configCodificationList.URL
$configCodificationListTemplate=$configCodificationList.Template
$configCodificationListSourcePrefixColumnName=$configCodificationList.SourcePrefixColumnName
$configCodificationListSourcePostfixColumnName=$configCodificationList.SourcePostfixColumnName
$configCodificationListTargetColumnColumnName=$configCodificationList.TargetColumnColumnName
$configCodificationListFormatDigitColumnName=$configCodificationList.FormatDigitColumnName
$configCodificationListFormatDigitColumnValue=$configCodificationList.FormatDigitColumnValue
$configCodificationListWebUrlColumnName=$configCodificationList.WebUrlColumnName
$configCodificationListSiteUrlColumnName=$configCodificationList.SiteUrlColumnName
$configCodificationListLibraryColumnName=$configCodificationList.LibraryColumnName

# Codification Target Libs node 
[System.Xml.XmlElement]$codificationtargetlibs = $xmlData.Inputs.CodificationTargetLibs

# Target List Fields node 
#[System.Xml.XmlElement]$listfields = $xmlData.Inputs.ListFields

# Target Config List Fields node 
[System.Xml.XmlElement]$CodificationConfiglistfields = $xmlData.Inputs.CodificationConfigListFields

# Web Parts node 
[System.Xml.XmlElement]$webparts = $xmlData.Inputs.AddWebParts

#########Chrono
#Get Config list details
[System.Xml.XmlElement]$configChronoList = $xmlData.Inputs.ChronoConfigList 
$configChronoListTitle=$ConfigChronoList.Title
$configChronoListUrl=$ConfigChronoList.URL
$configChronoListTemplate=$ConfigChronoList.Template
$configListChronoFieldColumnName=$ConfigChronoList.ChronoFieldColumnName
$configListChronoFieldIncrementValue=$ConfigChronoList.ChronoIncrementValueColumnName

# Target Lists node 
[System.Xml.XmlElement]$chronotargetlists = $xmlData.Inputs.ChronoTargetLists

# Target List Fields node 
[System.Xml.XmlElement]$chronolistfields = $xmlData.Inputs.ListFields

# Target Config List Fields node 
[System.Xml.XmlElement]$ChronoConfiglistfields = $xmlData.Inputs.ChronoConfigListFields


########################################################## Get Credentials ######################################
 
function GetCredentials() 
{  
    try
                {
                write-host -ForegroundColor Green "Get Credentials and connect to SP Online site: " $siteURL 
    # Convert password to secure string   
    $secureStringPwd = ConvertTo-SecureString -AsPlainText $Password -Force 

    # Get the credentials 
    $credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName,$secureStringPwd  

    # Connect to SP online site 
    Connect-PnPOnline –Url $siteURL –Credentials $credentials                 
                }
                catch{
                write-host $_.Exception.Message;
                 }
               
}
function GetConfigCredentials()
{
    try
                {
   write-host -ForegroundColor Green "Get Credentials and connect to SP Online site for COnfig: " $siteConfigURL 
    # Convert password to secure string   
    $secureConfigStringPwd = ConvertTo-SecureString -AsPlainText $passwordConfig -Force 

    # Get the credentials 
    $credentialsConfig = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userNameConfig,$secureConfigStringPwd  

    # Connect to SP online site 
    Connect-PnPOnline –Url $siteConfigURL –Credentials $credentialsConfig 
   }
                catch{
                write-host $_.Exception.Message;
                 }  
}

#######################################################  Create Codification Configuration List#############################

function CreateCodificationConfigList() 
                try
                {
                                write-host -ForegroundColor Green "Creating Codification Config List"   

                                $getConfigList=Get-PnPList -Identity $configCodificationListUrl

        # Check if list exists 
        if($getConfigList) 
        { 
           write-host -ForegroundColor Magenta $listURL " - Codification Config List already exists"                                                                                                                                      
                                }
        else 
        { 
           # Create new list           
                                   write-host -ForegroundColor Magenta "Creating Codification Config list: " $configCodificationListUrl          
                                   New-PnPList -Title $configCodificationListTitle -Url $configCodificationListUrl -Template $configCodificationListTemplate                
                                   
        } 
                }  
                catch
                {
                write-host $_.Exception.Message;
                }
     
}
#################################################################Create Configuration List Fields#####################################
function CreateCodificationConfigListFields() 
    try
                {
                                write-host -ForegroundColor Green "Creating Codification Config List Fields" 

                                # Loop through List Fields XML node 
                                foreach($CodificationConfiglistfield in $CodificationConfiglistfields.CodificationConfigListField)
                                {
                   
                                                # Get List Field node parameters                                             
                                                $CodificationConfiglistfieldTitle=$CodificationConfiglistfield.Title
                                                $CodificationConfiglistfieldinternalname=$CodificationConfiglistfield.InternalName
                                                $CodificationConfiglistfieldgroup=$CodificationConfiglistfield.Group    
                                                $CodificationConfiglistfieldtype=$CodificationConfiglistfield.Type
                                               
                                                $getConfigListFields=Get-PnPField -List $configCodificationListUrl
                                                foreach($field in $getConfigListFields)
                                                {
                                                if($field.InternalName -eq $CodificationConfiglistfieldinternalname)
                                                {
                                                                $tag=$tag+1;
                                                }
                                                }
                                                if($tag)
                                                {
                                                                write-host -ForegroundColor Magenta $CodificationConfiglistfieldTitle "-List Field Already exists"
                                                }
                                                else
                                                {
                                                               
                                                                Add-PnPField -List $configCodificationListTitle -DisplayName $CodificationConfiglistfieldTitle -InternalName $CodificationConfiglistfieldinternalname -Type $CodificationConfiglistfieldtype -Group $CodificationConfiglistfieldgroup -AddToDefaultView
                                                }                             
                               
                               
                                }
                }
                catch
                {
                write-host $_.Exception.Message;
                }
   
}
function HideCodificationConfiglist()
{
                try
                {
                                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
                                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")

                                write-host -ForegroundColor Green "Get Credentials and connect to SP Online Root site: " $siteConfigURL 
                                # Convert password to secure string   
                                $secureStringConfigPwd = ConvertTo-SecureString -AsPlainText $passwordConfig -Force

                                #Setup Credentials to connect
                                $credentialsConfig = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userNameConfig,$secureStringConfigPwd)

                                #Set up the context
                                $context = New-Object Microsoft.SharePoint.Client.ClientContext($siteConfigURL)
                                $context.Credentials = $credentialsConfig

                                #Get the List
                                $list = $context.Web.Lists.GetByTitle($configCodificationListTitle)
                                $list.Hidden = $true
                                $list.Update()
                                $context.ExecuteQuery()
                                Write-Host "List Hidden Successfully!"
                }
                catch
                {
                write-host $_.Exception.Message;
                }

}
#################################################################################################################

#################################################################Create Target Lib#####################################  
function CreateTargetLibs() 
{
                try
                { 
                                write-host -ForegroundColor Green "Creating Target Libs"  
                 
                                # Loop through List XML node 
                                foreach($codificationtargetlib in $codificationtargetlibs.CodificationTargetLib) 
                                { 
                                                # Get List node parameters 
                                                $listTitle=$codificationtargetlib.Title 
                                                $listURL=$codificationtargetlib.URL 
                                                $listTemplate=$codificationtargetlib.Template 
                                                $listItemTemplate=$codificationtargetlib.ContentType
                                                #$listFieldTitle=$list.ListFieldTitle
                                                #$listFieldInternalName=$list.ListFieldInternalName
                                                $listFieldGroup=$codificationtargetlib.ListFieldGroup
                                               
                                                #
                                                $listSourcePostfixFieldTitle=$codificationtargetlib.ListSourcePostfixFieldTitle
                                                $listSourcePostfixFieldInternalName=$codificationtargetlib.ListSourcePostfixFieldInternalName
                                               
                                                $listTargetColumnFieldTitle=$codificationtargetlib.ListTargetColumnFieldTitle
                                                $listTargetColumnFieldInternalName=$codificationtargetlib.ListTargetColumnFieldInternalName
                                               
                                                $listSourcePrefixFieldTitle=$codificationtargetlib.ListSourcePrefixFieldTitle
                                                $listSourcePrefixFieldInternalName=$codificationtargetlib.ListSourcePrefixFieldInternalName
                                               
                                                #write-host $listSourcePrefixFieldTitle
                                               
                                                # Get the list object 
                                                $getList=Get-PnPList -Identity $listURL
                                                $getListFields=Get-PnPField -List $listTitle                                          
                                               
                                                # Check if list exists 
                                                if($getList) 
                                                { 
                                                   write-host -ForegroundColor Magenta $listURL " - List already exists"                                                                                                      
                                                   $listGUID=Get-PnPList -Identity $listURL                                             
                                                   
                                                   #$outCodificationItems.Add($listGUID.Id.ToString()+";"+$listFieldTitle)                                                              
                                                   #$outCodificationItems.Add($listGUID.Id.ToString()+";"+$listFieldTitle+":"+$listSourcePostfixFieldTitle+"@"+$listTargetColumnFieldTitle)                                                                  
                                                   #$outCodificationItems.Add($listGUID.Id.ToString()+";"+$listSourcePrefixFieldTitle+":"+$listSourcePostfixFieldTitle+"@"+$listTargetColumnFieldTitle)                                                                  
                                                   $outCodificationItems.Add($listGUID.Id.ToString()+";"+$listTitle);                                                         
                                                   $outCodificationItems.ToArray()                                            

                                                   if($listTemplate -eq "DocumentLibrary")
                                                   {
                                                                                write-host $listTitle "is a document library"                                                       
                                                                                $doclb=Set-PnPList -Identity $listURL -EnableContentTypes $true
                                                   }
                                                } 
                                                else 
                                                { 
                                                   # Create new list 
                                                   write-host -ForegroundColor Magenta "Target library is not available: " $listURL
                                                   exit                       
                                                }
                                                #SourcePrefix
                                                foreach($field in $getListFields)
                                                {                                             
                                                if($field.InternalName -eq $listSourcePrefixFieldInternalName)
                                                {
                                                                $tag=$tag+1;
                                                }                                             
                                                }
                                                if($tag)
                                                {
                                                                write-host -ForegroundColor Magenta $listSourcePrefixFieldTitle "-List Field Already exists"
                                                }
                                                else
                                                {
                                                                $fielditem=Add-PnPField -List $listTitle -DisplayName $listSourcePrefixFieldTitle -InternalName $listSourcePrefixFieldInternalName -Type Text -Group $listfieldgroup -AddToDefaultView -Required                                               
                                                }
                                               
                                                #SourcePostfix
                                                foreach($field in $getListFields)
                                                {                                             
                                                if($field.InternalName -eq $listSourcePostfixFieldInternalName)
                                                {
                                                                $tag=$tag+1;
                                                }                                             
                                                }
                                                if($tag)
                                                {
                                                                write-host -ForegroundColor Magenta $listSourcePostfixFieldTitle "-List Field Already exists"
                                                }
                                                else
                                                {
                                                                $fielditem=Add-PnPField -List $listTitle -DisplayName $listSourcePostfixFieldTitle -InternalName $listSourcePostfixFieldInternalName -Type Text -Group $listfieldgroup -AddToDefaultView -Required                                               
                                                }
                                               
                                                #TargetColumn
                                                foreach($field in $getListFields)
                                                {                                             
                                                if($field.InternalName -eq $listTargetColumnFieldInternalName)
                                                {
                                                                $tag=$tag+1;
                                                }                                             
                                                }
                                                if($tag)
                                                {
                                                                write-host -ForegroundColor Magenta $listTargetColumnFieldTitle "-List Field Already exists"
                                                }
                                                else
                                                {
                                                                $fielditem=Add-PnPField -List $listTitle -DisplayName $listTargetColumnFieldTitle -InternalName $listTargetColumnFieldInternalName -Type Text -Group $listfieldgroup -AddToDefaultView -Required                                               
                                                }
                                               
                                }
                }             
                catch
                {
                write-host $_.Exception.Message;
                }
}
function AddListGUIDsToCodificationConfigLIst() 
{
                try
                {
                               
                                foreach($outCodificationItem in $outCodificationItems)
                                {
                                                                                $semicolonpos=$outCodificationItem.IndexOf(";")        
                                                                                $listCodificationGUIDvalue=$outCodificationItem.Substring(0, $semicolonpos)
                                                                                $targetLibName=$outCodificationItem.Substring($semicolonpos+1)                                                                     
                                                                                $listCodificationGUIDvaluearr="{"+$listCodificationGUIDvalue+"}"
                                                                                Write-Host $listCodificationGUIDvaluearr
                                                                               
                                                                $spCodificationQuery="<View Scope=`"RecursiveAll`"><Query><Where><Eq><FieldRef
                                                                Name = 'Title'/><Value Type ='Text'>"+$listCodificationGUIDvaluearr+"</Value></Eq></Where></Query></View>"                               
                                                               
                                                               
                                                                $listCodificationItems = Get-PnPListItem -List $configCodificationListUrl -Query $spCodificationQuery                                                  
                               
                                                                write-host $listCodificationItems.Count               

                                                                $listCodificationItemsCount=$listCodificationItems.Count                                                                                         
                                                                if($listCodificationItemsCount -eq 0)
                                                                {
                                                                                write-host -ForegroundColor Green "Adding Target Library details to Codification Config List"              
                                                                                $newItem = Add-PnPListItem -List $configCodificationListTitle                                                 
                                                                                $itmfield=Set-PnPListItem -List $configCodificationListTitle -Identity $newItem -Values @{"Title" = $listCodificationGUIDvaluearr;$configCodificationListWebUrlColumnName=$siteURL;$configCodificationListSiteUrlColumnName=$siteConfigURL;$configCodificationListFormatDigitColumnName=$configCodificationListFormatDigitColumnValue;$configCodificationListLibraryColumnName=$targetLibName}                                               
                                                                }
                                                                elseif($listCodificationItemsCount -eq 1)
                                                                {
                                                                                write-host -ForegroundColor Magenta $listCodificationGUIDvaluearr "Already Exists"
                                                                }             
                               
                                }             
                                                               
                               
                }
                catch
                {
                write-host $_.Exception.Message;
                }

}
#################################################################################################################

#################################################################Add the Web Parts #####################################
function AddWebPart()
{
                try
                {
                                write-host -ForegroundColor Green "Adding Web Parts"               
                               
                                # Loop through Web Parts XML node 
                                foreach($webpart in $webparts.AddWebPart) 
                                {
                                                $webPartRelativePageUrl=$webpart.RelativePageUrl
                                                $webPartPath=$webpart.WebPartPath
                                                $webPartTitle=$webpart.Title
                                                $webPartContentLink=$webpart.ContentLink
                                                $getwebpart=Get-PnPWebPart -ServerRelativePageUrl $webPartRelativePageUrl -Identity $webPartTitle                                                  
                                                if($getwebpart)
                                                {
                                                write-host -ForegroundColor Magenta $webPartTitle "-Web Part Already exists"
                                                $webpart = Get-PnPWebPart -ServerRelativePageUrl $webPartRelativePageUrl -Identity $webPartTitle                  
                                                $webpartId=$webpart.Id                            
                                                Set-PnPWebPartProperty -ServerRelativePageUrl $webPartRelativePageUrl -Identity $webpartId -Key ContentLink -Value $webPartContentLink                        
                                                write-host -ForegroundColor Magenta $webPartTitle "-Web Part ContentLink has been updated"
                                                }
                                                else
                                                {
                                                Add-PnPWebPartToWebPartPage -ServerRelativePageUrl $webPartRelativePageUrl -Path $webPartPath -ZoneId "Header" -ZoneIndex 1                  
                                                write-host -ForegroundColor Magenta $webPartTitle "-Web Part has been Added"                       
                                                $webpart = Get-PnPWebPart -ServerRelativePageUrl $webPartRelativePageUrl -Identity $webPartTitle                  
                                                $webpartId=$webpart.Id
                                                Set-PnPWebPartProperty -ServerRelativePageUrl $webPartRelativePageUrl -Identity $webpartId -Key ContentLink -Value $webPartContentLink                        
                                                write-host -ForegroundColor Magenta $webPartTitle "-Web Part ContentLink has been updated"                           
                                                }
                                }
                }
                catch
                {
                write-host $_.Exception.Message;
                }
                               
}
#######################################################  Create Configuration List#############################

function CreateChronoConfigList() 
                try
                {
                                write-host -ForegroundColor Green "Creating Chrono Config List"   

                                $getChronoConfigList=Get-PnPList -Identity $configChronoListUrl

        # Check if list exists 
        if($getChronoConfigList) 
        { 
           write-host -ForegroundColor Magenta $configChronoListUrl " - Chrono Config List already exists"                                                                                                                                  
                                }
        else 
        { 
           # Create new list           
                                   write-host -ForegroundColor Magenta "Creating Chrono Config list: " $configChronoListUrl          
                                   New-PnPList -Title $configChronoListTitle -Url $configChronoListUrl -Template $configChronoListTemplate         
                                   
        } 
                }  
                catch
                {
                write-host $_.Exception.Message;
                }
     
}
#################################################################################################################
#################################################################Create Chrono Configuration List Fields#####################################
function CreateChronoConfigListFields() 
    try
                {
                                write-host -ForegroundColor Green "Creating Chrono Config List Fields" 

                                # Loop through List Fields XML node 
                                foreach($ChronoConfiglistfield in $ChronoConfiglistfields.ChronoConfigListField)
                                {
                   
                                                # Get List Field node parameters                                             
                                                $ChronoConfiglistfieldTitle=$ChronoConfiglistfield.Title
                                                $ChronoConfiglistfieldinternalname=$ChronoConfiglistfield.InternalName
                                                $ChronoConfiglistfieldgroup=$ChronoConfiglistfield.Group       
                                                $ChronoConfiglistfieldtype=$ChronoConfiglistfield.Type
                                               
                                                $getChronoConfigListFields=Get-PnPField -List $configChronoListUrl
                                                foreach($field in $getChronoConfigListFields)
                                                {
                                                if($field.InternalName -eq $ChronoConfiglistfieldinternalname)
                                                {
                                                                $tag=$tag+1;
                                                }
                                                }
                                                if($tag)
                                                {
                                                                write-host -ForegroundColor Magenta $ChronoConfiglistfieldTitle "-List Field Already exists"
                                                }
                                                else
                                                {
                                                               
                                                                Add-PnPField -List $configChronoListTitle -DisplayName $ChronoConfiglistfieldTitle -InternalName $ChronoConfiglistfieldinternalname -Type $ChronoConfiglistfieldtype -Group $ChronoConfiglistfieldgroup -AddToDefaultView
                                                }                             
                               
                               
                                }
                }
                catch
                {
                write-host $_.Exception.Message;
                }
   
}
function HideChronoConfiglist()
{
                try
                {
                                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
                                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")

                                write-host -ForegroundColor Green "Get Credentials and connect to SP Online Root site: " $siteConfigURL 
                                # Convert password to secure string   
                                $secureStringConfigPwd = ConvertTo-SecureString -AsPlainText $passwordConfig -Force

                                #Setup Credentials to connect
                                $credentialsConfig = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userNameConfig,$secureStringConfigPwd)

                                #Set up the context
                                $context = New-Object Microsoft.SharePoint.Client.ClientContext($siteConfigURL)
                                $context.Credentials = $credentialsConfig

                                #Get the List
                                $list = $context.Web.Lists.GetByTitle($configCodificationListTitle)
                                $list.Hidden = $true
                                $list.Update()
                                $context.ExecuteQuery()
                                Write-Host "Chrono Config List Hidden Successfully!"
                }
                catch
                {
                write-host $_.Exception.Message;
                }

}
#################################################################Create Target Chrono Lists#####################################  
function CreateTargetLists() 
{
                try
                { 
                                write-host -ForegroundColor Green "Creating Target Lists"  
                 
                                # Loop through List XML node 
                                foreach($chronotargetlist in $chronotargetlists.ChronoTargetList) 
                                { 
                                                # Get List node parameters 
                                                $listChronoTitle=$chronotargetlist.Title 
                                                $listChronoURL=$chronotargetlist.URL 
                                                $listChronoTemplate=$chronotargetlist.Template 
                                                $listItemChronoTemplate=$chronotargetlist.ContentType
                                                $listChronoFieldTitle=$chronotargetlist.ListFieldTitle
                                                $listChronoFieldInternalName=$chronotargetlist.ListFieldInternalName
                                                $listChronoFieldGroup=$chronotargetlist.ListFieldGroup            
                                                $listChronoFieldIncrementValue=$chronotargetlist.ListFieldIncrementValue                                    
                                               
                                               
                                               
                                                # Get the list object 
                                                $getChronoList=Get-PnPList -Identity $listChronoURL
                                                $getChronoListFields=Get-PnPField -List $listChronoTitle                                            
                                               
                                                # Check if list exists 
                                                if($getChronoList) 
                                                { 
                                                   write-host -ForegroundColor Magenta $listChronoURL " - List already exists"                                                                                                     
                                                   $listGUID=Get-PnPList -Identity $listChronoURL                                                               
                                                   
                                                   
                                                   $outChronoItems.Add($listGUID.Id.ToString()+";"+$listChronoFieldTitle+":"+$listChronoFieldIncrementValue);                                                                  
                                                   $outChronoItems.ToArray()                                      

                                                   if($listTemplate -eq "DocumentLibrary")
                                                   {
                                                                                write-host $listChronoTitle "is a document library"                                                        
                                                                                $doclb=Set-PnPList -Identity $listChronoURL -EnableContentTypes $true
                                                   }
                                                } 
                                                else 
                                                { 
                                                   # Create new list 
                                                   write-host -ForegroundColor Magenta "Target list is not available: " $listChronoURL
                                                   exit                       
                                                }
                                                foreach($field in $getChronoListFields)
                                                {                                             
                                                if($field.InternalName -eq $listChronoFieldInternalName)
                                                {
                                                                $tag=$tag+1;
                                                }                                             
                                                }
                                                if($tag)
                                                {
                                                                write-host -ForegroundColor Magenta $listChronoFieldTitle "-List Field Already exists"
                                                }
                                                else
                                                {
                                                                $fielditem=Add-PnPField -List $listChronoTitle -DisplayName $listChronoFieldTitle -InternalName $listChronoFieldInternalName -Type Number -Group $listChronoFieldGroup -AddToDefaultView -Required                                            
                                                }                                             
                                               
                                }
                }             
                catch
                {
                write-host $_.Exception.Message;
                }
}
function AddListGUIDsToChronoConfigLIst() 
{
                try
                {
                                foreach($outChronoItem in $outChronoItems)
                                {
                                                $semicolonpos=$outChronoItem.IndexOf(";") 
                                                $colonpos=$outChronoItem.IndexOf(":")           
                                                $listChronoGUIDvalue=$outChronoItem.Substring(0, $semicolonpos)                                  
                                                $chronofieldpattern= ";(.*):"                    
                                                $chronoFieldValue=[regex]::match($outChronoItem, $chronofieldpattern).Groups[1].Value                                                               
                                                $chronoFieldIncrementValue=$outChronoItem.Substring($colonpos+1)                                              
                                                $listChronoGUIDvaluearr="{"+$listChronoGUIDvalue+"}"
                                               
                                                $spChronoQuery="<View Scope=`"RecursiveAll`"><Query><Where><Eq><FieldRef
                                                                Name = 'Title'/><Value Type ='Text'>"+$listChronoGUIDvaluearr+"</Value></Eq></Where></Query></View>"                                        
                                                               
                                                                $listChronoItems = Get-PnPListItem -List $configChronoListUrl -Query $spChronoQuery
                                                               
                                                                $listChronoItemsCount=$listChronoItems.Count             
                                                               
                                                                if($listChronoItemsCount -eq 0)
                                                                {
                                                                                $newItem = Add-PnPListItem -List $configChronoListTitle                           
                                                                                $itmfield=Set-PnPListItem -List $configChronoListTitle -Identity $newItem -Values @{"Title" = $listChronoGUIDvaluearr; $configListChronoFieldColumnName = $chronoFieldValue; $configListChronoFieldIncrementValue=$chronoFieldIncrementValue}                                
                                                                }
                                                                elseif($listChronoItemsCount -eq 1)
                                                                {
                                                                                write-host -ForegroundColor Magenta $listChronoGUIDvaluearr "Already Exists"
                                                                }

                                                                               
                                }                             
                               
                }
                catch
                {
                write-host $_.Exception.Message;
                }

}

#################################################################################################################
function SetClassicExperience()
{
                                try
                                {
                                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
                                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")                                
                               
                                $secureStringPwd = ConvertTo-SecureString -AsPlainText $password -Force
                               
                                #Setup Credentials to connect
                                $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName,$secureStringPwd)
                               
                                #Set up the context
                                $clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
                                $clientContext.Credentials = $credentials                           
                                $lists=$clientContext.Web.Lists
                                $clientContext.Load($lists)
                                $clientContext.ExecuteQuery()
                                foreach($list in $lists)
                                                {
                                                                                                               
                                                                foreach($codificationtargetlib in $codificationtargetlibs.CodificationTargetLib) 
                                                                {
                                                                                # Get List node parameters 
                                                                                $codificationdocLibTitle=$codificationtargetlib.Title 
                                                                                #write-host $codificationdocLibTitle
                                                                                if($list.Title -eq $codificationdocLibTitle)
                                                                                {
                                                                                                $list.ListExperienceOptions = "ClassicExperience"
                                                                                                $list.Update()
                                                                                                $clientContext.ExecuteQuery()
                                                                                                write-host -ForegroundColor Green "Classic Experience has been applied to"$list.Title
                                                                                }
                                                                               
                                                                }
                                                }
                                }
                                catch
                                                {
                                                                write-host $_.Exception.Message;
                                                }

}


#################################################################  Initiate #####################################
 
function Initiate() 
     write-host -ForegroundColor Green "Initiating the script.................. "  

     # Get Credentials and connect to SP Online site    
                 GetConfigCredentials    
     # Call the required functions 
                 CreateChronoConfigList             
                CreateChronoConfigListFields
                #HideChronoConfiglist                 
     CreateCodificationConfigList
                CreateCodificationConfigListFields        
                 #HideCodificationConfiglist      
                 GetCredentials
                CreateTargetLists                            
                 GetConfigCredentials   
                 AddListGUIDsToChronoConfigLIst         
                 GetCredentials
                CreateTargetLibs
                GetConfigCredentials
                AddListGUIDsToCodificationConfigLIst
                 GetCredentials
                AddWebPart
                SetClassicExperience

     # Disconnect from the server 
     Disconnect-PnPOnline 
  
     write-host -ForegroundColor Green "Completed!!!!"  

#################################################################################################################
 
Initiate 

Stop-Transcript  
1/Chrono Configuration list with required columns and values






2/ Codification Configuration list with required columns and values