UblionConnect.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
function Install-LeftConnectRemoteControllerSQL
{    
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [String]$Tenant,
        
        [System.Management.Automation.PSCredential]
        $Credential = $(Get-Credential),

        [Parameter(Mandatory)]
        [String]$SqlConnectionString
    )

    $folder = Create-LeftConnectConfigurationFolder
    
    Log("Install LeftConnect configuration to $folder")

    $secureSqlConnectionString = ConvertTo-SecureString -Force -AsPlainText $SqlConnectionString | ConvertFrom-SecureString 
    Set-Content "$folder\sql.cfg" (
        #connectionString
        $secureSqlConnectionString + "`n"
    )

    Install-LeftConnectionBase -Tenant $Tenant -Credential $Credential
    Log("LeftConnect installed")
}

### Storing the remote connection credentials on a save way
function Install-LeftConnectionBase{
    param(
        [Parameter(Mandatory)]
        [String]$Tenant,
                
        $Credential
    )
    
    $folder = Create-LeftConnectConfigurationFolder
    $secureStringText = $Credential.Password | ConvertFrom-SecureString 
    Set-Content "$folder\baseConnection.cfg" (
            #password
            $secureStringText + "`n" + 
            #username
            $Credential.UserName + "`n" + 
            #Tenant
            $Tenant + "`n"
    )
}

Function Log {
    param(
        [Parameter(Mandatory=$true)][String]$msg
    )
    
    $folder = Get-LeftConnectConfigurationFolder
    $logFile = Join-Path $folder "logfile.txt"
    $data = (Get-date).ToString() + " "  + $msg
    Add-Content $logFile $data
}

function Get-LeftConnectLog {
    param(
        [switch]$watching
    )

    $folder = Get-LeftConnectConfigurationFolder
    $logFile = Join-Path $folder "logfile.txt"
    if ($watching) {
        Get-Content $logFile -Wait
    } else {
        get-content $logFile
    }
}

function Create-LeftConnectConfigurationFolder{
    $folder = $env:LOCALAPPDATA + "\LeftConnect"
    
    if( -not (Test-path $folder)){
      Install-AppData -DirectoryToCreate $folder -ErrorAction Ignore
    }
    $folder
}
function Get-LeftConnectConfigurationFolder{
    $folder = $env:LOCALAPPDATA + "\LeftConnect"
    $folder
}

function Get-LeftConnectSqlConfiguration {
    $folder = Get-LeftConnectConfigurationFolder
    $data = (Get-Content "$folder\sql.cfg").split("`n")
    

    $secureString = $data[0] | ConvertTo-SecureString
    $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString)
    $UnsecureConnectionString = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

    @{
        connectionString = $UnsecureConnectionString
    }
}

function Get-LeftConnectBaseConfiguration {
    $folder = Get-LeftConnectConfigurationFolder
    $data = (Get-Content "$folder\baseConnection.cfg").split("`n")


    $secureString = $data[0] | ConvertTo-SecureString
    $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString)
    $UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

    @{
        user = $data[1]
        pass = $UnsecurePassword
        tenant = $data[2]
    }
}


function Get-UblionFile {
    [CmdletBinding()]
    param($id, $filename, $path)
      #get the pdf as a file base 64 stream
       $apiGetPDF = "api/services/app/Document/GetDocumentPDF?id="+$id
       $result   = Get-LeftConnectResult -request $apiGetPDF
       $b64      = $result.result.fileBase64

       # construct the filename for the pdf
       $filename = $path+"\"+$filename
       $fileOutputPdf = $filename+".pdf"

       # convert the file from base 64 to byte and write it to disk
       $bytes    = [Convert]::FromBase64String($b64)
       [IO.File]::WriteAllBytes($fileOutputPdf, $bytes)    
   
       
       $apiGetUbl = "api/services/app/Ubl/DownloadUbl"
       $body = "{""id"": ""$id""}"
       $result   = Get-LeftConnectResult -request $apiGetUbl -body $body
       $fileOutputUbl = $filename+".xml"
       $downloadFile = "/File/DownloadTempFile?FileType="+$result.result.fileType+"&FileToken="+$result.result.fileToken+"&FileName="+$result.result.filename
     
       log -msg ("Download file to $fileOutputPdf")
       Invoke-RestMethod ((Get-LeftConnectUrlHost)+$downloadFile) -OutFile $fileOutputUbl  
   
   }

   <#
   .SYNOPSIS
   Get modified documents
    
   .DESCRIPTION
   A document is deleiered when it is changing the state and it's not send before with GetModifiedDocuments, It's a infinitely loop
    
   .EXAMPLE
   An example
    
   .NOTES
   General notes
   #>

function Get-LeftConnectResultFiles {
    [CmdletBinding()]
    param()

    $DocumentType = @{Outgoing = 25}

    $ublionConfiguration = Get-UblionConfiguration
    While ($true) {
        if( -not (Test-path $resultFolder))
        {
            mkdir $resultFolder
        }
        try {
            # Check for incoming documents
            $apiGetModifiedFiles = "api/services/app/Document/GetModifiedDocuments"
            $result = Get-LeftConnectResult -request $apiGetModifiedFiles
            if ($result.result.GetType().Name -eq "Object[]") {
                #foreach available document
                foreach ($document in $result.result){
                    Write-Host $document.type.id $DocumentType.Outgoing
                    if ($document.type.id -eq $DocumentType.Outgoing) {
                        $outbresultFolderound = Join-Path $ublionConfiguration.baseFolder  $ublionConfiguration.incomingFolderOrders
                    } 
                    else {
                        $outbresultFolderound = Join-Path $ublionConfiguration.baseFolder  $ublionConfiguration.incomingFolderInvoices
                    }
                    Get-UblionFile -id ($document.id) -filename ($document.name) -path ($outbresultFolderound)
                }
            } 
        } 
        catch {
            write-host error $_
        }
        Start-Sleep -Seconds 10
    }
}


<#
.SYNOPSIS
Get the tenant url
 
.DESCRIPTION
Returns the url host
 
.EXAMPLE
An example
 
.NOTES
General notes
#>
#
function Get-LeftConnectUrlHost {
    $tenant = (Get-LeftConnectBaseConfiguration).tenant
    if (-not $tenant.Contains("-connectapi")) {
        $tenant = $tenant -replace ".apprx.eu", "-connectapi.apprx.eu"
    }
    "https://$tenant/"
}

<#
.SYNOPSIS
Create bearer token
 
.DESCRIPTION
Create a bearer token based on the login credentials
 
.EXAMPLE
An example
 
.NOTES
General notes
#>
#
function Get-LeftConnectToken{
    param ([switch]$force)
    $token = $global:token
    $tokenReset = $global:tokenReset
    

    if ($force) {
        $token = $null
    }

    if (-not [string]::IsNullOrEmpty($token) ){
        $token
    } else {
        write-host -backgroundcolor green new token required
        $data = Get-LeftConnectBaseConfiguration
        $loginBody = "{""userNameOrEmailAddress"": """+$data.user+""",""password"": """+$data.pass+"""}"
        $connectionApiString = "api/TokenAuth/Authenticate"

        $authorizationUrl = (Get-LeftConnectUrlHost) + $connectionApiString
        Log("Trying to connect to $authorizationUrl")
        $login = Invoke-RestMethod  $authorizationUrl -Method Post -Body $loginBody -ContentType "application/json" 

        $global:token = $login.result.accessToken
        $global:token
    }
}
function Get-LeftConnectResult{
    [CmdletBinding()]
    param($request, $body)
    $token = Get-LeftConnectToken
    $headers = @{"Authorization"="Bearer "+$token;}
    $requestUrl = (Get-LeftConnectUrlHost) + $request
    Log("Requesting url: $requestUrl")
    try {
        if ($body) {
            $answer = Invoke-RestMethod $requestUrl -Method Post -Body $body -ContentType "application/json; charset=utf-8" -Headers $headers
        } else {
            $answer = Invoke-RestMethod $requestUrl -Headers $headers
        } } catch {
            write-host "Token not accepected. Try renewing"
            if ($global:token) {
                Remove-Variable token -Scope Global
            }
            $token = Get-LeftConnectToken -force $true
            $headers = @{"Authorization"="Bearer "+$token;}
        if ($body) {
            $answer = Invoke-RestMethod $requestUrl -Method Post -Body $body -ContentType "application/json; charset=utf-8" -Headers $headers
        } else {
            $answer = Invoke-RestMethod $requestUrl -Headers $headers
        }
    }

    return $answer
}

function Start-Ublion {
    [CmdletBinding()]
    Param (
        [Parameter()] 
        [String]$WatchFolder,
        [Parameter()]
        [String]$DestinationFolder
        )
        
    # start watcher for outgoing invoices
    $ublionConfiguration = Get-UblionConfiguration

    $filter = '*.JSON'
    
    $outbound = Join-Path $ublionConfiguration.baseFolder $ublionConfiguration.outgoingFolderInvoices
    $resultFolder = Join-Path $ublionConfiguration.baseFolder $ublionConfiguration.outgoingFolderInvoices
    $fsw = New-Object IO.FileSystemWatcher $outbound, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 
    $action = {
        try{ 
            import-module UblionConnect
            
            $ublionConfiguration = Get-UblionConfiguration
            $copyFolder1 =  ($ublionConfiguration.copyLocation1)
            $copyFolder2 =  ($ublionConfiguration.copyLocation2)
            Start-Sleep -Seconds 1
            $documentCreateApi = "api/services/app/Document/Create"
            $path              = $Event.SourceEventArgs.FullPath
            $FileName          = $Event.SourceEventArgs.Name
            $hashfunction      = '[IO.File]::ReadAllLines($path)'
            $base64            = (Invoke-Expression $hashfunction).Replace("""","\""")
            $sendFile          = "{""name"": """+$FileName.Replace(".JSON","")+""",""type"": ""invoiceJson"", ""description"": ""PSUpload"",""file"": """+$base64+"""}"

            write-host ("Sending: " + "{""name"": """+$FileName.Replace(".JSON","")+""",""type"": ""invoiceJson"", ""file"": fileContent}")
            Get-LeftConnectResult -request $documentCreateApi -body $sendFile
             
            if (-not ([string]::IsNullOrEmpty($copyFolder1))) {
                $newPath = Join-Path $copyFolder1 "invoice"
                $newPath = Join-Path $newPath  $Event.SourceEventArgs.Name
                $newPath = Join-Path $newPath  (Get-Date).ToString("yyyyMMddHHmmss")
                write-host Copy file to $newPath
                mkdir $newPath
                Copy-Item  $Event.SourceEventArgs.FullPath  $newPath
                write-host Copy file to $newPath
            } else {
                Write-host "copyFolder1 1 not known $copyFolder1"
            }
            if (-not ([string]::IsNullOrEmpty($copyFolder2))) {
                mkdir $copyFolder2
                Copy-Item  $Event.SourceEventArgs.FullPath  $copyFolder2
                write-host Copy file to $copyFolder2
            } else {
                Write-host "copyFolder2 1 not known $copyFolder2"
            }

            Remove-Item $Event.SourceEventArgs.FullPath
        }
        catch {
            write-host -ForegroundColor Red $_.Exception.Message
            write-host -ForegroundColor Red $_.Exception.ItemName
            write-host "ERROR in file "$Event.SourceEventArgs.FullPath -ForegroundColor Red
        }
    }
    
    $backupscript = Register-ObjectEvent -EventName "Created" -InputObject $fsw -Action $action -MessageData $resultFolder 
    Write-Host "WatchFolder: `"Invoice To Ublion $($baseFolder)`" DestinationFolder: `"$($resultFolder)`" started. Job is in: $backupscript" -ForegroundColor Green


    #start watcher for incoming invoices
    if (-not [string]::IsNullOrEmpty($ublionConfiguration.outgoingFolderOrders)){
            $filter = '*.JSON'
            $outbound = Join-Path $ublionConfiguration.baseFolder $ublionConfiguration.outgoingFolderOrders
            $resultFolder = Join-Path $ublionConfiguration.baseFolder $ublionConfiguration.outgoingFolderOrders
            $fsw = New-Object IO.FileSystemWatcher $outbound, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 
            $action = {
                try{ 
                    import-module UblionConnect

                    
                    $ublionConfiguration = Get-UblionConfiguration
                    $copyFolder1 =  ($ublionConfiguration.copyLocation1)
                    $copyFolder2 =  ($ublionConfiguration.copyLocation2)
                    Start-Sleep -Seconds 1
                    $documentCreateApi = "api/services/app/Document/Create"
                    $path              = $Event.SourceEventArgs.FullPath
                    $FileName          = $Event.SourceEventArgs.Name
                    $hashfunction      = '[IO.File]::ReadAllLines($path)'
                    $base64            = (Invoke-Expression $hashfunction).Replace("""","\""")
                    $sendFile          = "{""name"": """+$FileName.Replace(".JSON","")+""",""type"": ""order"", ""file"": """+$base64+"""}"
                    
                    write-host ("Sending: " + "{""name"": """+$FileName.Replace(".JSON","")+""",""type"": ""order"", ""file"": fileContent}")
                    Get-LeftConnectResult -request $documentCreateApi -body $sendFile
                    if (-not ([string]::IsNullOrEmpty($copyFolder1))) {
                        $newPath = Join-Path $copyFolder1 "order"
                        $newPath = Join-Path $newPath  $Event.SourceEventArgs.Name
                        $newPath = Join-Path $newPath  (Get-Date).ToString("yyyyMMddHHmmss")
                        write-host Copy file to $newPath
                        mkdir $newPath
                        Copy-Item  $Event.SourceEventArgs.FullPath  $newPath
                    } else {
                        Write-host "copyFolder1 1 not known $copyFolder1"
                    }
                    if (-not ([string]::IsNullOrEmpty($copyFolder2))) {
                        mkdir $copyFolder2
                        Copy-Item  $Event.SourceEventArgs.FullPath  $copyFolder2
                        write-host Copy file to $copyFolder2
                    } else {
                        Write-host "copyFolder2 1 not known $copyFolder2"
                    }

                    Remove-Item $Event.SourceEventArgs.FullPath
                }
                catch {
                    write-host -ForegroundColor Red $_.Exception.Message
                    write-host -ForegroundColor Red $_.Exception.ItemName
                    write-host "ERROR in file "$Event.SourceEventArgs.FullPath -ForegroundColor Red
                }
            }
            
            $backupscript = Register-ObjectEvent -EventName "Created" -InputObject $fsw -Action $action -MessageData $resultFolder 
            Write-Host "WatchFolder: `"Order to Ublion$($baseFolder)`" DestinationFolder: `"$($resultFolder)`" started. Job is in: $backupscript" -ForegroundColor Green
        }
        Log("Start ublion watchers")


        Get-LeftConnectResultFiles
        Log("Start downloading items")
}





function Install-Ublion{
    
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [String]$Tenant,
        
        # The base folder
        [Parameter(Mandatory)]
        [String]$BaseFolder,

        [System.Management.Automation.PSCredential]
        $Credential = $(Get-Credential),

        # The incoming folder for invoices from ublion
        [String]$IncomingFolder = "FromUblion",

        # The folder which contains the document to upload
        [String]$OutgoingFolder = "ToUblion",

        #the order folder
        [String]$OrderPrefix = "Order",

        #the order folder
        [String]$InvoicePrefix = "Invoice",

        ##the template folder
        [String]$TemplateFolder = "Templates",
        ##CopyLocation
        [String]$CopyLocation1 = "",
        ##CopyLocation
        [String]$CopyLocation2 = ""
    )

    Install-LeftConnectionBase -Tenant $Tenant -Credential $Credential
    $folder = Get-LeftConnectConfigurationFolder
    
    
    Install-AppData -DirectoryToCreate ($BaseFolder + "\" + $InvoicePrefix + $OutgoingFolder)
    Install-AppData -DirectoryToCreate ($BaseFolder + "\"+ $InvoicePrefix + $IncomingFolder)

    Install-AppData -DirectoryToCreate ($BaseFolder + "\"+ $InvoicePrefix + $TemplateFolder)

    if (-not [string]::IsNullOrEmpty($OrderPrefix)) {        
        
        $OutgoingFolderOrder = $OrderPrefix + $OutgoingFolder     
        $IncomingFolderOrder = $OrderPrefix + $IncomingFolder

        Install-AppData -DirectoryToCreate ($BaseFolder + "\" + $OutgoingFolderOrder)
        Install-AppData -DirectoryToCreate ($BaseFolder + "\"+  $IncomingFolderOrder)

    }
    Set-Content "$folder\ublion.cfg" (
        #Root folder for data
        $BaseFolder + "`n" + 
        # Outgoing folder invoices
        $InvoicePrefix + $OutgoingFolder + "`n" + 
        # Incoming folder invoices
        $InvoicePrefix + $IncomingFolder + "`n" +
        # Outgoing folder orders
        $OutgoingFolderOrder + "`n" + 
        # Incoming folder orders
        $IncomingFolderOrder + "`n" + 
        # Incoming template folder
        $InvoicePrefix + $TemplateFolder + "`n"+
        # Copy Location 1
        $CopyLocation1  + "`n" +
        # Copy Location 2
        $CopyLocation2  + "`n"
        )

    Log("Install ublion configuration to $folder")
}


function Remove-LeftConnectInstallation {
    $folder = Get-LeftConnectConfigurationFolder
    if (Test-Path -LiteralPath $folder) {
        Remove-Item $folder
        "LeftConnect configuration removed"
    }
}

function Get-UblionConfiguration {
    $folder = Get-LeftConnectConfigurationFolder
    $data = (Get-Content "$folder\ublion.cfg").split("`n")

    @{
        baseFolder = $data[0]
        outgoingFolderInvoices = $data[1]
        incomingFolderInvoices = $data[2]
        outgoingFolderOrders = $data[3]
        incomingFolderOrders = $data[4] 
        incomingFolderTemplate = $data[5] 
        copyLocation1 = $data[6] 
        copyLocation2 = $data[7] 
    }
}

function Get-LeftConnectSqlConfiguration {
    $folder = Get-LeftConnectConfigurationFolder
    $data = (Get-Content "$folder\sql.cfg").split("`n")
    

    $secureString = $data[0] | ConvertTo-SecureString
    $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString)
    $UnsecureConnectionString = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

    @{
        connectionString = $UnsecureConnectionString
    }
}
<#
.SYNOPSIS
Create an folder
 
.DESCRIPTION
Long description
 
.PARAMETER DirectoryToCreate
Parameter description
 
.EXAMPLE
An example
 
.NOTES
General notes
#>
#
function Install-AppData{
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory = $True)]
    [String] $DirectoryToCreate)

    if (-not (Test-Path -LiteralPath $DirectoryToCreate)) {
        
        try {
            New-Item -Path $DirectoryToCreate -ItemType Directory -ErrorAction Stop | Out-Null #-Force
        }
        catch {
            Write-Error -Message "Unable to create directory '$DirectoryToCreate'. Error was: $_" -ErrorAction Stop
        }
        "Successfully saved credentials"
        $DirectoryToCreate

    }
    else {
        "Directory already existed"
        $DirectoryToCreate
    }
}

<#
.SYNOPSIS
Upload invoice templates
 
.DESCRIPTION
Upload invoice template for footer, main and header. The template is a html file with complete styling.
 
.EXAMPLE
An example
 
.NOTES
General notes
#>
#
function Start-UploadTemplate{
    [CmdletBinding()]
    param()

    $ublionConfiguration = Get-UblionConfiguration

    $filter = '*.JSO'
    $templateFolder = Join-Path $ublionConfiguration.baseFolder $ublionConfiguration.incomingFolderTemplate

    $filter = '*.html'
    $fsw = New-Object IO.FileSystemWatcher $templateFolder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 
    $action = {
            write-host Start uploading $Event.SourceEventArgs.FullPath 
            try{
                import-module UblionConnect
                Start-Sleep -Seconds 2
                $documentCreateApi = "api/services/app/EmailTemplate/CreateOrEdit"
                $path              = $Event.SourceEventArgs.FullPath
                $FileName          = $Event.SourceEventArgs.Name
                $hashfunction      = '[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([IO.File]::ReadAllLines($path)))'
                $base64            = (Invoke-Expression $hashfunction).Replace("""","\""")
                $sendFile          = "{""name"": """+$FileName.replace(".html","")+""",""type"": ""INVOICE"",""description"": ""PSUpload"", ""template"": """+$base64+"""}"
                write-host request file
                Get-LeftConnectResult -request $documentCreateApi -body $sendFile
            }
            catch {
                write-host -ForegroundColor Red $_.Exception.Message
                write-host -ForegroundColor Red $_.Exception.ItemName
                write-host "ERROR in file "$Event.SourceEventArgs.FullPath -ForegroundColor Red
            }
    }
    $backupscript = Register-ObjectEvent -EventName "Changed" -InputObject $fsw -Action $action -MessageData $resultFolder 
    Write-Host "Template watcher is started. WatchFolder: `"$($templateFolder)`" Job is in: $ backupscript" -ForegroundColor Green    
}


function Get-LeftConnectRemoteJob{
    
        $deliverResult = "api/services/app/RemoteControl/SetDeliveries"
        $getTask= "api/services/app/RemoteControl/GetAssignment"
        
        #Get the job from the server
        $job = (Get-LeftConnectResult -request $getTask).result
        if (-not $job){
            return
        }
        Log("Receive the following job: $job")
        if ($job.Action -eq "SQL") {
            $result = Start-LeftConnectJobSql -taskInformation $job
            $result | Add-Member -MemberType NoteProperty -Name "Id" -value $job.Id -Force -ErrorAction SilentlyContinue
        } elseif ($job.Action -eq "FILE") {
            $result = Start-LeftConnectJobFile -taskInformation $job
            $result | Add-Member -MemberType NoteProperty -Name "Id" -value $job.Id -Force -ErrorAction SilentlyContinue
        } elseif ($job.Action -eq "SELFUPDATE") {
            $result = = [PSCustomObject]@{
                success = $false
                message = Start-LeftConnectSelfUpdate
            }
        }else {
            $result = [PSCustomObject]@{
                success = $false
                message = ("There is no handler known for given action: " + $job.Action)
            }
        }

        # Send result to server
        $result | Add-Member -MemberType NoteProperty -Name "CreationDate" -value (Get-Date).ToString("o") 
        Get-LeftConnectResult -request $deliverResult -body  ($result | ConvertTo-Json)
        
        Remove-Variable result
}
function Start-LeftConnectSqlQuery{
    param ($query)
    $fakeStart = Start-LeftConnectJobSql -taskInformation @{
        Action = "SQL"
        Command = $query
    }
  $fakeStart
}

function Start-LeftConnectRemoteListener{
    param($interval = 10)
    while ($true) {
        Get-LeftConnectRemoteJob
        [system.gc]::Collect()
        Start-Sleep -Seconds $interval   
    }
}
function Start-LeftConnectJobSql
{
    param ($taskInformation)

    if (-not $taskInformation.command) {
        return @{
            message= "No command found"
            sucess= $false
        }
    }

    $sqlConfiguration = Get-LeftConnectSqlConfiguration
    $sqlConn = New-Object System.Data.SqlClient.SqlConnection

    $sqlConn.ConnectionString = $sqlConfiguration.connectionString
    $ErrorActionPreference = "Stop"
    try {
        $sqlConn.Open()
        $sqlcmd = $sqlConn.CreateCommand()
        $sqlcmd.Connection = $sqlConn
        $query = $taskInformation.Command
        $sqlcmd.CommandText = $query
        $sqlresult = $sqlcmd.ExecuteReader()

        $table = new-object System.Data.DataTable
        $table.Load($sqlresult)

        $returnValue = @{
            data=  $table | select $table.Columns.ColumnName
            success= $true
        }
    } catch {
        Log("Connection issue with getting the data. $_")
        $returnValue = @{
            message= $Error[0].Exception
            success= $false
        }
    }
    $ErrorActionPreference = "Continue"
    $sqlConn.Close()
    return $returnValue
}
function Start-LeftConnectJobFile{
    param ($taskInformation)
}

function Get-LeftConnectReleaseNotes {
    $logData = @(
                    "24/10/2020: Updating template service",
                    "20/08/2020: Fix logic to route order to outgoing folder",
                    "22/07/2020: Add order ",
                    "15/07/2020: Added order functionality, remove connection code, make order folder ",
                    "24/02/2022: Create Remote Controller"
                )
    Write-host $logData
}

function Start-LeftConnectSelfUpdate{
param()
    Update-Module ublionconnect
    Import-Module ublionconnect

}



Export-ModuleMember -function  Install-Ublion
Export-ModuleMember -function  Install-LeftConnectRemoteControllerSQL
Export-ModuleMember -function  Get-UblionFile
Export-ModuleMember -function  Get-LeftConnectResultFiles
Export-ModuleMember -function  Get-LeftConnectUrlHost
Export-ModuleMember -function  Get-LeftConnectToken
Export-ModuleMember -function  Get-LeftConnectResult
Export-ModuleMember -function  Start-Ublion 
Export-ModuleMember -function  Start-UploadTemplate
Export-ModuleMember -function  Get-LeftConnectReleaseNotes
Export-ModuleMember -function  Remove-LeftConnectInstallation
Export-ModuleMember -function  Get-LeftConnectLog
Export-ModuleMember -function  Start-LeftConnectJobSql
Export-ModuleMember -function  Get-LeftConnectRemoteJob
Export-ModuleMember -function  Start-LeftConnectSqlQuery
Export-ModuleMember -function  Start-LeftConnectSelfUpdate
Export-ModuleMember -function  Start-LeftConnectRemoteListener

#Export-ModuleMember -function Get-LeftConnectSqlConfiguration
#Export-ModuleMember -function Get-UblionConfiguration