def create_gdb_featureclass(gdb, name): fc = arcpy.CreateFeatureclass_management(gdb, name, geometry_type="POINT") arcpy.EnableAttachments_management(fc) arcpy.AddGlobalIDs_management(fc) arcpy.EnableEditorTracking_management( fc, creator_field="created_user", creation_date_field="created_date", last_editor_field="last_edit_user", last_edit_date_field="last_edit_date", add_fields=True, record_dates_in="UTC") print("Feature Class {} created".format(name)) #Add comments table fc_comments_name = "{}_Comments".format(name) fc_comments = create_gdb_table(gdb, fc_comments_name) arcpy.EnableAttachments_management(fc_comments) arcpy.AddGlobalIDs_management(fc_comments) arcpy.EnableEditorTracking_management( fc_comments, creator_field="created_user", creation_date_field="created_date", last_editor_field="last_edit_user", last_edit_date_field="last_edit_date", add_fields=True, record_dates_in="UTC") return fc, fc_comments, fc_comments_name
def AddGlobalID(Dataset): ''' Creates and populates a GlobalID Column in the output feature class that was created in the ExportView function. This function requires the location of the feature class to run correctly. ''' arcpy.AddGlobalIDs_management(Dataset)
def create_gdb_featureclass(gdb, name): fc = arcpy.CreateFeatureclass_management(gdb, name, geometry_type="POINT") arcpy.AddGlobalIDs_management(fc) arcpy.EnableAttachments_management(fc) arcpy.EnableEditorTracking_management(fc, "created_user", "created_date", "last_edit_user", "last_edit_date", "ADD_FIELDS", "UTC") print("Feature Class {} created".format(name)) #Add comments table fc_comments_name = "{}_Comments".format(name) fc_comments = create_gdb_table(gdb, fc_comments_name) arcpy.AddGlobalIDs_management(fc_comments) arcpy.EnableAttachments_management(fc_comments) arcpy.EnableEditorTracking_management(fc_comments, "created_user", "created_date", "last_edit_user", "last_edit_date", "ADD_FIELDS", "UTC") return fc_comments_name
def AddGlobalID(Dataset): ''' Creates and populates a GlobalID Column in the output feature class that was created in the ExportView function. ''' arcpy.AddGlobalIDs_management(Dataset)
msgs = arcpy.GetMessages(2) arcpy.AddError(msgs) except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n" arcpy.AddError(pymsg) arcpy.AddError(msgs) #Create the required GlobalID Field try: if len(arcpy.ListFields(fc_name,"GlobalID"))>0: arcpy.AddWarning ("GlobalID exits already") else: arcpy.AddGlobalIDs_management(fc_name) arcpy.AddMessage ("Sasquatch created the GlobalID field") except arcpy.ExecuteError: msgs = arcpy.GetMessages(2) arcpy.AddError(msgs) except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n" arcpy.AddError(pymsg) arcpy.AddError(msgs) #Enable editor tracking try: arcpy.EnableEditorTracking_management(fc_name, "CREATEUSER","CREATEDATE", "EDITUSER", "EDITDATE", "NO_ADD_FIELDS", time_format) arcpy.AddMessage ("Sasquatch enabled editor tracking on "+fc_name)
def _add_global_id(out_gdb, x): for f in x['fields']: type = _json_type_to_gdb_type(f['type']) if type == 'GLOBALID': arcpy.AddGlobalIDs_management( in_datasets=[out_gdb + '/' + x['name']])
def mainFunction( configFile ): # Get parameters from ArcGIS Desktop tool by seperating by comma e.g. (var1 is 1st parameter,var2 is 2nd parameter,var3 is 3rd parameter) try: # Logging if (enableLogging == "true"): # Setup logging logger, logMessage = setLogging(logFile) # Log start of process logger.info("Process started.") # --------------------------------------- Start of code --------------------------------------- # # If configuration provided if (configFile): # Set CSV delimiter csvDelimiter = "," # Open the CSV file with open(configFile, 'rb') as csvFile: # Read the CSV file rows = csv.reader(csvFile, delimiter=csvDelimiter) # For each row in the CSV count = 0 for row in rows: # Ignore the first line containing headers if (count > 0): # Get the full dataset name dataset = row[0] # Get the database connection string from the input splitDataset = dataset.split('.sde') database = splitDataset[0] + ".sde" # Disconnect users from the database arcpy.DisconnectUser(database, "ALL") # Get dataset properties datasetDesc = arcpy.Describe(dataset) # Add Global IDs # Logging if (enableLogging == "true"): logger.info("Adding Global IDs for " + dataset + "...") arcpy.AddMessage("Adding Global IDs for " + dataset + "...") arcpy.AddGlobalIDs_management(dataset) # If dataset isn't versioned if (datasetDesc.isVersioned == 0): # Register As Versioned # Logging if (enableLogging == "true"): logger.info( "Registering dataset as versioned - " + dataset + "...") arcpy.AddMessage( "Registering dataset as versioned - " + dataset + "...") arcpy.RegisterAsVersioned_management( dataset, "NO_EDITS_TO_BASE") else: # Logging if (enableLogging == "true"): logger.info("Dataset already versioned - " + dataset + "...") arcpy.AddMessage("Dataset already versioned - " + dataset + "...") count = count + 1 # No configuration provided else: arcpy.AddError("No configuration file provided...") # Logging if (enableLogging == "true"): # Log error logger.error("No configuration file provided...") # Remove file handler and close log file logging.FileHandler.close(logMessage) logger.removeHandler(logMessage) if (sendErrorEmail == "true"): # Send email sendEmail("No configuration file provided...") # --------------------------------------- End of code --------------------------------------- # # If called from gp tool return the arcpy parameter if __name__ == '__main__': # Return the output if there is any if output: arcpy.SetParameterAsText(1, output) # Otherwise return the result else: # Return the output if there is any if output: return output # Logging if (enableLogging == "true"): # Log end of process logger.info("Process ended.") # Remove file handler and close log file logging.FileHandler.close(logMessage) logger.removeHandler(logMessage) pass # If arcpy error except arcpy.ExecuteError: # Build and show the error message errorMessage = arcpy.GetMessages(2) arcpy.AddError(errorMessage) # Logging if (enableLogging == "true"): # Log error logger.error(errorMessage) # Remove file handler and close log file logging.FileHandler.close(logMessage) logger.removeHandler(logMessage) if (sendErrorEmail == "true"): # Send email sendEmail(errorMessage) # If python error except Exception as e: errorMessage = "" # Build and show the error message for i in range(len(e.args)): if (i == 0): errorMessage = str(e.args[i]) else: errorMessage = errorMessage + " " + str(e.args[i]) arcpy.AddError(errorMessage) # Logging if (enableLogging == "true"): # Log error logger.error(errorMessage) # Remove file handler and close log file logging.FileHandler.close(logMessage) logger.removeHandler(logMessage) if (sendErrorEmail == "true"): # Send email sendEmail(errorMessage)
Connection = "X:/TPFM_RDSC/FicherosConexionGDB/[email protected]/" VerDatasets = ["Anidamientos", "Arboles", "Areas_caninas", "Bancos_Vondelpark", "Canchas_deportivas", "Fallopia_japonica", "Panales_polinizadoras", "Parques_deportivos", "Procesionaria", "Residuos_urbanos"] # Execute RegisterAsVersioned for dataset in VerDatasets: dataset_name = Connection + "amsterdammilieudienstgdb.supervisor_0." + dataset arcpy.AddGlobalIDs_management(dataset_name) # Required for breanched datasets arcpy.RegisterAsVersioned_management(dataset_name, "NO_EDITS_TO_BASE") """ Snippet para la introducción de valores aleatorios del campo 'Tratamientos' en la capa Arboles En el campo Expression de la herramienta CalculateField se introduce la llamada a la función. El siguiente código se introduce en el Code Block """ from random import betavariate def PopulateTratamientos(): alfa = .25 beta = 1
def create_rel_classes(): print("Relationship classes") for _rel in relClassDict: _out_relationship_class = os.path.join(get_workspace(), featuredataset, _rel) # _out_relationship_class = os.path.join(GetWorkspace(), _rel) if arcpy.Exists(_out_relationship_class) is False: _origin_table = os.path.join( get_workspace(), featuredataset, relClassDict[_rel][1] ) if relClassDict[_rel][2] == "FIDA_LFP": _relationship_type = "SIMPLE" elif relClassDict[_rel][2] == "FIDA_HFP": _relationship_type = "SIMPLE" elif relClassDict[_rel][2] == "FIDA_LSN": _relationship_type = "SIMPLE" elif relClassDict[_rel][2] == "FIDA_KONTAKT": _relationship_type = "SIMPLE" else: _relationship_type = "COMPOSITE" _destination_table = os.path.join(get_workspace(), relClassDict[_rel][2]) _forward_label = relClassDict[_rel][3] _backward_label = relClassDict[_rel][4] _cardinality = relClassDict[_rel][0] # _origin_primary_key = "PK" geändert damit Checkout möglich wird _origin_primary_key = "GlobalID" if _cardinality == "MANY_TO_MANY": _origin_foreign_key = "ORIGNIVLINIEN_HFP" _destination_primary_key = "GlobalID" _destination_foreign_key = "DESTHFP_NIVLINIEN" else: _origin_foreign_key = "FK_" + relClassDict[_rel][1] _destination_primary_key = "" _destination_foreign_key = "" arcpy.CreateRelationshipClass_management( origin_table=_origin_table, destination_table=_destination_table, out_relationship_class=_out_relationship_class, relationship_type=_relationship_type, forward_label=_forward_label, backward_label=_backward_label, cardinality=_cardinality, origin_primary_key=_origin_primary_key, origin_foreign_key=_origin_foreign_key, destination_primary_key=_destination_primary_key, destination_foreign_key=_destination_foreign_key, ) print( "Relationship class between origin_table: {} and destination_table: {}".format( _origin_table, _destination_table ) ) print("Create Relationship class: " + _rel) if _rel == "FIDA_NIVLINIEN_HFP": arcpy.AddGlobalIDs_management(_out_relationship_class) if sde_fida is True: arcpy.EnableEditorTracking_management( in_dataset=_out_relationship_class, creator_field="CREATOR_FIELD", creation_date_field="CREATOR_DATE_FIELD", last_editor_field="LAST_EDITOR_FIELD", last_edit_date_field="LAST_EDITOR_DATE_FIELD", add_fields="ADD_FIELDS", record_dates_in="UTC", ) print("add GlobalID and EditorTracking to FIDA_NIVLINIEN_HFP") else: print("Relationship class already created: " + _rel)
def create_fcs(): for _fc in fcDict: if fcDict[_fc] == "TABLE": _dataset = os.path.join(get_workspace(), _fc) if arcpy.Exists(_dataset) is True: arcpy.Delete_management(_dataset) print("Table: " + _fc + " deleted") arcpy.CreateTable_management(get_workspace(), _fc) arcpy.AddGlobalIDs_management(_dataset) if _fc == "FIDA_ANHANGLFP" or _fc == "FIDA_ANHANGHFP": arcpy.EnableAttachments_management(_dataset) if sde_fida is True: arcpy.ChangePrivileges_management( _dataset, "ARCSDE_EDITOR", "GRANT", "GRANT" ) arcpy.ChangePrivileges_management(_dataset, "ARCSDE_READER", "GRANT") # if sde_fida is True: arcpy.EnableEditorTracking_management( in_dataset=_dataset, creator_field="CREATOR_FIELD", creation_date_field="CREATOR_DATE_FIELD", last_editor_field="LAST_EDITOR_FIELD", last_edit_date_field="LAST_EDITOR_DATE_FIELD", add_fields="ADD_FIELDS", record_dates_in="UTC", ) print("Tracking enabled") # Anhang: EnableEditorTracking (wichtig für BranchVersioning) if _fc == "FIDA_ANHANGLFP" or _fc == "FIDA_ANHANGHFP": _datasetattach = os.path.join(get_workspace(), _fc + "__ATTACH") if sde_fida is True: arcpy.ChangePrivileges_management( _datasetattach, "ARCSDE_EDITOR", "GRANT", "GRANT" ) arcpy.ChangePrivileges_management( _datasetattach, "ARCSDE_READER", "GRANT" ) arcpy.EnableEditorTracking_management( in_dataset=_datasetattach, creator_field="CREATOR_FIELD", creation_date_field="CREATOR_DATE_FIELD", last_editor_field="LAST_EDITOR_FIELD", last_edit_date_field="LAST_EDITOR_DATE_FIELD", add_fields="ADD_FIELDS", record_dates_in="UTC", ) print("Tracking enabled __ATTACH") print("Table: " + _fc + " created") else: _dataset = os.path.join(get_workspace(), featuredataset, _fc) _out_path = os.path.join(get_workspace(), featuredataset) _has_z = "ENABLED" arcpy.CreateFeatureclass_management( out_path=_out_path, out_name=_fc, geometry_type=fcDict[_fc], has_z=_has_z, out_alias=_fc, ) arcpy.AddGlobalIDs_management(_dataset) # if sde_fida is True: arcpy.EnableEditorTracking_management( in_dataset=_dataset, creator_field="CREATOR_FIELD", creation_date_field="CREATOR_DATE_FIELD", last_editor_field="LAST_EDITOR_FIELD", last_edit_date_field="LAST_EDITOR_DATE_FIELD", add_fields="ADD_FIELDS", record_dates_in="UTC", ) print("Tracking enabled") print("Featureclass: " + _fc + " created")
rc_list = [c.name for c in arcpy.Describe(workspace).children if c.datatype == "RelationshipClass" and c.name not in passTable] # Build a list of relationship classes which have an OBJECTID based origin class key rc_migrate = [] for rc in rc_list: rc_path = workspace + "\\" + rc rc_desc = arcpy.Describe(rc_path) print rc_desc.name for item in rc_desc.OriginClassKeys: if "OBJECTID" in item: rc_migrate.append(rc_path) # Check that the origin feature classes have Global Ids rc_final = [] for rel in rc_migrate: originfc = workspace + "\\" + arcpy.Describe(rel).originClassNames[0] if arcpy.ListFields(originfc,"","GlobalID"): rc_final.append(rel) print("Adding {0} to the migrate list.\n".format(rel.rsplit("\\",1)[1])) else: print("{0} must have Global Ids to migrate relationship class.\n".format(originfc.rsplit("\\",1)[1])) arcpy.AddGlobalIDs_management(originfc) rc_final.append(rel) # Pass the list of valid relationship classes into the Migrate Relationship tool print("Passing valid relationship classes into the Migrate Relationship Class tool.\n") for rel_class in rc_final: print("Migrating {0}... \n".format(rel_class.rsplit("\\",1)[1])) arcpy.MigrateRelationshipClass_management(rel_class) print(arcpy.GetMessages() + "\n")
def create_structures_fc(gdb): """ Create Historic Structures feature class """ arcpy.env.workspace = gdb fc = "HistoricStructures" spatref = arcpy.SpatialReference( "WGS 1984 Web Mercator (auxiliary sphere)") if arcpy.Exists(fc): arcpy.Delete_management(os.path.join(gdb, fc)) has_m = "DISABLED" has_z = "DISABLED" # Execute CreateFeatureclass arcpy.CreateFeatureclass_management(gdb, fc, "POINT", "", has_m, has_z, spatref) arcpy.AddField_management(fc, "ResourceID", "LONG", "", "", "", "Resource ID", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "PropName", "TEXT", "", "", 100, "Resource Name", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "StrucType", "LONG", "", "", "", "Structure Type", "NON_NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "BldType", "TEXT", "", "", 3, "Building Type", "NON_NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "StyleType", "TEXT", "", "", 3, "Architectural Style", "NON_NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "Eligibility", "TEXT", "", "", 3, "Eligibility Status", "NON_NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "ConstYr", "LONG", "", "", "", "Construction Year", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "Address", "TEXT", "", "", 200, "Address", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "Notes", "TEXT", "", "", 200, "Notes", "NULLABLE", "NON_REQUIRED", "") arcpy.AddGlobalIDs_management(fc) arcpy.AddField_management(fc, "EPProject", "TEXT", "", "", 20, "EPEI Project ID", "NULLABLE", "NON_REQUIRED", "") arcpy.SetSubtypeField_management(fc, "StrucType") for item in subtypes.items(): arcpy.AddSubtype_management(fc, item[0], item[1]) arcpy.SetDefaultSubtype_management(fc, 5) for item in subtypes.items(): arcpy.AssignDomainToField_management(fc, "BldType", item[1], item[0]) arcpy.AssignDomainToField_management( fc, "StyleType", "Styles", ['0', '1', '2', '3', '4', '5', '6', '7', '8']) arcpy.AssignDomainToField_management( fc, "Eligibility", "Eligibility", ['0', '1', '2', '3', '4', '5', '6', '7', '8']) arcpy.AssignDefaultToField_management( fc, "Eligibility", "U", ['0', '1', '2', '3', '4', '5', '6', '7', '8']) arcpy.AssignDefaultToField_management( fc, "StyleType", "NS", ['0', '1', '2', '3', '4', '5', '6', '7', '8']) arcpy.AssignDefaultToField_management( fc, "BldType", "OT", ['0', '1', '2', '3', '4', '6', '7', '8']) arcpy.AssignDefaultToField_management(fc, "BldType", "NAT", '5') return os.path.join(gdb, fc)
def create_gdb_featureclass(gdb,name): fc = arcpy.CreateFeatureclass_management(gdb,name, geometry_type="POINT") arcpy.AddGlobalIDs_management(fc) arcpy.EnableAttachments_management(fc) arcpy.EnableEditorTracking_management(fc, "created_user","created_date","last_edit_user","last_edit_date","ADD_FIELDS","UTC")
special_point_fc = datasets['special_point_fc'] special_line_fc = datasets['special_line_fc'] special_poly_fc = datasets['special_poly_fc'] chem_app_table = datasets['chem_app_table'] hv_optprod_table = datasets['hv_optprod_table'] activity_mobile = datasets['activity_mobile'] chem_app_mobile = datasets['chem_app_mobile'] # Add GlobalIDs to all datasets try: for ds in datasets: desc = arcpy.Describe(datasets[ds]) if desc.hasGlobalID: pass else: arcpy.AddGlobalIDs_management(datasets[ds]) print('...GlobalIDs added to all datasets') GWRutils.logMessage(log, '...GlobalIDs added to all datasets') except Exception as e: print('Failed to add GlobalIDs to all datasets! Exiting...') print(e) GWRutils.logMessage( log, 'Failed to add GlobalIDs to all datasets! ' + 'Exiting...') GWRutils.logMessage(log, str(e)) sys.exit() # Copy mobile datasets to SDE try: arcpy.FeatureClassToFeatureClass_conversion(activity_mobile, sde_connection,
#make query table qrytable = arcpy.MakeFeatureLayer_management(infc, viewtable, where_clause=clause) outFC = prjcode + "_AlterationConsensus" #copy features tool arcpy.CopyFeatures_management(qrytable, outloc + "\\" + outFC) #add global ids fc = outloc + "\\" + outFC fields = arcpy.ListFields(fc, "", "GlobalID") if "GlobalID" in fields: pass else: arcpy.AddGlobalIDs_management(outloc + "\\" + outFC) fields = [ "Fresh_Final_Score", "Potassic_Final_Score", "Chloritic_Final_Score", "Chl-Ep_Final_Score", "Qz-Ser_Final_Score", "Argillic_Final_Score", "AAA_Alu_Final_Score", "AAA_Dick_Final_Score", "AAA_Pyr_Final_Score", "Phyllic_Final_Score", "Propylitic_Final_Score", "Final_Alteration", "Completeness", "Coherence_Fresh", "Coherence_Potassic", "Coherence_Chloritic", "Coherence_Qt-Ser", "Coherence_Chl-Ep", "Coherence_Argillic", "Coherence_AAA_Alu", "Coherence_AAA_Dick", "Coherence_AAA_Pyr", "Coherence_Phyllic", "Coherence_Propylitic", "Final Flag Status" ] for field in fields: if field not in arcpy.ListFields(fc):
for ds in datasets: for fc in arcpy.ListFeatureClasses(feature_dataset=ds): #print(f'found {fc}') if fc in fcDelete: print(f'Deleting {fc}') arcpy.Delete_management(fc) #%% #check for GlobalID before migrating relationship classes for custAcctSource in custAcctSourceList: fldList = [fld.name.upper() for fld in arcpy.Describe(custAcctSource).fields] #print(fldList) if "GLOBALID" not in fldList: print(f'Adding GlobalID to {custAcctSource}') arcpy.AddGlobalIDs_management(custAcctSource) #%% # convert ObjectID relationship to GlobalID relationship in root sourceGDBList # exclude from list exclude = ['CircuitBreaker_CircuitSource','eConduitBank_eConduitBankConfigDef','eSurfaceStructure__ATTACHREL_1', 'eSupportStructure__ATTACHREL_1','SuppStructure_ForeignAttach','gCustomeraccount_SAPInstallation', 'gGasValve_gValveInspection','gGasValve_gValveMaintenance','gEmergencyShutoff_gEMSValves', 'gAbandonedValve_gValveInspection','eCUSTOMERACCOUNT__ATTACHREL' ] include = ['gMeterSet_gCustomerAccount','RSERVICEPOINT_CUSTACCT','WSERVICEPOINT_CUSTACCT'] for source_gdb in sourceGDBList: arcpy.env.workspace = source_gdb rcList = [c.name for c in arcpy.Describe(source_gdb).children if c.datatype == "RelationshipClass"] for rc in rcList:
msgs = arcpy.GetMessages(2) arcpy.AddError(msgs) except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n" arcpy.AddError(pymsg) arcpy.AddError(msgs) #Create the required GlobalID Field try: if len(arcpy.ListFields(in_Table,"GlobalID"))>0: arcpy.AddWarning ("GlobalID exits already") else: arcpy.AddGlobalIDs_management(in_Table) arcpy.AddMessage ("Sasquatch created the GlobalID field") except arcpy.ExecuteError: msgs = arcpy.GetMessages(2) arcpy.AddError(msgs) except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n" arcpy.AddError(pymsg) arcpy.AddError(msgs) #Enable editor tracking try: arcpy.EnableEditorTracking_management(gdb_location+"\\"+gdb_name+".gdb\\"+fc_name, "CREATEUSER","CREATEDATE", "EDITUSER", "EDITDATE", "NO_ADD_FIELDS", time_format) arcpy.AddMessage ("Sasquatch enabled editor tracking on "+fc_name)
def AddGlobalIDField(dataset): try: arcpy.AddGlobalIDs_management(arcpy.env.workspace + "\\" + dataset) print u"Campo GlobalID adicionado em {} com sucesso".format(dataset) except Exception as ex: print u"ERRO:", dataset, ex.message