3. Scripts

27 февраля 2020 г.

14:48

Script Meaning
Script (OnDiscarded) The script is run after the object is discarded.
Script (OnDiscarding) The script is run before the object is discarded.
Script (OnLoaded) The script is run after the object is loaded.
Script (OnSaved) The script is run after the object is saved.
Script (OnSaving) The script is run before the object is saved.

*From \<<https://support.oneidentity.com/technical-documents/identity-manager/8.0/configuration-guide/29*

Оповещение о пользователях, которые будут скоро уволены

Public Function Z_Notify_Upcoming_User_Termination() As String

Dim timeSqlParts As New List(Of String)

For Each nextTimeDiff As String In {"0", "5", "10"}

timeSqlParts.Add("DATEADD(DD," & nextTimeDiff & ",CAST(getdate() AS  
Date))=cast(ExitDate as date)")

Next

Dim items As IColDbObject = Nothing

items = Connection.CreateCol("Person")

items.Prototype("UID_Person").IsDisplayItem = True

items.Prototype("UID_PersonHead").IsDisplayItem = True

items.Prototype.WhereClause = "ExitDate is not null and IsInActive=0  
and IsExternal=1 and (" & String.Join(" or ", timeSqlParts) & ")"

items.Prototype.OrderBy = "internalname"

items.Load()

logger.Trace("pending termination count: " & items.Count)

Dim managersToUsers As New Dictionary(Of String, List(Of String))

For Each nextOp As IColElem In items

Dim managerId = nextOp.GetValue("UID_PersonHead").String

Dim persId = nextOp.GetValue("UID_Person").String

If Not String.IsNullOrEmpty(managerId) Then

Z_Dictionary_Put_If_Absent(managersToUsers, managerId, New List(Of  
String))

managersToUsers.Item(managerId).Add(persId)

End If

Next

For Each nextManager As String In managersToUsers.Keys

Try

Dim userIds As List(Of String) = managersToUsers.Item(nextManager)

logger.Trace("sending upcoming termination mail with " & userIds.Count  
& " users (" & String.Join(", ", userIds) & ") to " & nextManager)

Dim toEmail As String = Connection.CreateSingle("Person",  
nextManager).GetValue("DefaultEmailAddress").String

Dim emailParams As New Dictionary(Of String, Object)

emailParams.Add("userIds", userIds)

emailParams.Add("Receiver", nextManager)

Z_Send_Html_Mail_With_Template(toEmail, "Z_Upcoming_Termination",  
emailParams)

Catch ex As Exception

logger.Error(ex, "error hile sending mail to " & nextManager)

End Try

Next

Return "ok"

End Function

Параметр в переменную (скрипт отправки почты)

  #If Not SCRIPTDEBUGGER Then

 Imports System.Collections.Generic

 Imports System.Net.Mail

 #End If

  

 toAddress =
 Connection.GetConfigParm("Common\MailNotification\RedirectAllMailsTo")

 /////////////////////////////////////////////////////////////////////////////////////////////////////

 Sub Z_Send_Mail(ByVal toAddress As String, ByVal subject As String,
 ByVal body As String, isHTML As Boolean, Optional dontCatchError As
 Boolean = False)

 If Not
 String.IsNullOrWhiteSpace(Connection.GetConfigParm("Common\MailNotification\RedirectAllMailsTo"))
 Then

 toAddress =
 Connection.GetConfigParm("Common\MailNotification\RedirectAllMailsTo")

 logger.trace("system configured to redirect all mails to " &
 toAddress)

 End If

 If String.IsNullOrEmpty(toAddress) Then

 logger.Warn("toAddress is empty for message with subject = " & subject
 & "; body = " & body)

 Return

 End If

 If
 String.IsNullOrEmpty(Connection.GetConfigParm("Common\MailNotification\DefaultSender"))
 OrElse
 String.IsNullOrEmpty(Connection.GetConfigParm("Common\MailNotification\SMTPRelay"))
 Then

 logger.Warn("SMTP server is not configured for message with subject =
 " & subject & "; body = " & body)

 Return

 End If

 Try

 **Dim Smtp_Server As New SmtpClient**

 **Dim e_mail As New MailMessage()**

 **' Smtp_Server.UseDefaultCredentials = False**

 **' Smtp_Server.Credentials = New Net.NetworkCredential(
 Connection.GetConfigParm("Common\MailNotification\SMTPDomain") & "\\ &
 Connection.GetConfigParm("Common\MailNotification\SMTPAccount"),
 Connection.GetConfigParm("Common\MailNotification\SMTPPassword"))**

 **Smtp_Server.Port =
 Convert.toInt32(Connection.GetConfigParm("Common\MailNotification\SMTPPort"))**

 **Smtp_Server.EnableSsl = False**

 **Smtp_Server.Host =
 Connection.GetConfigParm("Common\MailNotification\SMTPRelay")**

 **e_mail = New MailMessage()**

 **e_mail.From = New
 MailAddress(Connection.GetConfigParm("Common\MailNotification\DefaultSender"))**

 **For Each addr As String In toAddress.Split(","c)**

 **e_mail.To.Add(addr.trim())**

 **Next**

 **e_mail.Subject = subject**

 **e_mail.IsBodyHtml = isHTML**

 **e_mail.Body = body**

 **Smtp_Server.Send(e_mail)**

 Catch ex As Exception

 logger.error(ex, "error while sending mesage with subject = " &
 subject & "; body = " & body & " to " & toAddress)

 If dontCatchError Then

 Throw ex

 End If

 End Try

 End Sub

Создание учетки SfB

Public Function Z_Connector_Skype_Add_Account(account As
 SingleDbObjectSnapshot) As String

 Dim scriptText As String = Z_Get_Email_Template_Body("Z_Skype_Create")

 Dim output As New List(Of String)

 'output.Add("userDataJSON")

 Dim scriptParams As New Dictionary(Of String, Object)

 scriptParams.Add("guid", account.GetValue("ObjectGUID").String)

 scriptParams.Add("pool", account.GetValue("CCC_RegistrarPool").String)

 scriptParams.Add("sip", account.GetValue("CCC_SipAddress").String)

 Dim results As IDictionary(Of String, Object) =
 Z_Run_PowerShell(scriptText, scriptParams, output)

 'Dim outputLines = CType(results.Item("\_\_OUTPUT\_\_"), List(Of
 String))

 'logger.Trace("outputLines = " & String.Join(vbCrLf, outputLines))

 Try

 Z_Send_Mail_New_Account_To_ISA(account.GetValue("XObjectKey").String)

 Catch ex As Exception

 logger.Error(ex, "error while sending mail to ISA")

 End Try

 Z_Assign_Add_Group(account.GetValue("UID_Person").String,
 Connection.GetConfigParm("TargetSystem\UNS\ITResource\Skype\DefaultGroupCN"))

 Return account.GetValue("ObjectGUID").String

 End Function

 /////////

 *Z_Skype_Create*

 param(\$guid, \$pool, \$sip)

 \$ErrorActionPreference = "Stop"

 import-module SkypeForBusiness

 \$trgUser = Get-CsAdUser –Identity \$guid

 If(\$trgUser.Enabled -eq \$null){

 Write-output "lync account not found; trying to create"

 try {

 Enable-CSUser \$guid -RegistrarPool \$pool -SipAddress \$sip

 } catch {

 \$ErrorMessage = \$\_.Exception.

 Write-output \$ErrorMessage

 if (\$ErrorMessage -eq "The EXECUTE permission was denied on the
 object 'XdsPublishItems', database 'xds', schema 'dbo'." ) {

 Write-output "expected error; should not affect lync account"

 } else {

 throw

 }

 }

 } elseif(\$trgUser.Enabled -eq \$false) {

 Write-output "account was disabled; enable it"

 Set-CsUser –Identity \$guid –Enabled \$True

 } else {

 Write-output "lync account already enabled"

 }

Создание учетки SfB 2 (в скприте процесса) ``` 'Value="get-alias | Where-Object {\$_.name -like 'tee*'}"

Dim theScript As New StringBuilder()

' load modules

' theScript.AppendLine("import-module activedirectory" )

' theScript.AppendLine("\$myname=""tee""")

' theScript.AppendLine("get-alias -Name \$myName")

Dim SAMAccountName As String = \$cn\$

Dim Username As String = Connection.GetConfigParm("Custom\SFB\Username")

Dim Password As String = Connection.GetConfigParm("Custom\SFB\Password")

Dim RegistrarPool As String = Connection.GetConfigParm("Custom\SFB\RegistrarPool")

Dim SipAddressType As String = Connection.GetConfigParm("Custom\SFB\SipAddressType")

Dim SipDomain As String = Connection.GetConfigParm("Custom\SFB\SipDomain")

Dim URL As String = Connection.GetConfigParm("Custom\SFB\URL_oscPowerShell")

theScript.AppendLine("\$creds = New-Object System.Management.Automation.PSCredential ('"+Username+"', (ConvertTo-SecureString '"+Password+"' -AsPlainText -Force))")

theScript.AppendLine("\$s = New-PSSession -Name SfB -ConnectionUri '"+URL+"' -Credential \$creds")

theScript.AppendLine("\$session = Import-PSSession -Session \$s")

theScript.AppendLine("Enable-CsUser -Identity 'nlmk\+SAMAccountName+"' -RegistrarPool '"+RegistrarPool+"' -SipAddressType '"+SipAddressType+"' -SipDomain '"+SipDomain +"'")

theScript.AppendLine("Remove-PSSession -Session \$s")

Value = theScript.ToString()

```


Поддержка SQL в сприптах

 ' Get the SQL formatter for our connection

 Dim f As ISqlFormatter = Session.SqlFormatter

SQL запрос

Public Function CCC_GetSingleValueWithOrderBy(UID_PersonWantsOrg As  
String) As String

Dim f As ISqlFormatter = Session.SqlFormatter

Dim WhereClause As String = f.AndRelation(

f.Comparison("DecisionType", "Unsubscribe", ValType.String),

f.Comparison("UID_PersonWantsOrg", UID_PersonWantsOrg,  
ValType.String))

Return Session.Source.GetSingleValue(Of String)(Query.

From("PWODecisionHistory").

Where(WhereClause).

OrderBy("DateHead DESC").

Select("ReasonHead"))

End Function

<https://www.oneidentity.com/community/identity-manager/f/forum/21728/orderby-quering-the-database-with-script

 <span class="mark"Dim qApprover = Query.From(Table.PWOHelperPWO,
 "php").Join(Table.PersonWantsOrg,
 "pwo").On(**Table.PWOHelperPWO.UID_PersonWantsOrg**).</span

 <span class="mark"Select(Table.PersonWantsOrg.DecisionLevel).</span

 <span class="mark"Where("php.UID_PersonHead =
 'e94fd1f7-ecf2-4d5f-9955-f2311a110c39' AND php.LevelNumber =
 pwo.DecisionLevel")</span

Expression Clauses in a query - Forum - Identity Manager Community - One Identity Community

С использованием Join и OrderBy

При использовании OrderBy меняется тип query на Iselect. Чтобы это исправить, меняет тив при получении коллекции.

 Dim qContentShort = Query.From("DialogWatchProperty",
 "watchprop").Join(Table.DialogWatchOperation,
 "watchop").On(Table.DialogWatchOperation.UID_DialogWatchOperation).SelectAll().Where(strWhere).OrderBy("DialogWatchOperation.OperationDate")


 colRecords = Session.Source.GetCollection(CType(qContentShort, Query))

Получение значения из БД

 Dim xValue As String  

 If (Session.Source().TryGetSingleValue(Of String)("\<tablename\",
 "\<columnname\", "\<whereclause\", xValue)) Then  
 'work with xValue  
 'Else 'make something different  
 End If

<https://support.oneidentity.com/identity-manager/kb/204144/changed-behaviour-in-the-new-object-layer-api


Получение значения из БД 2

 Dim xValue As String  
 Dim f As ISqlFormatter = Session.SqlFormatter

 Dim WhereClause As String = f.Comparison("UID_PersonWantsOrg",
 UID_PersonWantsOrg, ValType.String,CompareOperator.Equal,
 FormatterOptions.None)

 Session.Source().TryGetSingleValue(Of
 String)("Table","ColumnName",WhereClause,xValue)

 **ИЛИ**

 XValue = Connection.GetSingleProperty("AccProductGroup",
 "UID_AccProductGroup", WhereClause)

Вычисление родительского подразделения

 Dim CompanyCode As String

 Dim ObjectID as String = Right(\$ObjectID\$,8)

 Dim GroupName As String

 Dim ShortName as String = \$ShortName\$

 Dim dbDepartment as IEntity 'объявляем переменную, как объект

 Dim f As ISqlFormatter = Session.SqlFormatter 'для поддержки sql
 запросов и синтаксиса

 Dim strUID_ParentDepartment As String

 Dim strWhere As String

 dbDepartment = session.Source.Get("Department", \$UID_Department\$)
 'помещаем объект подразделения по его UID

 CompanyCode = dbDepartment.GetValue("CustomProperty02").ToString()
 'помещаем в переменную код компании подразделения

 strUID_ParentDepartment =
 dbDepartment.GetValue("UID_ParentDepartment") 'помещаем в переменную
 родительский департамент

 strWhere = f.UidComparison("UID_Department", strUID_ParentDepartment)
 'условия сравнения UID подразделения и родительского подразделения

 While string.IsNullOrWhiteSpace(CompanyCode) AND
 Session.Source.Exists("Department",strWhere) 'до тех пор, пока Код
 компании = Null и существует родительский департамент

 dbDepartment= session.Source.Get("Department",strUID_ParentDepartment)

 CompanyCode = dbDepartment.GetValue("CustomProperty02").ToString()

 strUID_ParentDepartment =
 dbDepartment.GetValue("UID_ParentDepartment")

 strWhere = f.UidComparison("UID_Department", strUID_ParentDepartment)

 End While

 If (not string.IsNullOrWhiteSpace(CompanyCode)) Then

 values("CompanyCode") = CompanyCode

 End if

 GroupName = "hab-" + CompanyCode + "-" + ObjectID

 values("ObjectID") = ObjectID

 values("ShortName") = ShortName

 values("GroupName") = GroupName

 values("Alias") = GroupName

 values("CanonicalName") = "ao.nlmk/HAB/" + GroupName

 values("DistinguishedName") = "CN=" + GroupName +
 ",OU=HAB,DC=ao,DC=nlmk"

Получение DistinguishedName по UID

 Public Function CCC_Test_UID_ADSContainer(ByVal strUID_ADSContainer As
 String) As String

 ' Get the SQL formatter for our connection

 Dim f As ISqlFormatter = Session.SqlFormatter

 'Dim a As String

 ' Build the WHERE clause for our request

 Dim where As String = f.Comparison("UID_ADSContainer",
 strUID_ADSContainer, ValType.String)

 ' Get Ident_Domain of the ADSContainer

 'a = Session.Source.GetSingleValue(Of String)("ADSContainer",
 "DistinguishedName", where)

 Dim xValue As String = "1"

 If (Session.Source().TryGetSingleValue(Of String)("ADSContainer",
 "DistinguishedName", where, xValue)) Then

 'work with xValue

 'Else 'make something different

 End If

 Return xValue

 End Function

Получение UID по имени домена

 Public Function CCC_Test_Get_UID_from_Name(ByVal Name As String) As
 String

 ' Get the SQL formatter for our connection

 Dim f As ISqlFormatter = Session.SqlFormatter

 ' Build the WHERE clause for our request

 Dim where As String = f.Comparison("ADSDomainName", Name,
 ValType.String)

 ' Get Ident_Domain of the ADSContainer

 'a = Session.Source.GetSingleValue(Of String)("ADSContainer",
 "DistinguishedName", where)

 Dim xValue As String = "1"

 'If (Session.Source().TryGetSingleValue(Of String)("ADSContainer",
 "DistinguishedName", where, xValue)) Then

 'work with xValue

 'Else 'make something different

 'End If

 xValue = Connection.GetSingleProperty("ADSDomain", "UID_ADSDomain",
 where)

 Return xValue

 End Function

Получаем значение из конфиг параметра

 Dim URL As String =
 Connection.GetConfigParm("Custom\Exchange\URL_ExchPowerShell")

Where в процессе

 Процесс SQLComponent - Existsvalues("GroupOUName").ToString вычисляем
 в Pre-Script первого блока процесса

 **Dim f As ISqlFormatter = Connection.SqlFormatter**

 **Value = f.Comparison("cn", values("GroupOUName"), ValType.String,
 CompareOperator.Equal)**

  

 values("GroupOUName") = GroupOUName

<img src="../media/3. Scripts/media/image1.png" style="width:8.5625in;height:1.51042in" alt="Param eters Parameter name Connectionprovider ConnectionString TableName Parameter value Value = Connectionlnfo.ConnectionProvider Value = Connectionlnfo.ConnectionString Value = •ADSContainer• Dim f ISqIFormatter = = f.Comparison(' cn' " /

<img src="../media/3. Scripts/media/image2.png" style="width:3.34375in;height:1.08333in" alt="Process step properties General Generation Error handling Extended Name Process task Check Exist OU SQLComponent - Exists " /


SQL выражение

Для SQLComponent - Execute SQL

 Dim f As ISqlFormatter = Connection.SqlFormatter

 Value = "delete ADSAccount where " & f.UIDComparison("UID_ADSAccount",
 \$UID_ADSAccount\$)

Работа с коллекциями из объектов БД

 Public Function CCC_Test_Unique_CompanyCode(ByVal CompanyCode As
 Integer) As String

 Dim colPersons As IEntityCollection

 Dim strSubType As String

 Dim dbPerson As IEntity

 Dim f As ISqlFormatter = Session.SqlFormatter

 Dim Res As String

 **' create the query object**

 Dim qPerson = Query.From("CCCOrgUnitMapping").SelectAll()

 **' Load a collection of Person objects**

 colPersons = Session.Source.GetCollection(qPerson)

 ' Run through the list

 For Each colElement As IEntity In colPersons

 dbPerson = colElement.Create(Session, EntityLoadType.Interactive)

 strSubType = dbPerson.GetValue("CCC_CompanyCode").String

 Dim qPerson1 = Query.From("CCCOrgUnitMapping").Where(Function(c)
 c.Column("CCC_CompanyCode") = strSubType).SelectCount()

 Dim iCount = Session.Source.GetCount(qPerson1)

 If iCount = CompanyCode Then

 Return strSubType

 End If

 Next

 Return CompanyCode.ToString()

 End Function

Шаблон параметра деактивации департамента

 Dim oDate As DateTime = Convert.ToDateTime(\$CustomProperty08\$)

 If oDate \< Date.UtcNow then

 Value = True

 Else

 Value = False

 End If

Вывести ошибку в Manager при сохранении (Для таблицы - OnSaving)

 Dim IPAddress As String = Convert.ToString(Value)

 If Not Regex.IsMatch(IPAddress,
 "^\d{1,3}\\\d{1,3}\\\d{1,3}\\\d{1,3}\$",
 RegexOptions.CultureInvariant) Then

 Throw New **VIException**("IP Address submitted is not valid.",
 ExceptionRelevance.EndUser)

 End If

Не создается запись в БД Insert через тестирование скрипта

Надо при тестировании скрипта отключить Use Transaction

<img src="../media/3. Scripts/media/image3.png" style="width:11.22917in;height:1.14583in" alt="Test script String UID_Person, String String UID.Org . • String Parameters _ Person (System.String) ccc (System.String) .Org (System. String) 4b9bebcf-204e4369-acf2-28ea26dd9af9 021 afe9f-c57c4e5e-8334-73045d1 b5780 Run Options • use master connection use transaction Record SQL log " /

<https://www.oneidentity.com/community/identity-manager/f/forum/30974/create-db-objects


Создание записи в БД Insert

 Public Function CCC_Test_Insert_DbObject(ByVal UID_Person As String,
 ByVal CCC_UID_Point_of_View As String, ByVal UID_Org As String) As
 String

  

 Dim dbCCCPointOfViewInAccProd As IEntity

 dbCCCPointOfViewInAccProd =
 Session.Source.CreateNew("CCCPointOfViewInAccProd")

 Using t As New Transaction(Session)

 dbCCCPointOfViewInAccProd.PutValue("CCC_UID_Person", UID_Person)

 dbCCCPointOfViewInAccProd.PutValue("CCC_UID_Point_of_View",
 CCC_UID_Point_of_View)

 **Using uow As IUnitOfWork = Session.StartUnitOfWork()**

 **uow.Put(dbCCCPointOfViewInAccProd)**

 **uow.Commit()**

 **End Using**

 **t.Commit()**

 End Using

 Return UID_Person

 End Function

Удаление записи из БД

 Public Function CCC_Test_Delete_DbObject(ByVal UID_Person As String,
 ByVal UID_ShoppingCartOrder As String, ByVal UID_PWO As String) As
 String

 Dim CCC_UID_Point_of_View As String

 Dim dbPointOfView As IEntity

 Dim dbPointOfView_new As IEntity

 Dim f As ISqlFormatter = Session.SqlFormatter

 Dim Res As String

 ' create the query object

 Dim qPointOfView =
 Query.From("CCCPointOfViewInAccProd_T").Where(Function(c)
 c.Column("CCC_UID_ShoppingCartOrder") =
 UID_ShoppingCartOrder).SelectAll()

 ' Load a collection of Person objects

 Dim colPointsOfView =
 Session.Source.GetCollection(qPointOfView,EntityCollectionLoadType.Bulk)

 Using uow = Session.StartUnitOfWork()

 ' Walk through the list of all persons

 For Each colElement As IEntity In colPointsOfView

 ' Mark for deletion

 colElement.MarkForDeletion()

 ' put the object in the unit of work

 uow.Put(colElement)

 Next

 ' All person objects will be saved here!

 uow.Commit()

 End Using

 Return UID_Person

 End Function

Обновление записи в БД

 dbcolCCCPersonnelActionsAPI = colElement.Create(Session,
 EntityLoadType.Interactive)

 dbcolCCCPersonnelActionsAPI.**PutValue**("CCC_InsertedDate",Date.UtcNow)

  

 Using t As New Transaction(Session)

         Using uow As IUnitOfWork = Session.StartUnitOfWork()

 uow.Put(dbcolCCCPersonnelActionsAPI)

 uow.Commit()

         End Using

         t.Commit()

         End Using


Сложный Where

 WhereClause = f.AndRelation( \_

 f.Comparison("CCC_CompanyCode", CompanyCode, ValType.String), \_

 f.Comparison("CCC_City", City, ValType.String), \_

 f.Comparison("CCC_CompanySubCode", CompanySubCode, ValType.String))

 End If

Для получения информации по наличии AD Account Definition у сотрудника для почтового шаблона оповещения согласующего при назначении режима доступа

 Public Function CCC_PersonHasTSBAccountDef() As String

 'Таблица PWOHelperPWO

 Dim f As ISqlFormatter = Session.SqlFormatter

 Dim UID_PersonOrdered As String =
 \$FK(UID_PersonWantsOrg).UID_PersonOrdered\$

 Dim colPersonHasTSBAccountDef As IEntityCollection

 Dim colTSBAccountDef As IEntityCollection

 Dim dbTSBAccountDef As IEntity

 Dim UID_AccDef As String

 Dim Result As String

 Dim qTSBAccountDef = Query.From("TSBAccountDef").Where(Function(c)
 c.Column("UID_DialogTableAccountType") =
 "ADS-T-ADSAccount").SelectAll()

 colTSBAccountDef = Session.Source.GetCollection(qTSBAccountDef)

 For Each colElement As IEntity In colTSBAccountDef

 dbTSBAccountDef = colElement.Create(Session,
 EntityLoadType.Interactive)

 UID_AccDef = dbTSBAccountDef.GetValue("UID_TSBAccountDef").String

 Dim qPersonHasTSBAccountDef =
 Query.From("PersonHasTSBAccountDef").Where(Function(c)
 c.Column("UID_Person") = UID_PersonOrdered And
 c.Column("UID_TSBAccountDef") = UID_AccDef ).SelectCount()

 Dim iCount = Session.Source.GetCount(qPersonHasTSBAccountDef)

 If iCount \ 0 Then

 Return "Да"

 End If

 Next

 Return "Нет"

 End Function

Работа с объектом

 Dim dbPWOHelperPWO As IEntity = Session.Source.Get("PWOHelperPWO",
 strUID_PWOHelperPWO)

 Dim f As ISqlFormatter = Session.SqlFormatter

 Dim strCCC_UID_ShoppingCartOrder As String =
 dbPWOHelperPWO.CreateWalker(Session).GetValue("FK(UID_PersonWantsOrg).UID_ShoppingCartOrder").String

 Dim res As String =
 dbPWOHelperPWO.CreateWalker(Session).GetValue("FK(UID_PersonWantsOrg).FK(ObjectKeyOrdered),QERAssign.FK(ObjectKeyAssignTarget),Org.Ident_Org").String

 Dim qCCCPointOfViewInAccProd_T =
 Query.From("CCCPointOfViewInAccProd_T") \_

 .Where(f.AndRelation( f.UidComparison("CCC_UID_ShoppingCartOrder",
 strCCC_UID_ShoppingCartOrder),

 f.UidComparison("CCC_UID_Person",strUID_PersonOrdered))) \_

 .Select("CCC_UID_Point_Of_View")

 colqCCCPointOfViewInAccProd_T =
 Session.Source.GetCollection(qCCCPointOfViewInAccProd_T)

 For Each colElement As IEntity In colqCCCPointOfViewInAccProd_T

 dbCCCPointOfView = Connection.CreateSingle("CCCPoint_Of_View",
 colElement.GetValue("CCC_UID_Point_Of_View").String)

 res= res + (dbCCCPointOfView.GetValue("CCC_Pov_Name").String) & " "

 Next

Update таблицы

 WhereClause

 Dim f As ISqlFormatter = Connection.SqlFormatter

 Value = f.Comparison("UID_Department", values("UID_Dep"),
 ValType.String, CompareOperator.Equal)

SQL запрос

 Public Function CCC_GetSingleValueWithOrderBy(UID_PersonWantsOrg As
 String) As String

 Dim f As ISqlFormatter = Session.SqlFormatter

 Dim WhereClause As String = f.AndRelation(

 f.Comparison("DecisionType", "Unsubscribe", ValType.String),

 f.Comparison("UID_PersonWantsOrg", UID_PersonWantsOrg,
 ValType.String))

  

 Return Session.Source.GetSingleValue(Of String)(Query.

 From("PWODecisionHistory").

 Where(WhereClause).

 OrderBy("DateHead DESC").

 Select("ReasonHead"))

 End Function

Добавление в массив уникальных значений из другого массива

 Dim arr1 As New ArrayList()

 Dim Col As New ArrayList()

  

 Arr1.add("123")

 Arr1.add("123")

  

 For Each I As String In arr1

 If Not Col.Contains(I) Then

 Col.Add(I)

 End If

 Next

 Return Col.Count.ToString()

Сначала выгружаем все записи таблицы, а потом проходимся по каждой и добавляем в Лист. Потом в другой лист пишем только уникальные значения того листа.

  

 Dim f As ISqlFormatter = Session.SqlFormatter

 Dim colUsers As IEntityCollection

 Dim colUsers_unique As IEntityCollection

 Dim dbUser As IEntity

 Dim listUID_UNSAccountB As New List(Of String)

 Dim listUID_UNSAccountBAll As New List(Of String)

  

 Dim qUsers =
 Query.From("UNSAccountBInUNSGroupB").Select("UID_UNSAccountB")

 colUsers =
 Session.Source.GetCollection(qUsers,EntityCollectionLoadType.Slim)

  

 For Each colElement As IEntity In colUsers

 dbUser = colElement.Create(Session, EntityLoadType.Interactive)

 UID_UNSAccountB = dbUser.GetValue("UID_UNSAccountB").String

 listUID_UNSAccountB.Add(UID_UNSAccountB)

 Next

 **listUID_UNSAccountBAll = listUID_UNSAccountB.Distinct().ToList()**

 Return listUID_UNSAccountBAll.count().tostring

Вычисление кол-ва согласующих по точкам зрения

 PreScript процесса для таблицы PersonWantsOrg

 Dim UID_ShoppingCartOrder as String = \$UID_ShoppingCartOrder\$

 Dim UID_PWO as String = \$UID_PersonWantsOrg\$

 Dim dbPoV As IEntity 'объявляем переменную, как объект

 Dim dbBalanceUnit As IEntity

 Dim dbDepartment As IEntity

 Dim dbPerson As IEntity

 Dim strCCC_UID_BalanceUnit As String

 Dim strCCC_UID_SanctionDepartment As String

 Dim strUID_PersonHeadDep As String

 Dim strMail_PersonHeadDep As String

 Dim strMail_PersonHeadDep_all As String

 Dim XObjectKey as String

 Dim arr As New ArrayList()

 Dim Col As New ArrayList()

 Dim colPointsOfView As IEntityCollection

 Dim colPWOHelperPWO As IEntityCollection

 Dim CCC_UID_Point_of_View As String

 Dim dbPointOfView As IEntity

 Dim dbPWOHelperPWO As IEntity

 Dim dbPointOfView_new As IEntity

 Dim f As ISqlFormatter = Session.SqlFormatter

 Dim Res As String

 ' create the query object

 Dim qPointOfView =
 Query.From("CCCPointOfViewInAccProd_T").Where(Function(c)
 c.Column("CCC_UID_ShoppingCartOrder") =
 UID_ShoppingCartOrder).SelectAll()

 Dim qPointOfView_count =
 Query.From("CCCPointOfViewInAccProd_T").Where(Function(c)
 c.Column("CCC_UID_ShoppingCartOrder") =
 UID_ShoppingCartOrder).SelectCount()

 Dim CountApprover = Session.Source.GetCount(qPointOfView_count)

 ' Load a collection of Person objects

 colPointsOfView = Session.Source.GetCollection(qPointOfView)

 ' Run through the list

 For Each colElement As IEntity In colPointsOfView

 dbPointOfView = colElement.Create(Session, EntityLoadType.Interactive)

 CCC_UID_Point_of_View =
 dbPointOfView.GetValue("CCC_UID_Point_of_View").String

 dbPoV = session.Source.Get("CCCPoint_of_View", CCC_UID_Point_of_View)
 'помещаем объект Point of View по его UID

 strCCC_UID_BalanceUnit = dbPoV.GetValue("CCC_UID_BalanceUnit")

 dbBalanceUnit = session.Source.Get("CCCBalance_units",
 strCCC_UID_BalanceUnit) 'помещаем объект Balance_unit по его UID

 strCCC_UID_SanctionDepartment =
 dbBalanceUnit.GetValue("CCC_UID_SanctionDepartment")

 dbDepartment = session.Source.Get("Department",
 strCCC_UID_SanctionDepartment) 'помещаем объект Department по его UID

 strUID_PersonHeadDep = dbDepartment.GetValue("UID_PersonHead")

 **arr.Add(strUID_PersonHeadDep) ' Add to array uid person**

 dbPerson = session.Source.Get("Person", strUID_PersonHeadDep)
 'помещаем объект Person по его UID

 strMail_PersonHeadDep = dbPerson.GetValue("DefaultEmailAddress")
 'получаем значение DefaultEmailAddress у руководителя департамента

 If (not string.IsNullOrWhiteSpace(strMail_PersonHeadDep)) Then

 strMail_PersonHeadDep_all = strMail_PersonHeadDep + "; " +
 strMail_PersonHeadDep_all

 End If

 Next

 'Calculate XObject PWOHelperPWO for mail template

 Dim qPWOHelperPWO = Query.From("PWOHelperPWO").Where(Function(c)
 c.Column("UID_PersonWantsOrg") = UID_PWO and
 c.Column("UID_PWODecisionRule") =
 "QER-PWODecisionRule-EX").SelectAll()

 colPWOHelperPWO = Session.Source.GetCollection(qPWOHelperPWO)

 For Each colElement As IEntity In colPWOHelperPWO

 dbPWOHelperPWO = colElement.Create(Session,
 EntityLoadType.Interactive)

 XObjectKey = dbPWOHelperPWO.GetValue("XObjectKey").String

 Next

 'Create array from arr with unique values

 For Each I As String In arr

 If Not Col.Contains(I) Then

 Col.Add(I)

 End If

 Next

 values("Addresses") = strMail_PersonHeadDep_all

 values("XObjectKey") = XObjectKey

 values("CountApprover") = Col.Count.ToString()

<img src="../media/3. Scripts/media/image4.png" style="width:9.9375in;height:5.90625in" alt="O PersonWantsOrg Calculate CountAp.„ Person Wan tsOrg Calcu late Coun tApprover for Decision Step Update CountApprover for Decisio n Step Make positive decision for requ Process - PersonWantsOrg Calcula... O Perso nWa ntsOrg create PWOHe1perPW0 I O ShoppingCartOrder Send mail Schema Editor Param eters Parameter name V SuthenticationString Connectionprovider ConnectionString ObjectType WhereCIause val_CountApprover ConnectionVariabIes Parameter value value = Connectionlnfo.ÅuthString Value = Connectionlnfo.ConnectionProvider Value = Connectionlnfo.ConnectionString Value = •PVVODecisionStep• Dim f As ISqIFormatter = Connection.SqIFormatter Value = f.ComparisonCUID_PVVODecisionStep , • •ccc-23FA8465854A064181A8113F9F8DIC84•, Val Value = valuesCCountApprover•) Value = •VarllVar21VarY " /


Вывод в шаблоне построчно из массива

 Dim DetailStrg As New StringBuilder

  

 DetailStrg.AppendLine(FIO_Attestor)

  

 Return DetailStrg.ToString()

ObjectWalker

 dbPWOHelperPWO_1 = colElement.Create(Session,
 EntityLoadType.Interactive)

 FIO_Attestor =
 dbPWOHelperPWO_1.CreateWalker(Session).GetValue("FK(UID_PersonHead).InternalName").String

  

 Dim Pers as ISingleDbObject = Connection.CreateSingle("Person",
 \$UID_PersonHead\$)

 Dim culture as String = Pers.Custom.CallMethod("GetCulture").ToString

 **Pers.ObjectWalker.GetValue("FK(UID_DialogCultureFormat).Ident_DialogCulture").String**

Глобальные и локальные переменные

  • Global variables owned by the set up program
    Syntax:
    Value = Variables("\<variable name\")
    Example:
    Value = Variables("GENPROCID")
    Value = Variables("FULLSYNC")

  • Process or process step variables created locally by a pre-script
    Syntax:
    Value = values("Name")
    Example:
    Value = Values("FirstHomeServer")

*From \<<https://support.oneidentity.com/technical-documents/identity-manager/8.0/configuration-guide/73*

Allocating Parameter Values

Define value templates in VB.Net syntax. The following statements can be used for allocating values:

None

Object columns or columns of a related object

Syntax:

Value = \$\<column name\:\<data type\$

Value = \${FK(\<foreign key column).}\<column name\:\<data type\$

Example:

Value = \$Lastname\$

Value = \$PasswordNeverExpires:bool\$

Value = \$FK(Ident_Domain).Description\$

Parameter from the optional parameter collection

Syntax:

Value = \$PC(\<parameter name)\$

Example:

Value = \$PC(SRCUID_Application)\$

Out parameter

Parameters of type "OUT" or "INOUT" are parameters that can be used by process components to output a value. This value is then available to subsequent process steps in the process and can be used as a value for IN parameters.

When you use OUT parameters you need to take care that these contain data at runtime. Alternatively, when the text is processed "&OUT(\<parameter name)&" is entered, which means that the variable will not be replaced.

Syntax:

Value = "&OUT(\<Parameter name)&"

Example:

Value = "&Out(FileSize)&"

Global variables owned by the set up program

Syntax:

Value = Variables("\<variable name\")

Example:

Value = Variables("GENPROCID")

Value = Variables("FULLSYNC")

Process or process step variables created locally by a pre-script

Syntax:

Value = values("Name")

Example:

Value = Values("FirstHomeServer")

Querying Configuration Parameters

The full path for the configuration parameter always has to be entered.

Syntax:

Value = Session.Config().GetConfigParm("\<full path\")

Example:

Value = Session.Config().GetConfigParm("TargetSystem\ADS\RestoreMode")

VB.net

Enter any VB.Net statement.

Identity Manager 8.0 - Configuration Guide (oneidentity.com)


Логирование

 \#If Not SCRIPTDEBUGGER Then

 References VI.DataImport.dll

 Imports System.Collections.Generic

 Imports System.IO

 Imports System.Globalization

 Imports VI.DataImport

 \#End If

  

 Dim SCLOG As String = Session.Config.GetConfigParm("Custom\LogPath") +
 "CCC_Department_ImportFromAPI\_" +
 DateTime.Now.ToString("yyyy-MM-dd") + ".txt"

  

 Try

 colCCCDepartmentsAPI =
 Session.Source.GetCollection(qCCCDepartmentsAPI)

 Catch ex As Exception

 If Not ex.InnerException Is Nothing AndAlso Not
 ex.InnerException.InnerException Is Nothing Then

 CCC_VID_Write2Log(SCLOG, Environment.NewLine +
 Date.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + "ERROR @ " +
 ex.Message + " " + ex.InnerException.Message + " " +
 ex.InnerException.InnerException.Message + " " + ex.StackTrace)

 ElseIf Not ex.InnerException Is Nothing Then

 CCC_VID_Write2Log(SCLOG, Environment.NewLine +
 Date.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + "ERROR @ " +
 ex.Message + " " + ex.InnerException.Message + " " + ex.StackTrace)

 Else

 CCC_VID_Write2Log(SCLOG, Environment.NewLine +
 Date.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + "ERROR @ " +
 ex.Message + " " + ex.StackTrace)

 End If

  

 End Try

CCC_VID_Write2Log

 \#If Not SCRIPTDEBUGGER Then

 References VI.Samba.Tools.dll

 \#End If

  

 Public Sub CCC_VID_Write2Log(ByVal LogFile As String, ByVal Line As
 String)

 Dim logFilePath As System.String

 If Not AppData.Instance.RuntimeEnvironment.IsMono Then

 logFilePath = PathHelper.ConvertSeparators(LogFile)

 Else

 Dim sambaUncPath As New VI.Samba.Tools.SambaUncPath(LogFile)

 If Not sambaUncPath.IsLocal Then

 Throw New System.Exception(#LD("UNC-path ""{0}"" does not reference a
 local path.", LogFile)#)

 Else

 logFilePath = sambaUncPath.LocalPath

 End If

 End If

  

 Dim f As System.IO.StreamWriter = Nothing

  

 Try

 f = New System.IO.StreamWriter(logFilePath, True,
 System.Text.Encoding.UTF8)

  

 f.NewLine() = Chr(13) & Chr(10)

 f.WriteLine(Line)

 Catch exc As System.Exception

 Throw New System.Exception(#LD("The path is '{0}'.", logFilePath)#,
 exc)

 Finally

 If Not f Is Nothing Then

 f.Flush()

 f.Close()

 End If

 End Try

 End Sub

Строки

Несколько строк

 Dim DetailStrg As New StringBuilder

 DetailStrg.AppendLine("qq")

 Return DetailStrg.ToString()

WHERE

 Dim f As ISqlFormatter = Session.SqlFormatter()

 Value = f.UidComparison("UID_ADSAccount", \$UID_ADSAccount\$)

EXPORT TO CSV

CSVExportSingle

<https://www.oneidentity.com/community/identity-manager/f/forum/30780/export-selectet-data-from-a-new-created-user-into-a-csv-file

Формат даты

 Dim asd As String = expenddt.ToString("dd/MM/yyyy")

*From \<<https://coderoad.ru/8644398/%D0%A4%D0%BE%D1%80%D0%BC%D0%B0%D1%82-%D0%B4%D0%B0%D1%82%D1%8B-%D0%B2-vb-net*

ObjectWalker

 Public Function CCC_Test_ObjectWalker (ByVal UID_PWO As String) As
 String

 Dim dbPWO As IEntity

 Dim strDisplayOrg As String

 Dim strDisplayOrgParent As String

 Dim strCCC_BPMServiceID As String

  

  

 dbPWO = Session.Source.Get("PersonWantsOrg", UID_PWO)

 strDisplayOrg =
 dbPWO.CreateWalker(Session).GetValue("DisplayOrg").String

 strDisplayOrgParent =
 dbPWO.CreateWalker(Session).GetValue("DisplayOrgParent").String

 'strCCC_BPMServiceID =
 dbPWO.CreateWalker(Session).GetValue("FK(UID_OrgParentOfParent).FK(UID_AccProduct).FK(UID_AccProductGroup).CCC_BPMServiceID").String

 strCCC_BPMServiceID =
 dbPWO.CreateWalker(Session).GetValue("FK(UID_Org).FK(UID_AccProduct).FK(UID_AccProductGroup).CCC_BPMServiceID").String

  

  

 Return strCCC_BPMServiceID

 End Function

Взаимодействие с GreenPlum (Postgress)

Надо установить odbc драйвер

<https://www.postgresql.org/ftp/odbc/versions/msi/

После этого можно юзать подключение, через ADO .NET (Введение в ADO.NET (https_metanit.com))

 Public Sub CCC_Test_GreenPlum_TestConnection()

 Dim MyCon As New Odbc.OdbcConnection

 MyCon.ConnectionString = "**Driver={PostgreSQL
 ANSI**};database=test001;server=[REDACTED_HOST];port=5432;uid=[REDACTED_USER];sslmode=disable;readonly=0;protocol=7.4;User
 ID=[REDACTED_USER];password=[REDACTED];"

  

 MyCon.Open()

 If MyCon.State = ConnectionState.Open Then

 MsgBox("Connected To PostGres", MsgBoxStyle.MsgBoxSetForeground)

 End If

 End Sub

IDbCommand Interface

*From \<<https://docs.microsoft.com/en-us/dotnet/api/system.data.idbcommand?view=net-5.0*

Обновляем данные в таблице постгресс

 Public Sub CCC_Test_GreenPlum_UpdateValue()

 Dim MyCon As New Odbc.OdbcConnection

 Dim DB = Connection.GetConfigParm("Custom\GreenPlum\GreenplumDB")

 Dim ConnPort =
 Connection.GetConfigParm("Custom\GreenPlum\ConnectionPort")

 Dim Srv = Connection.GetConfigParm("Custom\GreenPlum\GreenplumMaster")

 Dim ConnUser =
 Connection.GetConfigParm("Custom\GreenPlum\ConnectionUser")

 Dim ConnUserPass =
 Connection.GetConfigParm("Custom\GreenPlum\ConnectionUserPassword")

  

 Dim strSQL As String = "UPDATE AccessRights SET dimensionvalue =
 'TestValue003' WHERE username = 'Alex';"

 Dim strUserName As String

  

 MyCon.ConnectionString = "Driver={PostgreSQL ANSI};Database=" + DB +
 ";Server=" + Srv + ";Port=" + ConnPort + ";Uid=" + ConnUser +
 ";Pwd=" + ConnUserPass +";"

  

 MyCon.Open()

 ' Create a database command object

 Using dbCommand As IDbCommand = MyCon.CreateCommand()

 ' Set the SQL statement to execute

 dbCommand.CommandText = strSQL

  

 dbCommand.ExecuteNonQuery()

 End Using

  

 MyCon.Close()

 End Sub

Кавычки в скриптах

Для postgress, чтобы создать роль с точкой в имени, надо заключить имя в кавычки

Чтобы сделать это в Vb.Net надо написать

 '<span class="mark""""" (4 кавычки!!!)</span

Одна кавычки - это ""

Dim MyVar as string = "some text ""hello"" " = some text "hello"

*From \<<https://stackoverflow.com/questions/7767037/how-to-put-data-containing-double-quotes-in-string-variable*


Стандартные процессы для UNSAccountB

Identity Manager 8.0 - Administration Guide for Connecting to Custom Target Systems (oneidentity.com)


Увеличение производительности работы скриптов

Если не проводишь операции на объектами БД (Person, ..) такие, как удаление, изменение и т.п., то лучше не использовать SingleDBObject - это когда пробегаешься по коллекции и делаешь

For Each colUser_unique As IEntity In colUsers_unique

~~dbUser_unique = colUser_unique.Create(Session, EntityLoadType.Interactive)~~

можно получать значение записи так:

strGroupUID = colUser_unique.GetValue("UID_UNSGroupB").String

Причем, запрос формируем так:

Dim qUser = Query.From("UNSAccountBInUNSGroupB").Where(Function(c) c.Column("UID_UNSAccountB") = UID_UNSAccountB).Select("UID_UNSGroupB","UID_UNSAccountB")

[Для FK](onenote:#One%20Identity%20скрипты&section-id=[REDACTED_USER]

dbDepartment = dbPerson.GetFk(Session, "UID_Department").GetParent()


Вычисление Target System type (Custom Target System) по UID_Person

 Public Function CCC_Test_ChildRelation_UNSAccountB (ByVal UID_Person
 As String) As String

 Dim dbPerson As ISingleDbObject

 Dim dbUNSRootB As IEntity

 Dim crUNSAccountB As IChildRelation

 'Dim crDPRNameSpace As IChildRelation

 Dim dbUNSAccountB As ISingleDbObject = Nothing

 Dim dbDPRNameSpace As ISingleDbObject = Nothing

 Dim UID_UNSRootB As String

 Dim strIdent_DPRNameSpace As String

  

 dbPerson = Connection.CreateSingle("Person", UID_Person)

 crUNSAccountB = dbPerson.GetCR("UNSAccountB", "UID_Person")

 If crUNSAccountB.Children.Count = 1 Then

 For Each colElement As IColElem In crUNSAccountB.Children

 dbUNSAccountB = colElement.Create()

 Next

 UID_UNSRootB = dbUNSAccountB.GetValue("UID_UNSRootB")

 dbUNSRootB = Session.Source.Get("UNSRootB", UID_UNSRootB)

 strIdent_DPRNameSpace =
 dbUNSRootB.CreateWalker(Session).GetValue("FK(UID_DPRNameSpace).Ident_DPRNameSpace").String

 Return strIdent_DPRNameSpace

 End If

 return "1"

 End Function

Random число

 Public Function CCC_Test_Random() As String

 Dim value As Integer = CInt(Int((120 \* Rnd())))

 Return value.ToString

 End Function

Расшифровка зашифрованного значения из параметров

Имеем Encrypt значение в параметрах

В скрипте, чтобы его расшифровать надо:

' Caution: This only work if the script is running in the Job Service.

DecryptVal = Session.Decrypt(EncryptedString)

Работать будет только при выполнении с JobServer - поэтому надо сделать расписание и процесс и запускать этот процесс, через Process Automation.

<https://www.oneidentity.com/community/identity-manager/f/forum/27672/onedb-encrypted-how-to-decrypt-an-encrypted-password-on-config-parameters


Вставка переменной в строку

Dim tmpVal As String = Connection.GetSingleProperty("Person","UID_PersonHead","UID_Person = '"+UID_Owner+"'")

---

Извлечь текст из строки до и после символа (.)

 Dim IndexDotInCustomTable As Integer = **CustomTable**.IndexOf(".")

 If (IndexDotInCustomTable \ -1) Then

 SchemaName = CustomTable.Substring(0,IndexDotInCustomTable)

 TableName = CustomTable.Substring(IndexDotInCustomTable + 1)

 Else

 SchemaName = "public"

 TableName = CustomTable

 End If

  

 *Если CustomTable = qwe.ddd, то*

 *SchemaName = qwe*

 *TableName = ddd*

  

 *Если не найдет символ в строке, то* **CustomTable**.IndexOf(".") =
 **-1**

 **---**

Чтение из файла csv имен пользователей (SamAccountName) и запись в файл дополнительной информации по связанным Person

 Public Sub CCC_Test_GetDepartmentFullPath(ByVal InputFile As String,
 ByVal ResultFile As String)Dim strQuery As String = ""

 Dim strQuery1 As String = ""

 Dim strQuery2 As String = ""

 Dim strQuery3 As String = ""

 Dim UID_Person As String = ""

 Dim UID_Department As String = ""

 Dim FullPath As String = ""

 Dim Title As String = ""

 Dim AccountName As String = ""

  

 'Dim tfp As New FileIO.TextFieldParser("C:\temp\users1.txt")

 **FileOpen(1, InputFile, OpenMode.Input)**

 While Not EOF(1)

  

 Input(1, AccountName)

 strQuery = String.Format("SAMAccountName = '{0}'", AccountName)

 Session.Source().TryGetSingleValue(Of
 String)("ADSAccount","UID_Person",strQuery,UID_Person)

  

 strQuery1 = String.Format("UID_Person = '{0}'", UID_Person)

 Session.Source().TryGetSingleValue(Of
 String)("Person","UID_Department",strQuery1,UID_Department)

  

 strQuery2 = String.Format("UID_Person = '{0}'", UID_Person)

 Session.Source().TryGetSingleValue(Of
 String)("Person","Title",strQuery2,Title)

  

 strQuery3 = String.Format("UID_Department = '{0}'", UID_Department)

 Session.Source().TryGetSingleValue(Of
 String)("Department","FullPath",strQuery3,FullPath)

  

 **CCC_Write2Log(ResultFile,AccountName + ";" + FullPath)**

 End While

 End Sub

 **---**

Логирование в вывод JobServer

При отработке скрипта на JobServer информация будет выводиться в его лог

RaiseMessage("Table_count 002: "+Table_count.tostring()+ " RemoveExistsCustomTables 002: " + RemoveExistsCustomTables.ToString())

RaiseMessage(<span class="mark"MsgSeverity.Serious