Select to view content in your preferred language

import association through the service

453
9
Jump to solution
04-03-2025 02:12 AM
gpgisandsky
Regular Contributor

Hi,

I have AGS11.3 + UN v7 on Oracle DB. I need import un association. I have csv/excel based required by tool Import Association. Import Association work fine on file geodatabase un.

CSV example:

ASSOCIATIONTYPE,FROMFEATURECLASS,FROMASSETGROUP,FROMASSETTYPE,FROMGLOBALID,FROMTERMINAL,TOFEATURECLASS,TOASSETGROUP,TOASSETTYPE,TOGLOBALID,TOTERMINAL,ISCONTENTVISIBLE,PERCENTALONG
Containment,StructureJunction,Pozzetti,Cameretta di ispezione,{450CCDC5-24AA-4018-9001-793E856513CB},,AqDevice,Valvole,Valvola di rete,{5679CD23-D8EC-44DA-95C5-87632E35D40E} ,,False,

 

Now, I need import association directly on  un feature service. is there a py script/tool that I can use?

It's possible (https://developers.arcgis.com/rest/services-reference/enterprise/appendix-working-with-the-feature-s...) and I would like use a *.py script within pro to do this operation.

Thank you

 

 

 

 

0 Kudos
1 Solution

Accepted Solutions
gis_KIWI4
Frequent Contributor

In the payload you pasted in questions there seems to be an additional space.
'TOGLOBALID': '{5679CD23-D8EC-44DA-95C5-87632E35D40E} '
There is a space at the end of the TOGLOBALID.

It may be worth checking if the csv has a rogue space at the end of the TOGLOBALID that the code might be ingesting. 

PS - The format of the globalIDs is correct. 

View solution in original post

0 Kudos
9 Replies
MikeMillerGIS
Esri Frequent Contributor

The association table supports ApplyEdits, so you just need to craft the apply edits payload just like editing any other feature service/table.  

The association table is always layer id 500001

0 Kudos
gpgisandsky
Regular Contributor

hi @MikeMillerGIS ,

i tried this:

import arcpy
import csv
import json
import requests


#Acqua Device (ID: 1)    "sourceId": 9,
#Acqua Junction (ID: 2)    "sourceId": 12,
#Structure Junction (ID: 3)    "sourceId": 4,





# Configurazione
portalUrl = "https://xyz/portal"
username = 'xyz'
password = "xyz"
csv_path = r"C:\ArcGIS\26_xxx_UN\Creazione_UtilityNetwork\PRO prj\File_GDB\Association_xxx_2025_04_01_ore1811_DEVICE.csv"

# Funzione per ottenere il token se necessario
def get_token():
    token = generateToken(username, password, portalUrl)
    return token

def generateToken(username, password, portalUrl😞
    # Retrieves a token to be used with API requests.
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    parameters = {'username': username,
                  'password': password,
                  'client': 'referer',
                  'referer': portalUrl,
                  'expiration': 60,
                  'f': 'json'}
    url = portalUrl + '/sharing/rest/generateToken?'
    response = requests.post(url, data=parameters, headers=headers)

    try:
        jsonResponse = response.json()
       
        if 'token' in jsonResponse:
            return jsonResponse['token']
        elif 'error' in jsonResponse:
            print(jsonResponse['error']['message'])
            for detail in jsonResponse['error']['details']:
                print(detail)
    except ValueError:
        print('An unspecified error occurred.')
        print(ValueError)

# Leggere il CSV e creare le associazioni
associations = []
with open(csv_path, 'r', encoding='utf-8') as file:
    reader = csv.reader(file)
    header = next(reader)  # Legge l'intestazione
   
    for row in reader:
        if len(row) != 13:
            print(f"Errore: Riga non conforme -> {row}")
            continue
       

        association = {
            "attributes": {
            "ASSOCIATIONTYPE" : 2,
            #"ISCONTENTVISIBLE" : <0|1>,  // optional: false, true
            "FROMNETWORKSOURCEID" : 4,
            "FROMGLOBALID" : row[4],
            #"FROMTERMINALID" : <long>,   // optional
            "TONETWORKSOURCEID" : 9,
            "TOGLOBALID" : row[9],
            #"TOTERMINALID" : <long>,      // optional
            #"PERCENTALONG" : <float>       // optional
            "ISCONTENTVISIBLE" : 0

           
            }

        }
        associations.append(association)

# Invia le associazioni al Feature Service
payload = [
    {
        "id": 500001,  # Modifica con l'ID corretto del layer delle associazioni
        "adds": associations
    }
]

# Funzione per inviare modifiche al Feature Service
def apply_edits(payload😞
    url = f"{feature_service_url}/applyEdits"
    data = {"geodatabaseVersionName" : "sde.DEFAULT", "useGlobalIds" : "true", "f": "json",   "token": get_token(), "edits": json.dumps(payload)}
    response = requests.post(url, data=data)
    return response.json()

# Esegui l'importazione
result = apply_edits(payload)
print("Risultato dell'importazione:", result)

# Miglioramento: Gestione degli errori per il risultato
if 'error' in result:
    print("association:",association)
    print("Errore durante l'importazione:", result['error'])
else:
    print("Importazione completata con successo.")
 
but I had the following error:
 

Errore durante l'importazione: {'code': 400, 'extendedCode': -2147219118, 'message': 'Unable to complete operation.', 'details': ['Internal error while adding containment association. A requested row object could not be located.']}
 
association content is:
 
association: {'attributes': {'ASSOCIATIONTYPE': 2, 'FROMNETWORKSOURCEID': 4, 'FROMGLOBALID': '{450CCDC5-24AA-4018-9001-793E856513CB}', 'TONETWORKSOURCEID': 9, 'TOGLOBALID': '{5679CD23-D8EC-44DA-95C5-87632E35D40E} ', 'ISCONTENTVISIBLE': 0}}
 
what could be wrong?
0 Kudos
MikeMillerGIS
Esri Frequent Contributor

Could be the format of the globalids.  Do they have {}? Can you use fiddler or something and share what the payload looks like?  Compare that to the payload when you make association in Pro.

 

The other thought I had, have you tried the append gp tool?  You can make a table view from the url and call change version(gp) on it.  

0 Kudos
gpgisandsky
Regular Contributor

Could be the format of the globalids.  Do they have {}? 

'FROMGLOBALID': '{450CCDC5-24AA-4018-9001-793E856513CB}'

'TOGLOBALID': '{5679CD23-D8EC-44DA-95C5-87632E35D40E} '

 

The other thought I had, have you tried the append gp tool? No, append gp tool works on 

service?

 

0 Kudos
MikeMillerGIS
Esri Frequent Contributor

GP Append does work with services

0 Kudos
gis_KIWI4
Frequent Contributor

In the payload you pasted in questions there seems to be an additional space.
'TOGLOBALID': '{5679CD23-D8EC-44DA-95C5-87632E35D40E} '
There is a space at the end of the TOGLOBALID.

It may be worth checking if the csv has a rogue space at the end of the TOGLOBALID that the code might be ingesting. 

PS - The format of the globalIDs is correct. 

0 Kudos
gp2014
by
Emerging Contributor

hi, there is a additional space. I'll try to send the request without space. thank you

gis_KIWI4
Frequent Contributor

Did removing the space fix it? @gp2014  @gpgisandsky ? 

0 Kudos
gp2014
by
Emerging Contributor

Hi @gis_KIWI4 , Im waiting to restore the db. I'll try next day. thank you

0 Kudos