UpdateWebResoures.ps1


<#PSScriptInfo
 
.VERSION 1.0
 
.GUID ee407f00-467b-44f6-997c-aeea8fff60b5
 
.AUTHOR kai9kor
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
#>


<#
 
.DESCRIPTION
 testing
 
#>
 

Param()


 param(
[parameter(Mandatory=$true, Position=1)]
[string]$ConnString,
[parameter(Mandatory=$true, Position=2)]
[string]$WebReourceFolderPath,
[parameter(Mandatory=$true, Position=3)]
[string]$InputFilePath
)

<#
$WebReourceFolderPath = "C:\V1.0\src\CRM\MCSHHS.D365.CE\MCSHHS.D365.CE.Package";
$InputFilePath = "C:\Users\kai9kor\Desktop\trash\WebResourcesDeploy\WebResourceRegistryFile.xml";
$ConnString =
Install the microsoft.xrm.data.powershell modeule and create connection to instance
#>

$Module = Get-InstalledModule -Name "Microsoft.Xrm.Data.Powershell" -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
if($Module -ne $null)
{
    Write-host "Module is already installed!!!!, `nModule details:";
    $Module | Format-Table -Wrap 
 }
else
{
    Write-host "Module is not installed,`nInstalling Module('Microsoft.Xrm.Data.Powershell')...";
    Install-Module -Name Microsoft.Xrm.Data.Powershell -Force -Scope CurrentUser -Verbose
    Write-host "Module('Microsoft.Xrm.Data.Powershell') is installed successfully....";
}

$ServiceConn = Get-CrmConnection -ConnectionString $ConnString -WarningAction SilentlyContinue -ErrorAction SilentlyContinue


function CreateWebResource{
    param(
        [parameter(Mandatory=$true, Position=1)]
        [string]$Name,
        [parameter(Mandatory=$true, Position=2)]
        [string]$DisplayName,
        [parameter(Mandatory=$false, Position=3)]
        [string]$Description,
        [parameter(Mandatory=$true, Position=4)]
        [int]$WRType,
        [parameter(Mandatory=$true, Position=5)]
        [string]$Content,
        [parameter(Mandatory=$false, Position=6)]
        [int]$LanguageCode,
        [parameter(Mandatory=$true, Position=7)]
        [Microsoft.Xrm.Tooling.Connector.CrmServiceClient]$Conn
    )
    $webSrc =  New-Object Microsoft.Xrm.Sdk.Entity("webresource");
    $webSrc.Attributes["name"] = $Name;
    $webSrc.Attributes["displayname"] = $DisplayName;
    $webSrc.Attributes["description"] = $Description;
    $webSrc.Attributes["webresourcetype"] = [Microsoft.Xrm.Sdk.OptionSetValue] $WRType;
    $webSrc.Attributes["languagecode"] = $LanguageCode;
    # Set the content of the webresource languagecode
    $webSrc.Attributes["content"] = $content;
           
    $Conn.Create($webSrc);
}
function UpdateWebResource{
    param(
        [parameter(Mandatory=$true, Position=1)]
        [string]$WRId,
        [parameter(Mandatory=$true, Position=2)]
        [string]$DisplayName,
        [parameter(Mandatory=$false, Position=3)]
        [string]$Description,
        [parameter(Mandatory=$true, Position=3)]
        [string]$Content,
        [parameter(Mandatory=$false, Position=4)]
        [int]$LanguageCode,
        [parameter(Mandatory=$true, Position=5)]
        [Microsoft.Xrm.Tooling.Connector.CrmServiceClient]$Conn
    )

    $webSrc =  New-Object Microsoft.Xrm.Sdk.Entity("webresource");
    $webSrc.Id = $WRId;
    $webSrc.Attributes["displayname"] = $DisplayName;
    $webSrc.Attributes["description"] = $Description;
    $webSrc.Attributes["languagecode"] = $LanguageCode;

    # $webSrc.Attributes["name"] = "new_testwebR001"
    # $webSrc.Attributes["webresourcetype"] = [Microsoft.Xrm.Sdk.OptionSetValue] $WRType;
  
    # update the content of the webresource
    $webSrc.Attributes["content"] = $Content;
           
    $Conn.Update($webSrc);

}
$WebResourceTypes =@{
HTM = 1;
HTML = 1;
CSS = 2;    
JS = 3;    
XML = 4;            
PNG = 5;
JPG = 6;
GIF = 7;
XAP = 8;
XSL = 9;
ICO = 10;
SVG = 11;
RESX = 12
}

Measure-Command  {



[xml]$WebResourcesList = Get-Content $InputFilePath



foreach($Webresource in $WebResourcesList.WebResources.CRMWebResource)
{
    $RepoContent = "";
    $FilePath = $Webresource.Include 
    $DisplayName = $Webresource.DisplayName
    $UniqueName = $Webresource.UniqueName
    $Description = @{$true=$Webresource.Description ;$false=""}[$Webresource.Description -ne $null] 
    Write-Host "###############-----Deploying the webresource '$UniqueName'-----###############`n"

    $WebResourceType = $Webresource.WebResourceType
    Write-Verbose  "Details: $FilePath $DisplayName $UniqueName $Extension $WebResourceType "
    
    # get content from repo
    $RepoFilePath = "$WebReourceFolderPath\$FilePath";
    $RepoFilePath  = [System.Web.HttpUtility]::UrlDecode($RepoFilePath);
    #if([System.IO.File]::Exists($RepoFilePath)){ write-host "found"};
   $IsFileExists = Test-Path -Path $RepoFilePath;
    if($IsFileExists){
    $RepoContent = Get-Content "$RepoFilePath" # -Raw -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
    $Extension = [System.IO.Path]::GetExtension($RepoFilePath).replace(".",""); 
   if($RepoContent -ne $null -and $RepoContent -ne ""){
   # $contentBytes = [System.Text.Encoding]::UTF8.GetBytes($RepoContent);
  # $base64Converted = [System.Convert]::ToBase64String($contentBytes);

    $base64Converted= [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($RepoFilePath))
     $base64String -eq $base64Converted 
$WRFetch = @"
<fetch>
    <entity name="webresource" >
    <attribute name="organizationid" />
    <attribute name="languagecode" />
    <attribute name="description" />
    <attribute name="webresourceidunique" />
    <attribute name="content" />
    <attribute name="solutionid" />
    <attribute name="componentstate" />
    <attribute name="displayname" />
    <attribute name="name" />
    <attribute name="webresourceid" />
    <attribute name="webresourcetype" />
    <attribute name="organizationidname" />
    <attribute name="webresourcetypename" />
    <filter>
        <condition attribute="name" operator="eq" value="$UniqueName" />
    </filter>
    </entity>
</fetch>
"@

    $WRFetchExpr = New-Object  Microsoft.Xrm.Sdk.Query.FetchExpression($WRFetch);

    # Retrieve webresource from instance
 # $WebResourceQuery = New-Object Microsoft.Xrm.Sdk.Query.QueryExpression("webresource");

    $WebResourceRecords = $Conn.RetrieveMultiple($WRFetchExpr);

    if($WebResourceRecords.Entities.Count -gt 0)
    {
        Write-Host "Web Resource ('$UniqueName') is existing in target."
        $WRId = $WebResourceRecords.Entities[0].Id;
        $WRName = $WebResourceRecords.Entities[0].Attributes["name"];
        $Base64SourceContent = $WebResourceRecords.Entities[0].Attributes["content"];
        <#
        $SourceContentBytes = [System.Convert]::FromBase64String($Base64SourceContent);
        $DecodedSourceContent = [System.Text.Encoding]::UTF8.GetString($SourceContentBytes);
        #>

        
        # if($RepoContent.ToString() -ne $DecodedSourceContent.ToString())
        if( $base64Converted -ne $Base64SourceContent)
        {
            try
            {
             Write-Host "Web Resource ('$UniqueName') is updating..."
             $response = UpdateWebResource -WRId $WRId -DisplayName $DisplayName -Description $Description  -Content $base64Converted -LanguageCode "1033" -Conn $Conn
             Write-Host "Web Resource ('$UniqueName') is updated successfully."
            }
            catch{
            Write-Warning "Unable to update the webresource ('$UniqueName')"
            Write-Warning $_.Exception.Message
            }
        }
        else
        {
            Write-Host "No change is found in existing code to update for '$UniqueName'"
        }
    }
    else
    { 
 
        $Wrtype = [int]$WebResourceTypes.($Extension)
        try{
        $response =  CreateWebResource -Name "$UniqueName" -DisplayName "$DisplayName" -Description $Description  -WRType $Wrtype -Content $base64Converted -LanguageCode "1033" -Conn $Conn
        Write-Host "Web Resource ('$UniqueName') is created successfully with Id: $response ."
        }
        catch{
        Write-Warning "Unable to create the webresource ('$UniqueName')"
        Write-Warning $_.Exception.Message
        }
    }
    }
    else 
    {
         Write-Warning "No data found in file !!!`nFile Path: $RepoFilePath "
         Write-Warning "Skipped the web resource ('$UniqueName')."
    }
    }
    else
    {
        Write-Warning "File path does not exists !!!"
    }

    Write-Host "`n###############-----Deploy the webresource '$UniqueName' is complete-----###############`n"
}
Write-Host "Time taken for webreources deployment is:`n"
}
Write-Host "Publishing all customizations !!!`n";
Measure-Command{
$publishRequest = New-Object Microsoft.Crm.Sdk.Messages.PublishAllXmlRequest;
#$Conn.Execute($publishRequest);
Write-Host "Successfully published all customizations`nTime taken:";
}