2.3 One Identity Native DB Connector

22 марта 2021 г.

16:11

Настройка подключения к PostgeSQL

DSN

PostgreSQL35W

Driver={PostgreSQL UNICODE};Database=test001;Server=[REDACTED_HOST];Port=5432;Uid=[REDACTED_USER];Pwd=;

Эту строку прописываем сюда

Create system connection... Database connection Define interface and connection parameters Database providers installed in the system Odbc Data Provider System.Data.Odbc.OdbcFactory, System.Data, Version=4.O.O.O, Culture—neutral, PublicKeyToken=b77a5c561934e089 Connection data Test

Enter the database connection data. Misc database port server Named ConnectionString Security Driver mdw.open.ru {PostgreSQL ANSI)

Либо указываем System DSN которую прописали в Панели управления ODBC

Control Panel System and Security Administrative Tools Set up ODBC data sources (32-bit) Set up ODBC data sources (64-bit) O Searc ODBC Data Source Administrator (64-bit) User DSN System DSN file DSN Drivers Tracing Connection Pooling About System Data Sources Platform 644)it ver PostgreSQL Unicode(x64)

System Filter для Scope 1IM

CanonicalName = 'GreenPlum' and UID_DPRNameSpace = (select UID_DPRNameSpace from DPRNameSpace where Ident_DPRNameSpace = 'GreenPlum')

All schema types UNSRoot8 UNSContainer8 UNSAccount8 UNSGroup8 UNSAccount8 UNSGroup8 UNSAccount81nUNSGro... UNSGroup81nUNSGroup8 Condition Is filtere... 9 9 9 9 System filter Object filter Define two filters to be applied in sequence to the system objects. O The target system filter directly affects the target system. This filter is more effective and should take precedence. The system object filter applies to already loaded system objects. Therefore, it is not as fast but is more flexible than a target system filter in many target systems which are not database-based. System filter Object filter This filter only works when loading existing system objects. ' encl 71 D (select 71 D frc:m

Mapping Rules

Направление синхронизации

Taken from mapping - это значит, что будет браться направление из свойства самого маппинга, а не из конкретного шага маппинга (конкретного маппинга атрибутов)

Ignore mapping direction restrictions on adding

При создании новых объектов игнорируется заданное направление, то есть если задан маппинг имени пользователя только в 1IM при этом флажке значение будет отправлено в таргет систем.

Например, при создании пользователя AD указано напраление GUID только в 1IM. Если этот флаг установлен - данные будут отправляться в AD, что нам не нужно. Нужно убирать этот флаг для свойств, которые генерятся на стороне управляемой системы.

Force mapping against direction of synchronization

Это означает, что если у нас есть workflow провизионнинга и в нем не указана отправка данных GUID в управляемую систему - то с этим флагом, после провизионнинга - данные GUID из таргет системы будут отправлены в 1IM. (после того, как там сформируется GUID)

Detecting rogue modifications

Будет определять изменения в таргет системе, котороые были совершены без ведома 1IM и писать их в лог.

Correct rogue modifications

Будет корректровать изменения в таргет системе на основе данных из 1IM

Членство в группах

Identity Manager 8.0 - Target System Synchronization Reference Guide (oneidentity.com)

Для того, чтобы в 1IM корректно отображалось членство аккаунтов в группах - надо настроить связь M:N (многие ко многим).

Создаем поле в маппинге кастомной таблицы VRT_Members

Stan page G roups X UNSGroup8 (all) [REDACTED_IP]\OnelM Object matching rules Schema property in One Identity Manager cn Property mapping rules Edit propety... Change the schema property of type "Script property". pg_group (all) postg res Property Canonical Name Description DisplayName DistinguishedName GroupType IsForITShop IslTShopOnIy MatchPatternForMe... ObjectGUID Risklndex UID AccProduct UID UNSContainer8 LID UNSGroup8 LID UNSRoot8 VRT Member VRT_ObjectGUIDAsInt... VRT LID UNSRoot8 vrtRevisionDate GO vrtScopeParentRefere... XDateInserted XDateSubItem XDateUpdated XMarkedForDeIetion XObjectKey XTouched Behavior fil@ Information Primary rule Schema propeO' in the target system groname Property CCC VRT DN CCC VRT RootDN CCC vrt UNSRoot8 . groiist groname grosysid Behavior fil@ D' Name Display name Data type Description Read script Write script VRT Members String Multi-value Ignorescriptexecutionerroß Implement the script to read the schema property value. Leave the script empty if the propety is write-only. O You must use S<property name> S to access other schema properties. Example: return SFirstNameS, SLastNameS) Public Function GetVaIue(8yRef schemaproperty as ISchemaProperty, 8yVaI options as SchemaPropertyGetVaIueOption) as StringO $ grolist$ Dim Members As SC ling Dim stIResuIC As SC ling = Members . Replace ( Dim a: IResuIC As SC ling O s CIResuIC stIResuIC . Replace ("Y " a: IResuIC Split (stIResuIC," „ Return a: IResuIC Activate Windows Go to Settings to activate Windows.

Скрипт чтения

Dim Members As String = \$grolist\$

Dim strResult As String = Members.Replace("{","")

Dim arrResult As String()

strResult = strResult.Replace("}","")

arrResult = Split(strResult,",")

Return arrResult

Скрипт записи

Dim VRT_Members As String() = value

Dim str As String = ""

Dim trimChars As Char() = {CChar(",")}

if ( VRT_Members IsNot Nothing AndAlso VRT_Members.Length > 0 ) then

For Each VRT_Member As String in VRT_Members

str = str & "," & VRT_Member

Next

str = "{" & str.TrimStart(trimChars) & "}"

\$grolist\$ := str

Else

\$grolist\$ := Nothing

End If

Затем, в таблице UNSGroupB создаем поле M:N (VRT_Member)

Start page G roups X UNSGroup8 (all) [REDACTED_IP]\OnelM Edit propety... Change the schema property of type "Members of M:N schema types" Property CanonicalName Description DisplayName DistinguishedName GroupType IsForITShop IslTShopOnIy MatchPatternForMe... ObjectGUID Risklndex UID AccProduct UID UNSContainer8 LID UNSGroup8 LID UNSRoot8 VRT Member VRT_ObjectGUIDAsInt... VRT LID UNSRoot8 vrtRevisionDate GO vrtScopeParentRefere... XDateInserted XDateSubItem XDateUpdated XMarkedForDeIetion XObjectKey XTouched Behavior fil@ fil@ D' Name Display name VRT Member VRT Member Ignore case Enable relativecomplement (required for member rues) O Tryto mark theobjectfordeletion(outstardiro LINSAcccunt81nLlNSGrcup8 (all) UNSGroup81nUNSGroup8 (all) Member key properties must be unique across schema types. Only the first member found is assigned! Base schema type UNSGroupB M:N schema type UNSAccount31nUNSGroup3 (all) UD UNSGroup3 UNSAccount3 Members U NSAccountB Prima k ro ObjectGUID Additional k ro ties o ional AccountName Canonical Name Description

Stan page G roups X UNSGroup8 (all) [REDACTED_IP]\OnelM Edit propety... Change the schema property of type "Members of M:N schema types" Property CanonicalName Description Display Name DistinguishedName GroupType IsForITShop IslTShopOnIy MatchPatternForMe... ObjectGUID Risklndex UID AccProduct UID UNSContainer8 LID UNSGroup8 LID UNSRoot8 VRT Member VRT_ObjectGUIDAsInt... VRT LID UNSRoot8 vrtRevisionDate GO vrtScopeParentRefere... XDateInserted XDateSubItem XDateUpdated XMarkedForDeIetion XObjectKey XTouched Behavior fil@ fil@ D' Name Display name VRT Member VRT Member Ignore case Enable relativecomplement (required for member rues) O Tryto marktheobjectfordeletion(outstardiro UNSAccount81nUNSGroup8 (all) UNSGrcup81nUNSGrcup8 (all) Member key properties must be unique across schema types. Only the first member found is assigned! Base schema type UNSGroupB UNSGroup31nUNSGroup3 (all) UD UNSGroup3Parent M:N schema type UD UNSGroup3ChiId Members UNSGroupB Prima k ro ObjectGUID Additional k ro ties o ional CanonicalName Description DisplayName

Делаем маппинг VRT_Member - VRT_Members

Edit mapping rule... Edit the rule of type (Value comparison rule). Rule name Display name Mappirrg directon Description One Identity Manager Schema propety O VRT Member VRT Members VRT Member < > VRT Members One Identity Manager Ignore map p i ng direction restrictions on Force map p i tv against n ofsyrrchro nizabon Detect rogue modificatiom Ignore case sensitivity Disable merge mode support Correct rogue modificatiom Target system Schema propety VRT Member Do notoverwrite Hardlefirstpropertyvalueassiroevalue VRT Members Do notoverwrite Hardlefirstpropertyvalueassiroevalue

Start page G roups X UNSGroup8 (all) [REDACTED_IP]\OnelM Property Canonical Name Description DisplayName DistinguishedName GroupType IsForITShop IslTShopOnIy MatchPatternForMe.. ObjectGUID Risklndex UID AccProduct UID UNSContainer8 UD UNSGroup8 •a LID UNSRoot8 VRT Member VRT_ObjectGUIDAsInt... VRT LID UNSRoot8 Behavior Object matching rules Schema property in One Identity Manager cn Property mapping rules Schema property in One Identity Manager Distinguished Name ObjectGUIDAsInteger VRT LID UNSRoot8 Member Information Primary rule Information Schema propeO' in the target system groname Schema propeO' in the target system groname CCC VRT DN grosysid CCC UNSRoot8 Name VRT Members pg_group (all) postg res Property CCC VRT DN CCC VRT RootDN CCC vrt UNSRoot8 groiist groname grosysid VRT Members vrtPrimaryKey Behavior fil@ fil@ fil@


В общем, надо после сопоставления атрибутов VRT_Member - VRT_Member сделать процесс на Update UNS_GroupB ADHoc и в поле ForceSyncOf для шага ProjectorComponent - AdHocProjection указать виртуальное поле VRT_Member (на стороне UNS_GroupB которое меняется)

I have added the virtual attribute to the ForceSyncOf parameter of the "Update Account" step of the "ADS_ADSAccount_Update/(De-)activate" process.

That seems to do the trick.

From \<https://www.oneidentity.com/community/identity-manager/f/forum/26629/virtual-mapping-attribute-object-reference-not-provisioned-in-adhoc>

Param eters Parameter name U date user CSV GrænPlum Parameterualue CausingEntityPatch Connectionprouider ConnectionString UID DPRProjectionco... UID DPRsystem'%riabl... ForceSyncOf Authenticationstring = VID = VID = DPRProjectionConfigurationl.ToString0 = DPRSystemhÆriabIeSetl.ToString0 Member" = Connectionlnfo.AuthString

Identity Manager 8.1.4 - Target System Synchronization Reference Guide (oneidentity.com)


Чтобы работало добавление и удаление для поля, а не перезатирание при Update группы, надо для поля M:N (VRT_Members) поставить галку

"Enable relative complement handling (requred for member rules)"

Edit properw... Change the schema property of type "Members of M:N schema types'. Display name YR T Members Ignore case *Enable relatiue complement handling (required for member Try to mark the object for deletion (outstanding) UNSAccountBInUNSGroupB (all)

НО! маппить в таком случае надо в целевой системе с полем типа SystemObjectData (свойство из целевой системы, у которого стоят галки

IsMultiValue и IsReference

Edit properw... Change the schema property. Display name Base property Data type Access constraint Mandatory Maximum length Description Referenced schema types uttMembersAIIDn DN of all group members (SID for F SP only) None Multi-ualue Unique builtinDomain contact. domainDNS msDS-PasswordSettin s organizationall_lnit Is reference Reuision counter

Edit mapping rule... Edit the rule of type (Multi-reference mapping rule). Display name Mapping dire&on Description One "entity Manager Schema properw Members OUT Members OUT Target system O Ignore mapping direction restrictons on adding O Detect. rogue modificatons vrtMembersAIIObj Correct. rogue modificatons Do not ouenmrite Member filter Target system Schema properw Member filter Only include these Name computer contact inetOrgPerson O builtinDomain vrtMembersAIIDn Do not ouenmrite o Exclude these

Описание в доке OneIM Synchronization Technology (Multi-reference mapping rule, Enable relative complement handling)


Если не надо каждый раз перезатирать членство, то нужно поставить галки Enable merging

0 SW MS wobsn3 0

В таком случае, операции по добавлению в группу будут отображаться в таблице DPRMemberShipAction.


Did you tried to use the events ASSIGN and REMOVE instead of INSERT and DELETE? For M:N tables these are the ones to go. In addition, what type of connector are you using? 

From \<https://www.oneidentity.com/community/identity-manager/f/forum/29657/adhocprojection-works-for-insert-but-not-for-delete>


Если членство хранится не в группе, а в пользователе (он член групп) то это сложнее - предлагают обратиться в ТП

How does AccountInGroup Ad-Hoc Provisioning work? => how to update multi-valued attrib on account not group - Forum - Identity Manager Community - One Identity Community


Can forcesyncof functionality inserts an account at target if not found?

From \<https://www.oneidentity.com/community/identity-manager/f/forum/32031/can-forcesyncof-functionality-inserts-an-account-at-target-if-not-found>


Для AdHoc преобразование событий Assign/Remove в Insert/Delete

If you move to ASSIGN/REMOVE events then that would also have to align correctly. If needed, there is an example with the Azure Connector pre-script where it transforms ASSIGN/REMOVE to INSERT/DELETE before calling Get_AdHocData(), so that the Provisioning process operation would have 'Insert' in it.

Dim evt as String = EventName

If evt.Equals("Assign", StringComparison.OrdinalIgnoreCase) _

OrElse evt.Equals("HandleOutStanding", StringComparison.OrdinalIgnoreCase) then

evt = "Insert"

ElseIf evt.Equals("Remove", StringComparison.OrdinalIgnoreCase) then

evt = "Delete"

End If

Imports System.Collections.Generic

Dim data As IDictionary(Of String,string) = DPR_GetAdHocData( _

\$FK(UID_AADUser).FK(UID_AADOrganization).XObjectKey\$, _

"AzureAD","",evt)

Sync Project - inserting objects works but not the update - Forum - Identity Manager Community - One Identity Community


Трабла с событием Assign ADSAccountBInADSGroupB - не запускается ADHoc Provisionning на это событие

Надо во 1х заменить Assign на Insert. чтобы передавался в проект синхронизации (В PreScript)

Dim evt as String = EventName

If evt.Equals("Assign", StringComparison.OrdinalIgnoreCase) _

OrElse evt.Equals("HandleOutStanding", StringComparison.OrdinalIgnoreCase) then

evt = "Insert"

End If

data = DPR_GetAdHocData(\$FK(UID_UNSGroupB).FK(UID_UNSRootB).XObjectKey\$,"DB","",evt)

Во вторых - убрать Condition из шага процесса AdHoc Provisioning, так как он в values("NeedExecute") пишет False почему то


Сначала создает Single Object Operation - указываем событие и потом, в pre-script AdHoc процесса, который на событии таблицы - указываем это событие в

DPR_GetAdHocData

data = DPR_GetAdHocData(\$FK(UID_UNSAccountB).FK(UID_UNSRootB).XObjectKey\$,"DB","","Delete")

From \<https://support.oneidentity.com/technical-documents/identity-manager/8.1.1/target-system-synchronization-reference-guide/40#TOPIC-1246704>


При провижининге игнорит отправку AccountName UNSAccountB в usename Postgres

Для правила CN \<- usename надо убрать галку Ignore mapping direction restriction on adding

Edit mapping rule... Edit the rule of type (Value comparison rule). Rule name Display name Mappirrg directon Description One Identity Manager Schema propety O cn usename Name < > usename One Identity Manager Ignore map p i ng direction restrictions on additv Force map p i tv against direction nizabon Detect rogue modificatiom Ignore case sensitivity Disable merge mode support Correct rogue modificatiom Target system Schema propety Z] Do notoverwrite Cl Hardlefirstpropertyvalueassinglevalue usename Do notoverwrite Cl Hardlefirstpropertyvalueassinglevalue


Не работает Force mapping against direction of synchronization - не обновляется ObjectGuid после провижиннинга

Сделал событие Read на UNSAccountB и UNSGroupB.

Там запилил процесс ProjectorComponent - UpdateProjection

Read user Green Plum Red in m Param eters Parameter name Connectionprovider ConnectionString UlD_DPRProjectionco. UlD_DPRsystemVanabl. EntityToUpdateKey Authenticationstring EntityToUpdatePatch OverrideVariabIes TargetSystemConnectE... UD DPRJournal Parameter value Value = VIO Connectionprovider'l Value = VID_GetVaIueOfDiaIogdatabasesCConnectionString•) Value = Value = SX0bJectKeyS Value = Value = Connectionlnfo.AuthString Value = Value = Hidden E ncryp ted Partial en..

Затем, в событии Insert добавил вызов события Read после создания пользователя / группы (HandleObjectComponent - FireGenEvent)

Param eters Parameter name Authenticationstring Connectionprovider ConnectionString Event Name ObjectType WhereCIause ParamNameI CCC_UNSAccou n tB_ Insert_Ad Hoc Create user GreenPIum Cræte Read lum user Update D Value = •Read Parameter value 'value = Connectionlnfo.ÅuthString Value = Connectionlnfo.ConnectionProvider Value = Connectionlnfo.ConnectionString Value = •UNSAccounta• Dim f As ISqIFormatter = Connection.SqIFormatterVaIue = f.ComparisonCcn•, ValWpe.String, CompareOperator.EquaI) Value = [Name of parameter]

Маппинги

Navigation Mappings Groups Users Group - user Group in Group Group - user (filtered) Group - Group (filtered) Stan page G roups X UNSGroupa (all) [REDACTED_IP]\OnelM Property Canonical Name Description DisplayName DistinguishedName GroupType IsForITShop IslTShopOnIy MatchPatternForMembership ObjectGUID Risklndex UID AccProduct UID UNSContainer8 LID UNSGroup8 LID UNSRoot8 VRT Member VRT_ObjectGUIDAsInteger VRT LID UNSRoot8 vrtRevisionDate Behavior fil@ Object matching rules Schema property in One Identity Manager cn VRT ObjectGUIDAsInteger Property mapping rules Schema property in One Identity Manager Distinguished Name VRT ObjectGUIDAsInteger VRT LID UNSRoot8 Information Primary rule Alternate rule Information Schema propeO' in the target system groname g rosysid Schema propeO' in the target system groname CCC VRT DN grosysid CCC Vit UNSRoot8 Name pg_group (all) postg res Property CCC VRT DN CCC VRT RootDN CCC vrt UNSRoot8 grolist groname grosysid VRT Members vrtPrimaryKey Behavior fil@ fil@

Navigation Mappings Groups Group - user Group in Group Group - user (filtered) Group - Group (filtered) Stan page Users X UNSAccount8 (all) [REDACTED_IP]\OnelM Property AccountDisabled AccountExpires AccountName CanonicalName Description DisplayName DistinguishedName FirstName dentityType IsGroupAccount IsPriviIegedAccount Last Logon Last Name Behavior Object matching rules Schema property in One Identity Manager AccountName VRT ObjectGUIDAsInteger2 Property mapping rules Schema property in One Identity Manager AccountName DistinguishedName VRT ObjectGUIDAsInteger2 VRT LID UNSRoot8 pg_user (all) postg res Information Primary rule Alternate rule Information Schema propeO' in the target system usename usesysid Schema propeO' in the target system use name use name CCC VRT DN usesysid CCC UNSRoot8 Name Property CCC VRT DN CCC VRT RootDN CCC vrt UNSRoot8 usecreatedb usename userepl usesuper usesysid valuntil vrtPrimaryKey Behavior fil@

Navigation Mappings Groups Users Group - user Group in Group Group - user (filtered) Group - Group (filtered) Stan page Group - User (filtered) UNSAccount81nUNSGroup8 (all) [REDACTED_IP]\OnelM Property RiskIndexCaIcuIated LID UNSAccount8 UID_UNSGroup8 VRT_Group VRT_GroupAsInteger VRT_GroupName VRT Member VRT_MemberAsInteger VRT MemberName vrtRevisionDate XDateInserted XDateUpdated XlsInEffect XMarkedForDeIetion XObjectKey XOrigin XTouched XUserInserted XUserUpdated x Behavior Object matching rules Schema property in One Identity Manager VRT_Group, LID UNSGroup8, VRT Member, LID UNSAccount8 Property mapping rules Schema property in One Identity Manager VRT_Group VRT Member pg_auth_members_users (all) postg res Information Primary rule Information Schema propeO' in the target system VRT_roIeidAsString, roleid, VRT_memberAsString, member Schema propeO' in the target system VRT_roIeidAsString VRT_memberAsString Property admin_option grantor member roleid VRT_memberAsString VRT_roIeidAsString vrtPrimaryKey Behavior

Navigation Mappings Groups Users Group - user Group in Group Group - user (filtered) Group - Group (filtered) Stan page Group - Group (filtered) UNSGroup81nUNSGroup8 (all) x [REDACTED_IP]\OnelM Property LID UNSGroup8ChiId LID UNSGroup8Parent VRT_Group VRT_GroupMember vrtRevisionDate XDateInserted XMarkedForDeIetion XObjectKey XTouched XUserInserted XUserUpdated Object matching rules Schema property in One Identity Manager VRT_Group, UID UNSGroup8Parent, VRT_GroupMember, UID Property mapping rules Schema property in One Identity Manager VRT_Group VRT_GroupMember pg_auth_members_groups postg res Behavior Information Primary rule Information Schema propeO' in the target system VRT_roIeidAsString, roleid, VRT_memberAsString, member Schema propeO' in the target system VRT_roIeidAsString VRT_memberAsString Property admin_option grantor member roleid VRT_memberAsString VRT_roIeidAsString vrtPrimaryKey Behavior

Трабла с проверкой проекта (verify project)

Поставил в Workflow

Edit workflow... Edit a synchronization workflow. General Wo rkfiowdisp lay name Synchro nization indirection Revision filtering Exception hardling Deperdercy• re-so ution Description InitialSync Defined by execution Use revision filter Continue on error Manual Log variablesetcontents O O

Трабла с тем, что не заполнялся ObjectGUID у UNSAccountB после создания и вызова события Read.

Решилась путем настройки паузы между созданием и чтением атрибута = 2 мин.

Navigation Process Orchestration Processes Custom processes DialogScheduIe DPRMemberShipActlon UNSAccount8 ccc CCC U Hoc ccc g] ccc U NSAcco _Script UNSAccount81nUNSGroup8 ccc g] ccc UNSGroup8 ccc ccc ccc ccc UNSGroup81nUNSGroup8 ccc ccc Process automation Objects without processes Value = •n• O Getting Started Configuration parameters CCC_UNSAccou n tB_ Insert_Ad Hoc Create user Green Plum Cræte in GrænPlum Read Green Plum user Ll "Ste ObjEtGl_l D Getting Started One Identity Manager Schema Permissions Process Orchestration Script Library user Interface Mail Templates Param eters Parameter name Connectionprovider ConnectionString Delaylntervall DelayTime JoblD Parameter value Value = Connectionlnfo.ConnectionProvider Value = Connectionlnfo. ConnectionString Value = 2 Value = JoblD

Фильтр UNSAccountBInUNSGroupB

UID_UNSAccountB IN (select UID_UNSAccountB from UNSAccountB JOIN UNSRootB ON UNSAccountB.UID_UNSRootB = UNSRootB.UID_UNSRootB where UNSRootB.Ident_UNSRoot = 'GreenPlum2')

Для групп в группах

UID_UNSGroupBChild IN (select UID_UNSGroupB from UNSGroupB JOIN UNSRootB ON UNSGroupB.UID_UNSRootB = UNSRootB.UID_UNSRootB where UNSRootB.Ident_UNSRoot = 'GreenPlum1')

UID_UNSGroupBChild IN (select UID_UNSGroupB from UNSGroupB JOIN UNSRootB ON UNSGroupB.UID_UNSRootB = UNSRootB.UID_UNSRootB where UNSRootB.Ident_UNSRoot = '\$UNSRootB_Name\$')

Фильтр UNSRootB

CanonicalName = '\$UNSRootB_Name\$' and UID_DPRNameSpace = (select UID_DPRNameSpace from DPRNameSpace where Ident_DPRNameSpace = '\$Ident_DPRNameSpace\$')

В \$ - переменные


Экспорт проекта синхронизации

Start the Synchronization Editor with option "-d" using a command line:

E.g.: C:\Program Files\One Identity\One Identity Manager\SynchronizationEditor.exe -d

When the Synchronization Editor opens there will be additional save and export options:

Synchronization Editor ( Help *Commit to database • Navigation Configuration G Remote connection... Start page General No synchronization project loaded. Select a synchronization project from the list below by double clic Delete Synchronization projects Start a new synchronization project Select to create a new synchronization project.

From \<https://support.oneidentity.com/identity-manager/kb/187752/how-to-export-the-synchronization-project-shell-from-the-synchronization-editor>


Перенос проекта синхронизации (экспорт/импорт)

  1. Сделать бекап!

  2. Установить драйвер ODBC (psqlodbc_13_00_0000) на админскую станцию и на JobServer!

  3. [Сделать экспорт проекта синхронизации](onenote:#One%20Identity%20Native%20DB%20Connector&section-id=[REDACTED_USER]

  4. Сделать экспорт Custom Processes

  5. Проверить, что есть необходимый компонент для проекта синхронизации (Native Database Connector, например)

  6. Импортировать проект синхронизации

  7. Настроить подключение к БД (Target System -> Edit Connection)

  8. В Manager Создать Target System Type (указать таблицы для синхронизации и group merging behavior - если необходимо) и сами Custom Target Systems

  9. Добавить Base Object в проект синхронизации и указать JobServer (у него должен быть указан тип под этот коннектор!)

  10. Добавить триггеры для операций (Insert/Update/Delete) AdHoc (в дизайнере - Single Object Operations)

  11. Импортировать Custom Processes чтобы связать операции с UNS таблицами и вызов Workflow

  1. Сделать Acc Definitions!

Трабла с тем, что при назначении Acc Definition не создается UNSAccountB и ругается на политику паролей

Причина в том, что для дефолтной политики не был указан дефолтный пароль и при сработке скрипта onSaving брался этот null пароль и он не подпадал под эту же политику.

Создал отдельную политику паролей для этого UNSRootB

Designer - (Main Database) Qatabase Object filter Yiew Help e aack• *Next •I O Commit to database Navigation Base Data General Security settirrgs Authentication modules Database server permissions PrOgrams "E Web server configurations "E HTML applications Connection data OAuth 2.0,'OpenID Connect configuration f' Password policies Restricted passwords • Installation Localization Advanced Getting Started One Identity Manager Schema Permissions Process Orchestration Script Library user Interface Mail Templates Documentation Base Data Favorites Search DefaultInitlaIPassword Y • Process Orchestration Password policies List Editor UNSAccount8 Active Directory password policy GreenPIum password policy One Identity Manager password policy password policy for central password of employees GreenPlum password policy Schema Editor Description Predefined password po Predefined password po Predefined password po Display name Description Erro r message Assignment Passwo rd co umn Ap p to Password poloj GreenPIum password policy Cl Default policy Password Character classes Scripts Remove Test Assignments Apply to GreenPIum I (GreenPIumIl LINSAccounta - Password GreenPIum I (GreenPIumI) GreenPIum password policy Passwo rd co um n LINSAccountS - Password


Удаление учетной записи без ожидание периода Deferred

Commit to database Navigation Identity Manager Schema ShoppirrgCartOrder ShoppirrgCartPattern ShoppingCartPatternItem TS&AccountDef TS3AccountDefHas3ehavior TS83ehavior TS81TData TS81TDataMapping TS8PersonUsesAccount UNSAccountB UNSAccount8HasUNSltem8 UNSAccount81nUNSGroup8 UNscontainer8 UNSGroup8 UNSGroup3collection UNSGroup8Exclusion UNSGroup8HasUnsItem8 UNSGroup81nUNSGroup8 UNSItem8 UNSRoot8 WorkDesk WorkDeskHasESet WorkDeskState Getting Started One Identity Manager Schema Permissions Process Orchestration Script Library user Interface Mail Templates Documentation Next • „ Search DefaultImtlaIPassword 10036 • I V X O UNSAccounta Col um ns UNSAcc Columns AccountDisabIed AccountExpires AccountName CanonicalName Description DisplayName DistinguishedName FirstName Identitywpe IsGroupAccount IsPrwiIegedAccount Table properties Display name (sirrgular) Display name (plural) Display pattem Display pattern (10 ng) Hierarch] path Remarks Cache information Prep rocesso r co ndition Deferred deletion [days] Icon &ackgro co Ior Schema Editor X i Display name user account is disabled Account expiry date Login name Canonical name Name Description Display name Distinguished name First name Identity Groups can be inherited Privileged user account user account user accounts UNSRoot81Ull not Ioa Disabled by preprocessor • UNS Acco unt

Не запускается Update AdHoc

Надо из условия шага убрать

Value = Cbool(values("NeedExecute"))

Не обновлялся ObjectGUID после создания пользователя или группы

Странная штука, стандартный метод отрабатывает не всегда

Property UNSAccount8 (all) [REDACTED_IP]\OnelM usesysid Object matching rules Schema property in One Identity Manager Account Name VRT ObjectGUIDAsInteger2 Property mapping rules Schema property in One Identity Manager AccountName DistinguishedName IsGroupAccount VRT_ObjectGUIDAsInteger2 VRT LID U VRT CCC Ac Edit mapping rule.. Edit the rule of type (Value comparison rule). pg_user (all) postg res Behavior Information Primary rule Alternate rule Information Schema propeO' in the target system use name usesysid Schema propeO' in the target system use name use name CCC VRT DN CCC_isGroupAccount usesysid Property Behavior Description DisplayName DistinguishedName First Name dentityType IsGroupAccount IsPriviIegedAccount Last Logon Last Name MatchPatternForMe... MemberOf ObjectGUID assword PWDLastSet Riskl ndexCaIcuIated UID Person LID TS8AccountDef LID TS88ehavior LID UNSAccount8 UID UNSContainer8 LID UNSRoot8 VRT CCC AccountDis... @ Member VRT ObjectGUIDAsInt... CCC_isGroupAccount @ CCC VRT DN CCC VRT RootDN CCC vrt UNSRoot8 rolconnlimit use createdb usename userepl usesuper valuntil VRT CCC RolConnLi... vrtPrimaryKey Activ e Windows fil@ fil@ Rule name Display name Mappirrg directon Description One Identity Manager Schema propety ObjectGUID_usesysid Object GUID < > usesysid One Identity Manager Ignore map p i ng direction restrictions on additv Force map p i tv against direction nizabon Detect rogue modificatiom Ignore case sensitivity Disab le merge mode support VRT ObjectGUIDAsInteger2 Cl Correct rogue modificatiom Target system Schema propety Go to S ttings to activate Windows. 172.25.32.19510nelM (Main Database) viadmin

Пришлось делать ожидание в процессе ADHoc и затем чтение объекта для обновления ObjectGUID

UNSAccountB GP Insert Ad Create user Green Plum in Plum Read Green Plum user Ll "Ste ObjEtGl_l D 10

В процессе чтения из БД важно установить ProjectorComponent - UpdateProjectionSingle

Read group Green Plum Red m Process step properties ;eneral Generation Process tracking Error handling Extended 'rocess task ription 'rocess information 'rioritj Read group GreenPIum Pro dat±ProæctionSin Read groupin GreenPIum Full process tracking Notification (error) Notification (success) Process history D&Queue does not wait Disabled by preprocessor

-----

И эта штука не всегда работает(((

В общем, пока остановился на том, что после создания пользователя - обновляю ему ObjectGUID рандомным числом

В Pre-Script процесса

Dim rndObjectGUID As Integer = CInt(Int((50000 * Rnd())))

values("rndObjectGUID") = rndObjectGUID

Update ObjectGUID Param eters Parameter name Authenticationstring Connectionprovider ConnectionString Objectwpe WhereCIause val_0bjectGUlD ConnectionVariabIes Parameter value Value = Connectionlnfo.AuthString Value = Connectionlnfo.ConnectionProvider Value = Connectionlnfo. ConnectionString Value = •UNSAccounta• Dim f As ISqIFormatter = Connection.SqIFormatterVaIue = f.UidComparisonCUID_UNSAccoun.. Value = valuesCrndObjectGUICY) Value = •VarllVar21VarY

Запускается процесс обновления пользователя и подгружает правильный ObjectGUID

Преобразование даты в строку с последующим фильтром строки

Property UNSAccount8 (all) [REDACTED_IP]\OnelM Behavior Object matching rules Schema property in One Identity Manager AccountName VRT ObjectGUIDAsInteger2 Property mapping rules Schema property in One Identity Manager Account Name DistinguishedName IsGroupAccount VRT ObjectGUIDAsInteger2 VRT LID UNSRoot8 VRT AccountExpiresAsStri Edit propety... pg_user (all) postg res Information Primary rule Alternate rule Information Schema propeO' in the target system usename usesysid Schema propeO' in the target system use name use name CCC VRT DN CCC_ isGroupAccount usesysid CCC UNSRoot8 Name VRT valuntil Property Behavior AccountName Canonical Name Description DisplayName DistinguishedName FirstName dentityType IsGroupAccount IsPriviIegedAccount Last Logon Last Name MatchPatternForMe... MemberOf ObjectGUID assword PWDLastSet RiskIndexCaIcuIated UID Person LID TS8AccountDef LID TS88ehavior LID UNSAccount8 UID UNSContainer8 LID UNSRoot8 VRT_Accou nt ExpiresA... VRT CCC AccountD15... • CCC_isGroupAccount @ CCC VRT DN CCC VRT RootDN CCC vrt UNSRoot8 rolconnlimit usecreatedb usename userepl usesuper usesysid valuntil VRT CCC RolConnLi... fil@ Change the schema property of type "Data conversion". D' Name Display name aase propertj Description New data type Special date format La ng cage code Time zone of base value VRT Account expiry date AccountExpires Expiry date for the user account. String my MM-dd use default language [SO format Activ Go to S vrtPrimaryKey e Windows ings to activate Windows. Moscow, St. Petersburg

Edit propety... Change the schema property of type "Script property". D' Name Display name Data type Description Read script Write script VRT valuntil VRT valuntil String Multi-value Ignorescriptexecutionerroß Move to script library Apply your script to write the schema property value. Leave the script empty if the propety is read-only. O You must use S<propety name> S to access other schema properties. Example: SLastNameS CStr(vaIue)SpIit(" SFirstNameS Public Sub SetVaIue(8yRef schemaproperty as ISchemaProperty, 8yRef value as String, 8yRef options as SchemaProperty•SetVaIueOption) If value "0001-01-01" Then val ue End If End Sub Debug Compile Cancel

Read script пуст, так как только provisioning работает в custom target system

И ещё фишка- при обновлении пользователя в скрипте коннектора

If column = "valuntil" Then

sql.AppendFormat("ALTER ROLE {0} VALID UNTIL {1};", """" & record.GetValue("usename", "") & """", "'" & record.GetValue("valuntil", "") & "'")

sql.AppendLine()

End If

Дату надо заключать в аппострофы, а не в кавычки!!!

Откат изменений из целевой системы

В SyncEditor для изменений в целевой системе делаем MarkAsOutstanding

Navigation Workflows InitialSync Provisioning Stan page General InitialSync x Initia[Sync Wo lay name [7 Edit Workflow Groups Users 172.25.32.1g5\OneIM UNSAccount8 (all) Mappirrg step generated by template Group - user (filtered) Group - Group (filtered) Edit synchronization step... Modify the synchronization step. General Processing Quotas Rule filter Extended Run the following methods in the target system when synchronizing from One Identity Manager to the target system: Objects only found in One Identity Manager are: Objects only found in the target system are: Objects with modfied properties: Objects without modfications: Do nothing Do nothing Do nothing Do nothing Run the following methods in One Identity Manager when synchronizing from the target system to One Identity Manager: Objects only found in the target system are: Objects only found in One Identity Manager are: Objects with modfied properties: Objects without modfications: Insert Delete MarkAsOutsta ng Do nothing

Таким образом, изменившиеся учетки будут попадать в

Manager - (Main Database) Database Object Yiew Help Home Back • Forward • Database search New Navigation Custom Target Systems csvl (csvl) GreenPIum I (GreenPIumI) user accounts Groups Container structure Permissions contro Is GreenPIum 2 (GreenPIum2) Target system synchronization: CSV Target G}Gtem onchronization: GreenPIum UNSAccount8 UNSAccount81nUNSGroup8 UNSGroup8 UNSGroup81nUNSGroup8 Troubleshooting x Result list GreenPIum X Delete Table 'Object user accounts (I)

Если нажмем на Publish для учетки, то сработает событие HandleOutstanding (HANDLEOUTSTANDING - UNSAccountB), которое будем ловить отдельным процессом

Designer - (Main Database) Qatabase Process Process step Yiew Help a Commit to database •e Sack • Next • • Search Navigation Process Orchestration Processes - Custom p rocesses ADSAccount ccc DialogScheduIe DPRMemberShipAction PersonWa ntsOrg UNSAccount8 ccc CCC UNSAccountB GP_ ccc ccc ccc UNSAccount8 Insert CreateRoIeInGreenPIum UNSAccount81nUNSGroup8 UNSGroup8 UNSGroup81nUNSGroup8 Process automation Objects without processes Process components Object events Getting Started One Identity Manager Schema Permissions Process Orchestration Script Library user Interface Mail Templates Documentation Process - n tB_GP Update user GrænPIum Llpdäte Process properties General process tracking Name Table Description Pre-script for generatirrg Generatirrg cordition Remarks Extended LINSAccounta If Not CSOOI (Connection. Variables ("FULLSYNC UNSRoocB) .NamespaceManagedBy:st Value Not CSOOI (Connection. Variables $FK (OID UNSRootB) . NamespaceManagecIBy: St Iinv; Do notgenerate Disabled by preprocessor

Чтобы работал Publish надо поставить галку Can be Published!

Manager - (Main Database) Database Object Yiew Help Back • *Forward • *Database search Z New R Save Home Navigation Custom Target Systems GreenPIum 2 (GreenPIum2) Target system synchronization: CSV [35 Target system synchronization: Greenplum UNSAccount8 UNSAccount81nUNSGroup8 UNSGroup8 UNSGroup81nUNSGroup8 Troubleshooting Synchronization logs [30" &asic configuration data ' Target system types x Target system types (2) Recently used CSV csv GreenPIum GreenPIum X Target systemtvpes: assignedtables LINSAccountE UNSAccountE1nUNSGroupE UNSGroupE UNSGroupE1nUNSGroupB Can be published Merge mode Condition

Pre-Script

If Not CBool(Connection.Variables("FULLSYNC")) AndAlso _

\$FK(UID_UNSRootB).NamespaceManagedBy:String\$.Equals("VISYNC",StringComparison.OrdinalIgnoreCase) Then

Imports System.Collections.Generic

Dim data As IDictionary(Of String,string) = Nothing

values("AdHocDataFound") = False                

values("NeedExecute") = False

values("SystemType") = "DB"

Dim dbDataFound As Boolean = true

' try to get DB data:

' the second parameter has to correspond to the SystemType field of the DPRSchema.

'

Try

data = DPR_GetAdHocData(\$FK(UID_UNSRootB).XObjectKey\$,"DB","","Update")

'values("SyncType") = "DB"

Catch ex As Exception

dbDataFound = false

End Try

If Not data is Nothing

values("AdHocDataFound") = True

values("NeedExecute") = DPR_NeedExecuteWorkflow(data("ProjectionConfigUID").ToString(),entity)

values("ObjectKey") = New DbObjectKey(base.Tablename,\$UID_UNSAccountB\$).ToXmlString()

values("UID_DPRSystemVariableSet") = data("VariableSetUID")

values("UID_DPRProjectionConfiguration") = data("ProjectionConfigUID")

values("UID_QBMServer") = data("ExecutionServerUID")

values("cn") = \$cn\$

End if

'VID_Write2Log("C:\temp\GreenPlum.txt", \$AccountName\$ & " will created in GreenPlum " & "AdHocDataFound=" & CStr(values("AdHocDataFound")).toString() )

End If

Condition

Value = Not CBool(Connection.Variables("FULLSYNC")) AndAlso _

\$FK(UID_UNSRootB).NamespaceManagedBy:String\$.Equals("VISYNC",StringComparison.OrdinalIgnoreCase) AndAlso _

Cbool(values("AdHocDataFound"))

--

Затем, запускаем процесс Update user GreenPlum

Process - • CCC UNSAccountB GP Handleou nding Update user GreenPIum Update Process step properties General Generation Process tracking Error handling Extended Name Process task Description Process information Prioritj Ll dat± ProjectorComponent - AdHocProjectionSingIe Update user GreenPIum Full process tracking Notification (error) Notification (success) Process history D&Queue does not wait Disabled by preprocessor

Process -CCC • CCC UNSAccountB GP Handleou nding U pdate user Green Plum Update Process step properties General Generation process tracking Error handling Extended Pre-script for generatirrg Generatirrg cordition Server furrction Script for server selection Prep rocesso r co nd ition Val ue values ("OID QBMServeI")

Process -CCC • CCC UNSAccountB GP Handleou nding U pdate user GreenPIum Update u Param eters Parameter name Parameter value CausingEntit}Patch 'value = Connectionprovider ConnectionString JID DPRProjectionConfiguration UlD_DPRsystemVanableset ForceSyncOf Authenticationstring MemberShipActionPartionSize Value= 1024 OverrideVariabIes TargetSystemConnectError UD DPRJournal Process - CCC Value = Value = VID_GetVaIueOfDiaIogdatabasesCConnectionString•) Value = Value = Value = •AccountName,cn• Value = Connectionlnfo.AuthString Value =

В ForceSyncOf указываем поля для принудительного обновления в написании, как в ObjectBrowser!

Failover

Failover mechanism for Active Directory connector - Forum - Identity Manager Community - One Identity Community

You could convert the CP_ADServer variable into a scripted variable in the sync project (for a FullSync my comments from above apply. No synchronization optimization allowed then).

In the script, you could determine a DC of your domain and do some other checks as well (ping, login, whatsoever).

The sample script is just taking the first domain controller it gets from the collection: Further enhancements would be to check the DC classes, ping time, etc.

Fullscreen

References System.DirectoryServices.dll

Imports System.DirectoryServices.ActiveDirectory

Dim RootDN as String = VariableSet.Item("CP_ADRootdn")

Dim DomainName As String = RootDN.Replace(",dc=",".").Replace("dc=","")

Dim DomainCon As New DirectoryContext(DirectoryContextType.Domain, DomainName)

Dim DCs As DomainControllerCollection = Domain.GetDomain(DomainCon).DomainControllers

Return DCs.Item(0).Name

'For Each DC As DirectoryServices.ActiveDirectory.DomainController In DCs

' Return DC.Name

'Next

From \<https://www.oneidentity.com/community/identity-manager/f/forum/31749/failover-mechanism-for-active-directory-connector>

-----

Работает указание серверов, через запятую!

Enter the database connection data. Misc database port server Named ConnectionString Security Driver mdw.open.ru,smdw.open.ru {PostgreSQL ANSI)

----

Для процессов AdHoc, чтобы узнать, что находится в data

В PreScript

data = DPR_GetAdHocData(\$FK(UID_UNSGroupB).FK(UID_UNSRootB).XObjectKey\$,"DB","",evt)

Итого параметры подключения определяются на основании вот такого запроса

select * from DPRRootObjConnectionInfo where (ObjectKeyRoot = '\<Key>\<T>UNSRootB\</T>\<P>82b349c1-8d67-4b65-b26a-bdc9d15233bc\</P>\</Key>') and (UID_DPRSystemConnection IN ( Select UID_DPRSystemConnection FROM DPRSystemConnection WHERE UID_DPRSchema IN ( Select UID_DPRSchema FROM DPRSchema WHERE SystemType = N'Posh') And isnull(Name, N'') \<> N'MainConnection'))


Для процессов AdHoc вывести данные data в лог

VID_Write2Log("C:\..",xObjectKey)

VID_Write2Log("C:\..",ex.ErrorString) (в Catch)

--

for each item as KeyValuePair(of String, String) in data

VID_Write2Log("C:\..",item.key & " -> " & item.Value)

Next

--

VID_Write2Log("C:\..",dbDataFound.tostring())


Не отрабатывает процесс на удаление членства пользователя в группе по событию Remove таблицы UNSAccountBInUNSGroupB

Странная ситуация - если ловить только REMOVE - то PreScript отрабатывает на машине, на которой произошло непосредственно событие (На машине, где установлен Manager.) и в целевой системе изменение членства не отражается.

Если ловить Delete - то отрабатывает нормально все.

Как вариант, можно на REMOVE не вызывать ADHoc проекта синхронизации, а, например, через скрипт делать изменения в БД.

Похожая трабла

https://www.oneidentity.com/community/identity-manager/f/forum/29657/adhocprojection-works-for-insert-but-not-for-delete


В Object Browser при обращении к view членства (группа - пользователь) выходит ошибка "1 object(s) should be reloaded but … "

Для view, которые должны однозначно определяться по нескольким колонкам надо создавать Column group - это и будет уникальным ключем!

Create system connection... Extend key information Define a unique key. Some tables in the schema haue no key or an unsuitable unique key. These tables cannot be defined. You haue the option to define new keys here. It is important that all tables haue well defined unique keys otherwise a serious error may occl Hide unconfigured tables Edit column group... Enter a unique name for the column group and select at least ovo columns. Schema 60]pg au members pg_auth members admin_option member uttPrimaryKey Column is key _grou users Column group Add... Add... Add... Add... Key name admin_option member vrtPrimayKey utLlserCoIumnGroupr... pg_group pg_user roleid member Cancel Cancel

Identity Manager 8.0.1 - Native Database Connector User Guide for Connecting Oracle Databases (oneidentity.com)


Postgres/Greenplum скрипт коннектора

Dim succProcessed As IList(Of CommitRecord) = New List(Of CommitRecord)()

Dim sql As New StringBuilder()

Dim strGroupName As String

Dim strMemberName As String

Dim strUseNameOld As String

Dim strGroNameOld As String

Dim strUseName As String

Dim transaction As IDbTransaction = Nothing

Try

' Create transaction

transaction = connection.BeginTransaction()

' Create database command

Using cmd As IDbCommand = connection.CreateCommand()

' Assign transaction to SQL command

cmd.Transaction = transaction

' Loop through list of changed records

For Each record As CommitRecord In records

' Switch by operation type (INSERT, UPDATE or DELETE)

Select Case operation

Case MultiPassCommitStrategyOperation.ProcessInserts

Select Case tableName.ToLowerInvariant()

Case "pg_user"

' Prepare SQL Statement

' TODO format the value

sql.AppendFormat("CREATE USER {0};", record.GetValue("usename", ""))

' TODO format the value

sql.AppendLine()

Exit Select

Case "pg_group"

sql.AppendFormat("CREATE ROLE {0};", record.GetValue("groname", ""))

' TODO format the value

sql.AppendLine()

Exit Select

Case "pg_auth_members_users"

'Log.Debug([String].Format("Select from pg_group"))

sql.AppendFormat("SELECT groname FROM pg_group WHERE grosysid = {0};", record.GetValue(Of Int64)("roleid"))

' Execute SQL Command

cmd.CommandText = sql.ToString()

Using dbReader = cmd.ExecuteReader()

While dbReader.Read()

' Get string value of first result column

strGroupName = If(Not dbReader.IsDBNull(0), dbReader.GetString(0), String.Empty)

End While

End Using

sql.Clear()

sql.AppendFormat("SELECT usename FROM pg_user WHERE usesysid = {0};", record.GetValue(Of Int64)("member"))

' Execute SQL Command

cmd.CommandText = sql.ToString()

Using dbReader = cmd.ExecuteReader()

While dbReader.Read()

' Get string value of first result column

strMemberName = If(Not dbReader.IsDBNull(0), dbReader.GetString(0), String.Empty)

End While

End Using

sql.Clear()

sql.AppendFormat("GRANT {0} TO {1};", strGroupName, strMemberName)

' TODO format the value

sql.AppendLine()

Exit Select        

Case "pg_auth_members_groups"

Log.Debug([String].Format("Select from pg_group"))

sql.AppendFormat("SELECT groname FROM pg_group WHERE grosysid = {0};", record.GetValue(Of Int64)("roleid"))

' Execute SQL Command

cmd.CommandText = sql.ToString()

Using dbReader = cmd.ExecuteReader()

While dbReader.Read()

' Get string value of first result column

strGroupName = If(Not dbReader.IsDBNull(0), dbReader.GetString(0), String.Empty)

End While

End Using

sql.Clear()

sql.AppendFormat("SELECT groname FROM pg_group WHERE grosysid = {0};", record.GetValue(Of Int64)("member"))

' Execute SQL Command

cmd.CommandText = sql.ToString()

Using dbReader = cmd.ExecuteReader()

While dbReader.Read()

' Get string value of first result column

strMemberName = If(Not dbReader.IsDBNull(0), dbReader.GetString(0), String.Empty)

End While

End Using

sql.Clear()

sql.AppendFormat("GRANT {0} TO {1};", strGroupName, strMemberName)

' TODO format the value

sql.AppendLine()

Exit Select        

End Select

Exit Select

Case MultiPassCommitStrategyOperation.ProcessUpdates

Select Case tableName.ToLowerInvariant()        

Case "pg_user"

For Each column As String In record.TouchedColumns

If column = "usename" Then

sql.AppendFormat("SELECT usename FROM pg_user WHERE usesysid = {0};", record.GetValue(Of Int64)("usesysid"))

' Execute SQL Command

cmd.CommandText = sql.ToString()

Using dbReader = cmd.ExecuteReader()

While dbReader.Read()

' Get string value of first result column

strUseNameOld = If(Not dbReader.IsDBNull(0), dbReader.GetString(0), String.Empty)

End While

End Using

sql.Clear()

sql.AppendFormat("ALTER ROLE {0} RENAME TO {1};", strUseNameOld, record.GetValue("usename", ""))

' TODO format the value

sql.AppendLine()

End If

Next

Exit Select

Case "pg_group"

For Each column As String In record.TouchedColumns

If column = "groname" Then

sql.AppendFormat("SELECT groname FROM pg_group WHERE grosysid = {0};", record.GetValue(Of Int64)("grosysid"))

'Execute SQL Command

cmd.CommandText = sql.ToString()

Using dbReader = cmd.ExecuteReader()

While dbReader.Read()

' Get string value of first result column

strGroNameOld = If(Not dbReader.IsDBNull(0), dbReader.GetString(0), String.Empty)

End While

End Using

sql.Clear()

sql.AppendFormat("ALTER ROLE {0} RENAME TO {1};", strGroNameOld, record.GetValue("groname", ""))

' TODO format the value

sql.AppendLine()

End If

Next

Exit Select

End Select

Exit Select

Case MultiPassCommitStrategyOperation.ProcessDeletes

Select Case tableName.ToLowerInvariant()

Case "pg_user"

'sql.AppendFormat("delete pg_user where PKColumn = {0}", record.GetValue(Of [String])("PKColumn"))

sql.AppendFormat("DROP ROLE {0};", record.GetValue(Of [String])("usename"))

'TODO: Use correct datatype for your primary key column

Exit Select

Case "pg_group"

sql.AppendFormat("DROP ROLE {0};", record.GetValue(Of [String])("groname"))

Exit Select

Case "pg_auth_members_users"

sql.AppendFormat("SELECT groname FROM pg_group WHERE grosysid = {0};", record.GetValue(Of Int64)("roleid"))

' Execute SQL Command

cmd.CommandText = sql.ToString()

Using dbReader = cmd.ExecuteReader()

While dbReader.Read()

' Get string value of first result column

strGroupName = If(Not dbReader.IsDBNull(0), dbReader.GetString(0), String.Empty)

End While

End Using

sql.Clear()

sql.AppendFormat("SELECT usename FROM pg_user WHERE usesysid = {0};", record.GetValue(Of Int64)("member"))

' Execute SQL Command

cmd.CommandText = sql.ToString()

Using dbReader = cmd.ExecuteReader()

While dbReader.Read()

' Get string value of first result column

strMemberName = If(Not dbReader.IsDBNull(0), dbReader.GetString(0), String.Empty)

End While

End Using

sql.Clear()

sql.AppendFormat("REVOKE {0} FROM {1};", strGroupName, strMemberName)

' TODO format the value

sql.AppendLine()

Exit Select

Case "pg_auth_members_groups"

sql.AppendFormat("SELECT groname FROM pg_group WHERE grosysid = {0};", record.GetValue(Of Int64)("roleid"))

' Execute SQL Command

cmd.CommandText = sql.ToString()

Using dbReader = cmd.ExecuteReader()

While dbReader.Read()

' Get string value of first result column

strGroupName = If(Not dbReader.IsDBNull(0), dbReader.GetString(0), String.Empty)

End While

End Using

sql.Clear()

sql.AppendFormat("SELECT groname FROM pg_group WHERE grosysid = {0};", record.GetValue(Of Int64)("member"))

' Execute SQL Command

cmd.CommandText = sql.ToString()

Using dbReader = cmd.ExecuteReader()

While dbReader.Read()

' Get string value of first result column

strMemberName = If(Not dbReader.IsDBNull(0), dbReader.GetString(0), String.Empty)

End While

End Using

sql.Clear()

sql.AppendFormat("REVOKE {0} FROM {1};", strGroupName, strMemberName)

' TODO format the value

sql.AppendLine()

Exit Select

End Select

Exit Select

End Select

' Execute SQL command if something is to do

If Not String.IsNullOrEmpty(sql.ToString()) Then

' Execute SQL Command

cmd.CommandText = sql.ToString()

cmd.ExecuteNonQuery()

' Add record to list of succesfull provisioned objects

succProcessed.Add(record)

End If

Next

' Commit transaction

transaction.Commit()

End Using

Catch

If transaction IsNot Nothing Then

transaction.Rollback()

End If

Throw

End Try

Return succProcessed