How to read XML file in Dynamics CRM 2011 using Javascript

In Dynamics CRM 2011, we could maintain the XML files using web resource utility, which is a very good feature. It could be read using Javascript which is also maintained in the web resources of Dyanmics CRM 2011.You could make use of this feature when you want to populate some values dynamically.

Sample xml file –Settings.xml

<Configurations>
<Configuration id=”License”>54383-32343-213-22-2-21232-1222</Configuration>
<Configuration id=”Name”>Client 1</Configuration>
</Configurations>


Javascript sample code to read XML File:

var xmlPath = "../WebResources/Settings.xml";
 
var xmlnodePath = "//Configurations/Configuration";
var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
xmldoc.preserveWhiteSpace = true;
xmldoc.async = false;
xmldoc.load(xmlPath);
var params = new Array();
var xmlnodelist;
xmlnodelist= xmldoc.selectNodes(xmlnodePath);
for (var i = 0; i < xmlnodelist.length; i++)
{
     params[i] = xmlnodelist(i).attributes[0].value;
}

PowerShell

imagesSono due giorni che sto “smanettando” con powershell: Sto creando una poweshell per importare i contatti Lync (Migrazione da Lync 2010 a Lync2013). Per risolvere il problema ho dovuto crearmi una lista di utenti lync e ciclare su ogni utente. Per ognuno ho dovuto creare un file zip, modificare un file xml e poi eseguire un altro comando della powershell di lync.

Dato che non sono molto pratico di powershell ho cercato un po’ su internet e alla fine sono riuscito a creare tutto quello che mi serviva, senza importare nessuna libreria esterna ma utilizzando la potenza di powershell. Vediamo come ho risolto il tutto:
Per iniziare mi sono creato dei metodi base per la gestione degli zip, delle cartelle e del file xml:
In questo post vedremo questo. Magari in futuro vi faro’ vedere i comandi lync… 🙂

Prima di tutto ho creato delle cartelle temporanee per poter lavorare in tranquillita’:

#Tmp dir
$folderTmp = "C:\TmpLync\"
$folderTmpContact = "C:\TmpLync\Contacts"
#********************************************************************************************************************************************
#Start TMP FOLDER
#********************************************************************************************************************************************
#Clean and create all tmp dir
if (!(Test-Path $folderTmp)) {
# create it
[void](new-item $folderTmp -itemType directory)
}
if (!(Test-Path $folderTmpContact)) {
# create it
[void](new-item $folderTmpContact -itemType directory)
}

Poi ho creato le funzioni per zippare ed unzippare cartelle

function UnZipMe($zipfilename,$destination)
{
   $shellApplication = new-object -com shell.application
   $zipPackage = $shellApplication.NameSpace($zipfilename)
   $destinationFolder = $shellApplication.NameSpace($destination)
	# CopyHere vOptions Flag # 4 - Do not display a progress dialog box.
	# 16 - Respond with "Yes to All" for any dialog box that is displayed.
	$destinationFolder.CopyHere($zipPackage.Items(),20)
}

function ZipMe($srcdir,$ZipFileName,$zipFilepath )
{
		$zipFile = "$zipFilepath$zipFilename"
		#Prepare zip file
		if(-not (test-path($zipFile))) {
		    set-content $zipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
		    (dir $zipFile).IsReadOnly = $false
		}

		$shellApplication = new-object -com shell.application
		$zipPackage = $shellApplication.NameSpace($zipFile)
		$files = Get-ChildItem -Path $srcdir | where{! $_.PSIsContainer}

		foreach($file in $files) {
		    $zipPackage.CopyHere($file.FullName)
			#using this method, sometimes files can be 'skipped'
			#this 'while' loop checks each file is added before moving to the next
		    while($zipPackage.Items().Item($file.name) -eq $null){
		        Start-sleep -seconds 1
		    }
		}
}

L’utilizzo di queste due funzioni e’ semplicissimo:
Per unzippare:

$zipFilename = "contacts.zip"
$a = gci -Path $folderTmpContact -Filter $zipFilename
foreach($file in $a)
{
    Write-Host "Processing - $file" UnZipMe –zipfilename
    UnZipMe –zipfilename $file.FullName -destination $file.DirectoryName
}

Per zippare:

$srcdir = $folderTmpContact
$zipFilepath = $folderTmp
ZipMe -srcdir $srcdir -zipFileName $ZipFileName -zipFilePath $zipFilepath

La parte piu’ complessa e’ stata la gestione e la modifica del file XML: Ho provato ad utilizzare i comandi standard per leggere un file xml:

$xml = New-Object XML
$xml = [xml](get-content "c:\test\DocItemSet.xml")
$email = $xml.DocItemSet.DocItem[0].name

Ma la stringa da ricercare non aveva logica e il file xml poteva cambiare. Alla fine ho deciso di utilizzare una semplice ricerca e modifica:

$original_file = "c:\test\DocItemSet.xml"
$destination_file =  "c:\test\DocItemSet.xml.new"
(Get-Content $original_file) | Foreach-Object {
    $_ -replace $email, 'something1aa'
    } | Set-Content $destination_file

In questo modo ricerco, modifico e faccio anche un backup del file.
Per lavorare e per debuggare poweshell ho utilizzato PowerGUI mentre per un ottimo punto di partenza per powershell consiglio questi link:

http://powershell.com/
http://powershell.it/Comandi/v1.0/Get-Content.aspx
http://powershell.it/Tutorial/Introduzione-a-PowerShell.aspx

NB: Se abbiamo il seguente errore File xyz.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see “get-help about_signing” for more details. Esesguiamo la console powershell ed eseguiamo il seguente comando:
Set-ExecutionPolicy Unrestricted -Force
Set-ExecutionPolicy RemoteSigned -Force

Spero di essere stato utile…
Buon divertimento a tutti!!!