Esempio n. 1
0
def SetFeatureClassPrivileges(sensitive, sensubgrp, sdeConn, dbName,
                              schemaOwner, featName, grant):
    funcName = 'SetFeatureClassPrivileges'
    userName = []

    if sensitive:
        userName.append('SPREAD')
        if sensubgrp.lower() <> 'none' and sensubgrp <> None:
            if sensubgrp.lower() == 'cultres':
                userName.append('cultres_read')
            if sensubgrp.lower() == 'infotech':
                userName.append('infotech_read')
            if sensubgrp.lower() == 'cultres_natres':
                userName.append('cultres_natres_read')
            if sensubgrp.lower() == 'natres':
                userName.append('natres_read')
            if sensubgrp.lower() == 'wwconres':
                userName.append('wwconres_read')
    else:
        userName.append('GISREAD')
    inFeature = '"' + sdeConn + '\\' + dbName + '.' + schemaOwner + '.' + featName + '"'
    if grant:
        for user in userName:
            arcpy.ChangePrivileges_management(in_dataset=inFeature,
                                              user=user,
                                              View="GRANT",
                                              Edit="AS_IS")
    else:
        for user in userName:
            arcpy.ChangePrivileges_management(in_dataset=inFeature,
                                              user=user,
                                              View="REVOKE",
                                              Edit="REVOKE")
Esempio n. 2
0
def snapshotfunc(source_sde, target_sde):

    # all the deletes here
    prepare_target(target_sde)

    source_fd = os.path.join(source_sde, feature_dataset)

    target_fd = os.path.join(target_sde, feature_dataset)

    print "copying {0} to {1}".format(source_fd, target_fd)

    # all but the data tables are caught in this feature dataset web
    arcpy.Copy_management(source_fd, target_fd)

    for dt in data_tables:

        source_dt = os.path.join(source_sde, dt)

        target_dt = os.path.join(target_sde, dt)

        print "copying {0} to {1}".format(source_dt, target_dt)

        arcpy.Copy_management(source_dt, target_dt)

        # if our pal ESRI renames COUNT to COUNT_
        renamecol(target_dt, 'COUNT_', 'COUNT')

    print "registering as versioned {0}".format(feature_dataset)

    arcpy.RegisterAsVersioned_management(
        os.path.join(target_sde, feature_dataset))

    allgrantableobjects = feature_classes + entwined_tables + data_tables

    for copiedobject in allgrantableobjects:

        print "granting privs on {0}".format(copiedobject)

        arcpy.ChangePrivileges_management(
            os.path.join(target_sde, copiedobject), "DOITT_DTM_VIEWER",
            "GRANT", "")
        arcpy.ChangePrivileges_management(
            os.path.join(target_sde, copiedobject), "TAXMAP_VIEWER", "GRANT",
            "")
        arcpy.ChangePrivileges_management(
            os.path.join(target_sde, copiedobject), "DOF_READONLY", "GRANT",
            "")
        arcpy.ChangePrivileges_management(
            os.path.join(target_sde, copiedobject), "DOF_TAXMAP_EDITOR",
            "GRANT", "GRANT")
        arcpy.ChangePrivileges_management(
            os.path.join(target_sde, copiedobject), "DCP_MAP_EDITOR", "GRANT",
            "GRANT")

    exitcode = qa_target(source_sde, target_sde)

    return exitcode
Esempio n. 3
0
def create_feature_class(src, dst):
    try:
        outLocation = get_path(dst)
        outFCName = clean_name(get_file_name(dst))
        arcpy.FeatureClassToFeatureClass_conversion(src, outLocation, outFCName)
        log('\nCreated feature class ' + dst + '\n')
        # Process: Change Privileges
        arcpy.ChangePrivileges_management(dst, "gis_viewer", "GRANT", "")
        # Process: Change Privileges (2)
        arcpy.ChangePrivileges_management(dst, "gis_editor", "GRANT", "GRANT")

    except Exception, err:
        log('\nError in function create_feature_class!\n' + arcpy.GetMessages(2) + '\n' + str(err) + '\n')
Esempio n. 4
0
def setDataEditors(allDatasets, editorGroup):
    '''
    Function that grants read and write permissions for the provided
    editor group to all of the feature classes and tables within the
    provided database.
    '''
    for dataset in allDatasets:
        arcpy.ChangePrivileges_management(dataset, editorGroup, "GRANT",
                                          "GRANT")
Esempio n. 5
0
def setDataViewers(allDatasets, viewerGroup):
    '''
    Function that grants read and permissions for the provided
    viewer group to all of the feature classes and tables within the
    provided database.
    '''
    for dataset in allDatasets:
        arcpy.ChangePrivileges_management(dataset, viewerGroup, "GRANT",
                                          "AS_IS")
Esempio n. 6
0
def updateRCPrivileges(array):
    for fc in array:
        datasetName = wkspc + "/" + fc
        print datasetName
        try:
            arcpy.ChangePrivileges_management(datasetName, "gisadmin", "GRANT",
                                              "GRANT")
            print arcpy.GetMessages()
        except:
            print "An error occurred setting privileges:"
            print arcpy.GetMessages()
Esempio n. 7
0
    def grantprivileges(self, user, edits='GRANT'):  # or AS_IS

        # https://pro.arcgis.com/en/pro-app/tool-reference/data-management/change-privileges.htm
        # caller should know who editors are we dont concern ourselves here

        # always grant select, edits are GRANT or AS_IS for grant select only
        # The nobs and dials on this tool are confounding

        logging.info('granting privileges on {0} to {1}'.format(
            self.name, user))

        return self.interpret(
            arcpy.ChangePrivileges_management(self.featureclass, user, 'GRANT',
                                              edits))
Esempio n. 8
0
def changePrivileges(dataset, role, view, write):
    try:
        arcpy.ChangePrivileges_management(dataset, role, view, write)
    except:
        for i in range(arcpy.GetMessageCount()):
            message(i, 2)
Esempio n. 9
0
import os

import arcpy

# Set variables
connection_file = raw_input('Enter SDE connection filename: ')
user = raw_input('Enter username or group [SPECTRUM\GIS_Admin]: ') \
       or 'SPECTRUM\GIS_Admin'
view_rights = 'GRANT'
edit_rights = 'GRANT'

# Set workspace
arcpy.env.workspace = "Database Connections/" + connection_file

# Enumerate Database elements
db_items = arcpy.ListDatasets() \
           + arcpy.ListFeatureClasses() \
           + arcpy.ListTables()

arcpy.ChangePrivileges_management(in_dataset=db_items, 
                                  user=user, 
                                  View=view_rights, 
                                  Edit=edit_rights)
Esempio n. 10
0
    # Get a list of feature classes, tables and feature datasets
    # and apply appropriate permissions.
    print(
        "\tBuilding a list of feature classes, tables, and feature datasets in the geodatabase"
    )
    arcpy.env.workspace = ownerConn[
        0]  #note environments do not work with result objects.
    dataList = arcpy.ListTables() + arcpy.ListFeatureClasses(
    ) + arcpy.ListDatasets("", "Feature")

    # Use roles to apply permissions.
    print(
        "\tGranting appropriate privileges to the data for the 'viewers' and 'editors' roles"
    )
    arcpy.ChangePrivileges_management(dataList, 'viewers', 'GRANT')
    arcpy.ChangePrivileges_management(dataList, 'editors', 'GRANT', 'GRANT')

    # Register the data as versioned.
    print("\tRegistering the data as versioned")
    for dataset in dataList:
        arcpy.RegisterAsVersioned_management(dataset)

    # Finally, create a version for each editor.
    print("\tCreating a private version for each user in the editor role")
    for user3 in editors:
        verCreateConn = arcpy.CreateDatabaseConnection_management(
            r'<path_to_save_connection_file>', '<file_name>.sde', platform,
            instance, 'DATABASE_AUTH', user3, '<your_password_choice>',
            'SAVE_USERNAME', database)
        arcpy.CreateVersion_management(verCreateConn, 'sde.Default',
Esempio n. 11
0
def main():
    # uncomment two lines below when debugging in Pycharm
    import pydevd_pycharm
    pydevd_pycharm.settrace('localhost',
                            port=12345,
                            stdoutToServer=True,
                            stderrToServer=True)

    csDict = {}
    try:
        with open('tables/2021-spcs-counties.csv', mode='r') as csFile:
            reader = csv.reader(csFile)
            csDict = {row[1]: (row[2], row[3], row[5]) for row in reader}
    except:
        arcpy.AddError("ERROR: Unable to find Coordinate System CSV, exit")
        sys.exit("ERROR: Unable to find Coordinate System CSV, exit")

    # Parameters
    num_cl_shp = arcpy.GetParameterAsText(
        0)  # Number of CoreLogic shapefiles to be processed
    cl_parcel_shp1 = arcpy.GetParameterAsText(1)  # CoreLogic shapefile 1
    cl_parcel_shp2 = arcpy.GetParameterAsText(2)  # CoreLogic shapefile 2
    cl_parcel_shp3 = arcpy.GetParameterAsText(3)  # CoreLogic shapefile 3
    cl_parcel_shp4 = arcpy.GetParameterAsText(4)  # CoreLogic shapefile 4
    workspace = arcpy.GetParameterAsText(5)  # Workspace
    env.workspace = workspace
    project_fgdb = arcpy.GetParameterAsText(6)  # Project FGDB
    project_Number = arcpy.GetParameterAsText(7)  # Output parcel FC
    firstSaleID = arcpy.GetParameterAsText(8)
    secondSaleID = arcpy.GetParameterAsText(9)
    subjectProperty = arcpy.GetParameterAsText(10)  # Subject property FC
    calculateDistance = arcpy.GetParameterAsText(
        11)  # Method to measure distance
    sale_year_query = arcpy.GetParameterAsText(12)  # Sale Year Query
    impValQuery = arcpy.GetParameterAsText(13) or "1000"
    create_parcel_fc = arcpy.GetParameterAsText(14)
    create_salefc = arcpy.GetParameterAsText(
        15)  # Boolean for creation of sale feature class
    create_comp_insp_pt_fc = arcpy.GetParameterAsText(16)
    naming_convention = arcpy.GetParameterAsText(17)

    countyFIPS = os.path.splitext(
        os.path.basename(cl_parcel_shp1))[0].split('_')[1]
    if not countyFIPS.isdigit():
        arcpy.AddError("ERROR: Unable to parse FIPS from file name, exit")
        sys.exit("ERROR: Unable to parse FIPS from file name, exit")

    location = csDict.get(countyFIPS)[:2]
    if not location:
        arcpy.AddError("ERROR: Unable to identify county from FIPS code, exit")
        sys.exit("ERROR: Unable to identify county from FIPS code, exit")
    countyName, stateAbbrev = location
    countyName = re.sub('[^A-Za-z0-9_\s]+', '', countyName)

    parcel_output_fc = "_".join(
        [project_Number, "parcelcl", countyName,
         stateAbbrev]).replace(' ', '_')
    full_parcel_output_fc = os.path.join(project_fgdb, parcel_output_fc)

    name_components = [
        project_Number, "compsale", countyName, stateAbbrev
    ] if naming_convention == 'County/State' else [project_Number, "compsale"]
    sale_output_fc = "_".join(name_components).replace(' ', '_')
    full_sale_parcel_output_fc = os.path.join(project_fgdb, sale_output_fc)
    update_sale_output_fc_permissions = True

    name_components = [
        project_Number, "comp_insp_pt", countyName, stateAbbrev
    ] if naming_convention == 'County/State' else [
        project_Number, "comp_insp_pt"
    ]
    comp_insp_pt_output_fc = "_".join(name_components).replace(' ', '_')
    full_comp_insp_pt_output_fc = os.path.join(project_fgdb,
                                               comp_insp_pt_output_fc)
    update_comp_insp_pt_fc_permissions = True

    # 1 - Check for existence of temporary feature classes & tables and delete if exist
    arcpy.AddMessage(
        "START (1/21): Check for temporary features and tables and delete")
    delete_temp_files()
    arcpy.AddMessage(
        "COMPLETE (1/21): Check for temporary features and tables and delete")

    # 2 Create Output Feature Classes
    arcpy.AddMessage("START (2/21): Create Output Feature Classes")
    if create_parcel_fc.lower() == "true":
        if arcpy.Exists(full_parcel_output_fc):
            arcpy.AddError(
                "ERROR: Output parcel feature class already exists, exit")
            sys.exit("ERROR: Output parcel feature class already exists, exit")
        arcpy.Copy_management(r"templates\templates.gdb\parcelcl",
                              full_parcel_output_fc)

    if create_salefc.lower() == "true":
        if arcpy.Exists(full_sale_parcel_output_fc):
            arcpy.AddMessage("Compsale output already exists, skipping")
            update_sale_output_fc_permissions = False
        else:
            arcpy.Copy_management(r"templates\templates.gdb\compsale",
                                  full_sale_parcel_output_fc)

    if create_comp_insp_pt_fc.lower() == "true":
        if arcpy.Exists(full_comp_insp_pt_output_fc):
            arcpy.AddMessage("Comp_insp_pt output already exists, skipping")
            update_comp_insp_pt_fc_permissions = False
        else:
            arcpy.Copy_management(r"templates\templates.gdb\comp_insp_pt",
                                  full_comp_insp_pt_output_fc)

    arcpy.AddMessage("COMPLETE (2/21): Create Output Feature Classes")

    if create_parcel_fc.lower() == "true":
        # 3 - Project CL parcel shapefile 1 to local StatePlane 2011 and output to temp FGDB
        epsg = int(csDict.get(countyFIPS)[2])
        if not epsg:
            arcpy.AddError("ERROR: Unable to identify Coordinate System, exit")
            sys.exit("ERROR: Unable to identify Coordinate System, exit")

        state_coordinate_system = arcpy.SpatialReference(epsg)
        arcpy.AddMessage(
            "START (3/21): Project Parcel data 1 to local State Plane")
        arcpy.Project_management(cl_parcel_shp1, "temp1",
                                 state_coordinate_system)
        arcpy.AddMessage(
            "COMPLETE (3/21): Project Parcel data 1 to local State Plane")

        # 4a - Project CL parcel shapefile 2 to local StatePlane 2011 and append to temp1
        if num_cl_shp == "2":
            arcpy.AddMessage(
                "START (4a-1/21): Project Parcel data 2 to local State Plane")
            arcpy.Project_management(cl_parcel_shp2, "temp1a",
                                     state_coordinate_system)
            arcpy.AddMessage(
                "COMPLETE (4a-1/21): Project Parcel data to local State Plane")
            arcpy.AddMessage(
                "START (4a-2/21): Project Parcel data 2 append to temp1")
            arcpy.Append_management("temp1a", "temp1", "TEST")
            arcpy.AddMessage(
                "COMPLETE (4a-2/21): Project Parcel data 2 append to temp1")
        elif num_cl_shp == "3":
            # 4b - Project CL parcel shapefiles 2 and 3 to local StatePlane 2011 and append to temp1
            arcpy.AddMessage(
                "START (4b-1/21): Project Parcel data 2 to local State Plane")
            arcpy.Project_management(cl_parcel_shp2, "temp1a",
                                     state_coordinate_system)
            arcpy.AddMessage(
                "COMPLETE (4b-1/21): Project Parcel data 2 to local State Plane"
            )
            arcpy.AddMessage(
                "START (4b-2/21): Project Parcel data 3 to local State Plane")
            arcpy.Project_management(cl_parcel_shp3, "temp1b",
                                     state_coordinate_system)
            arcpy.AddMessage(
                "COMPLETE (4b-2/21): Project Parcel data 3 to local State Plane"
            )
            arcpy.AddMessage(
                "START (4b-3/21): Project Parcel data 2 and 3 append to temp1")
            arcpy.Append_management(["temp1a", "temp1b"], "temp1", "TEST")
            arcpy.AddMessage(
                "COMPLETE (4b-3/21): Project Parcel data 2 and 3 append to temp1"
            )
        elif num_cl_shp == "4":
            # 4c - Project CL parcel shapefiles 2, 3, and 4 to local StatePlane 2011 and append to temp1
            arcpy.AddMessage(
                "START (4c-1/21): Project Parcel data 2 to local State Plane")
            arcpy.Project_management(cl_parcel_shp2, "temp1a",
                                     state_coordinate_system)
            arcpy.AddMessage(
                "COMPLETE (4c-1/21): Project Parcel data 2 to local State Plane"
            )
            arcpy.AddMessage(
                "START (4c-2/21): Project Parcel data 3 to local State Plane")
            arcpy.Project_management(cl_parcel_shp3, "temp1b",
                                     state_coordinate_system)
            arcpy.AddMessage(
                "COMPLETE (4c-2/21): Project Parcel data 3 to local State Plane"
            )
            arcpy.AddMessage(
                "START (4c-3/21): Project Parcel data 4 to local State Plane")
            arcpy.Project_management(cl_parcel_shp4, "temp1c",
                                     state_coordinate_system)
            arcpy.AddMessage(
                "COMPLETE (4c-3/21): Project Parcel data 4 to local State Plane"
            )
            arcpy.AddMessage(
                "START (4c-4/21): Project Parcel data 2, 3, and 4 append to temp1"
            )
            arcpy.Append_management(["temp1a", "temp1b", "temp1c"], "temp1",
                                    "TEST")
            arcpy.AddMessage(
                "COMPLETE (4c-4/21): Project Parcel data 2, 3, and 4 append to temp1"
            )
        else:
            # No additional shapefiles to project and append
            arcpy.AddMessage("No additional shapefiles to project and append")

        # 5 - Add fields
        arcpy.AddMessage("START (5/21): Add additional attribute fields")
        fields = [
            ("SALE", "TEXT", "20"),
            ("BOOK_PAGE", "TEXT", "20"),
            ("SALE_DOC_NBR", "TEXT", "20"),
            ("COUNTY", "TEXT", "50"),
            ("M_ACRES", "DOUBLE", ""),
            ("M_SQFT", "DOUBLE", ""),
            ("SALE_CNT", "SHORT", ""),
            ("SALE_TOT_VAL", "DOUBLE", ""),
            ("SALE_LND_VAL", "DOUBLE", ""),
            ("SALE_IMP_VAL", "DOUBLE", ""),
            ("SALE_LAND_ACRES", "DOUBLE", ""),
            ("SALE_LAND_SQFT", "LONG", ""),
            ("SALE_UBLD_SQFT", "LONG", ""),
            ("SALE_YR_BLT_MIN", "SHORT", ""),
            ("SALE_YR_BLT_MAX", "SHORT", ""),
            ("SALE_M_ACRES", "DOUBLE", ""),
            ("SALE_M_SQFT", "DOUBLE", ""),
            ("SALE_PR_ACRE", "DOUBLE", ""),
            ("SALE_PR_SQFT", "DOUBLE", ""),
            ("MI_TO_SUBJECT", "DOUBLE", ""),
            ("SALE_YEAR", "SHORT", ""),
            ("DEED_DATE", "DATE", ""),
            ("GRANTOR", "TEXT", "255"),
            ("GRANTEE", "TEXT", "255"),
            ("RMI_USE", "TEXT", "50"),
            ("SALE_NOTES", "TEXT", "255"),
            ("VRFD_ACRES", "DOUBLE", ""),
            ("VRFD_SQFT", "DOUBLE", ""),
            ("VRFD_SIZE_SOURCE", "SHORT", ""),
            ("DEED_TAX", "DOUBLE", ""),
            ("DEED_SALE_PRICE", "DOUBLE", ""),
            ("DEED_NOTES", "TEXT", "255"),
            ("PARCEL_INCL_SALE", "SHORT", ""),
            ("VERIFIED_BY", "TEXT", "10"),
            ("DEED", "TEXT", "3"),
            ("DEED_VRFD", "TEXT", "3"),
            ("DEED_PKG", "TEXT", "3"),
            ("MAPPED", "TEXT", "3"),
            ("INSPECTED", "TEXT", "3"),
            ("SELECTION", "SHORT", ""),
            ("STATUS", "SHORT", ""),
            ("SUBSTATUS", "SHORT", ""),
            ("STATUS_NOTES", "TEXT", "255"),
            ("SALE_GRP1", "SHORT", ""),
            ("SALE_GRP2", "SHORT", ""),
            ("SALE_GRP3", "SHORT", ""),
            ("SALE_GRP4", "SHORT", ""),
            ("SALE_GRP5", "SHORT", ""),
            ("SALE_PRIM_SEC", "SHORT", ""),
            ("SALE_QUERY", "SHORT", ""),
            ("CUSTOM1", "TEXT", "50"),
            ("CUSTOM2", "TEXT", "50"),
            ("CUSTOM3", "TEXT", "50"),
            ("CUSTOM4", "TEXT", "50"),
            ("CUSTOM5", "TEXT", "50"),
            ("SALE_APNS", "TEXT", "255"),
        ]

        # Create the fields using the above parameters
        for field in fields:
            arcpy.AddField_management("temp1", field[0], field[1], "", "",
                                      field[2], "", "NULLABLE", "NON_REQUIRED",
                                      "")
        arcpy.AddMessage("COMPLETE (5/21): Add additional attribute fields")

        # 6 - Calculate Field M_ACRES and M_SQFT
        arcpy.AddMessage("START (6/21): Calculate parcel measured size")
        arcpy.CalculateField_management("temp1", "M_ACRES",
                                        "!Shape.area@acres!", "PYTHON3")
        # arcpy.CalculateGeometryAttributes_management("temp1", geometry_property=[["M_ACRES", "AREA"]], area_unit="ACRES", coordinate_system=state_coordinate_system)

        arcpy.CalculateField_management("temp1", "M_SQFT",
                                        "!Shape.area@squarefeet!", "PYTHON3")
        # arcpy.CalculateGeometryAttributes_management("temp1", geometry_property=[["M_SQFT", "AREA"]], area_unit="SQUARE_FEET_US", coordinate_system=state_coordinate_system)

        arcpy.AddMessage("COMPLETE (6/21): Calculate parcel measured size")

        # 7 - Calculate Sale Book/Page
        arcpy.AddMessage("START (7/21): Calculate Book/Page")
        expression_BP = "getBookPage(!SALE_BK_PG!)"
        codeblock_BP = """def getBookPage(SALE_BK_PG):
            if SALE_BK_PG == '':
                return None
            elif SALE_BK_PG == ' ':
                return None
            else:
                return (SALE_BK_PG[0:6].lstrip("0") + '-'
                + SALE_BK_PG[6:].lstrip("0"))"""
        arcpy.CalculateField_management("temp1", "BOOK_PAGE", expression_BP,
                                        "PYTHON3", codeblock_BP)
        arcpy.AddMessage("COMPLETE (7/21): Calculate Book/Page")

        # 8 - Calculate Sale Document Number
        arcpy.AddMessage("START (8/21): Calculate Document Number")
        expression_DN = "getDocNbr(!REC_DT!,!DOC_NBR!)"
        codeblock_DN = """def getDocNbr(REC_DT,DOC_NBR):
            if REC_DT == 0:
                return None
            elif DOC_NBR == '':
                return None
            elif DOC_NBR == ' ':
                return None
            else:
                return str(REC_DT)[0:4] + '-' + str(DOC_NBR)"""
        arcpy.CalculateField_management("temp1", "SALE_DOC_NBR", expression_DN,
                                        "PYTHON3", codeblock_DN)
        arcpy.AddMessage("COMPLETE (8/21): Calculate Document Number")

        # 9 - Calculate Sale Year
        arcpy.AddMessage("START (9/21): Calculate Sale Year")
        expression_SY = "getSaleYear(!SALE_DT!)"
        codeblock_SY = """def getSaleYear(SALE_DT):
            if SALE_DT == 0:
                return None
            else:
                SALE_YR = str(SALE_DT)[0:4]
                return int(SALE_YR)"""
        arcpy.CalculateField_management("temp1", "SALE_YEAR", expression_SY,
                                        "PYTHON3", codeblock_SY)
        arcpy.AddMessage("COMPLETE (9/21): Calculate Sale Year")

        # 10 - Calculate Additional Attributes (County & Boolean)

        no_value = "NO"
        arcpy.AddMessage(
            "START 10/21): Calculate Additional Attributes (County & Boolean)")
        arcpy.CalculateField_management("temp1", "COUNTY",
                                        "'" + countyName + "'", "PYTHON3")
        arcpy.CalculateField_management("temp1", "DEED", "'" + no_value + "'",
                                        "PYTHON3")
        arcpy.CalculateField_management("temp1", "DEED_VRFD",
                                        "'" + no_value + "'", "PYTHON3")
        arcpy.CalculateField_management("temp1", "DEED_PKG",
                                        "'" + no_value + "'", "PYTHON3")
        arcpy.CalculateField_management("temp1", "MAPPED",
                                        "'" + no_value + "'", "PYTHON3")
        arcpy.CalculateField_management("temp1", "INSPECTED",
                                        "'" + no_value + "'", "PYTHON3")
        arcpy.AddMessage(
            "COMPLETE (10/21): Calculate Additional Attributes (County & Boolean)"
        )

        # 11 - Calculate SALE_ID (Select whether Book_Page or SALE_DOC_NBR is appropriate)
        arcpy.AddMessage("START (11/21): Calculate SaleID")
        expression = "getSaleID(!SALE_DOC_NBR!,!BOOK_PAGE!)"
        codeblock1 = """def getSaleID(SALE_DOC_NBR,BOOK_PAGE):
            if SALE_DOC_NBR is not None:
                return SALE_DOC_NBR
            else:
                return None"""
        codeblock2 = """def getSaleID(SALE_DOC_NBR,BOOK_PAGE):
            if SALE_DOC_NBR is not None:
                return SALE_DOC_NBR
            elif SALE_DOC_NBR is None and BOOK_PAGE is not None:
                return BOOK_PAGE
            else:
                return None"""
        codeblock3 = """def getSaleID(SALE_DOC_NBR,BOOK_PAGE):
            if BOOK_PAGE is not None:
                return BOOK_PAGE
            else:
                return None"""
        codeblock4 = """def getSaleID(SALE_DOC_NBR,BOOK_PAGE):
            if BOOK_PAGE is not None:
                return BOOK_PAGE
            elif BOOK_PAGE is None and SALE_DOC_NBR is not None:
                return SALE_DOC_NBR
            else:
                return None"""
        # Execute Calculate Field
        if firstSaleID == "Document Number" and secondSaleID == "None":
            arcpy.CalculateField_management("temp1", "SALE", expression,
                                            "PYTHON3", codeblock1)
        elif firstSaleID == "Document Number" and secondSaleID == "Book/Page":
            arcpy.CalculateField_management("temp1", "SALE", expression,
                                            "PYTHON3", codeblock2)
        elif firstSaleID == "Book/Page" and secondSaleID == "None":
            arcpy.CalculateField_management("temp1", "SALE", expression,
                                            "PYTHON3", codeblock3)
        elif firstSaleID == "Book/Page" and secondSaleID == "Document Number":
            arcpy.CalculateField_management("temp1", "SALE", expression,
                                            "PYTHON3", codeblock4)
        elif firstSaleID == "Document Number" and secondSaleID == "Document Number":
            print(
                "ERROR: Cannot select same field for First and Second Sale ID."
            )
        elif firstSaleID == "Book/Page" and secondSaleID == "Book/Page":
            print(
                "ERROR: Cannot select same field for First and Second Sale ID."
            )
        else:
            print(
                "ERROR: Must select First Sale ID & OPTIONALLY select Second Sale \n"
                "ID.")
        arcpy.AddMessage("COMPLETE (11/21): Calculate SaleID")

        # 12 - Select non-null SaleIDs, first create feature layer
        arcpy.AddMessage(
            "START (12/21): Non-null SaleID Selection and Calculation \n"
            "of Summary Statistics")
        arcpy.MakeFeatureLayer_management("temp1", "temp1_lyr")
        arcpy.SelectLayerByAttribute_management("temp1_lyr", "NEW_SELECTION",
                                                "SALE IS NOT NULL")
        # Calculate Summary Statistics of selected Sales
        arcpy.Statistics_analysis(
            "temp1_lyr", "temp_sum",
            [["TOT_VAL", "SUM"], ["LAN_VAL", "SUM"], ["IMP_VAL", "SUM"],
             ["LAND_ACRES", "SUM"], ["LAND_SQ_FT", "SUM"],
             ["UBLD_SQ_FT", "SUM"], ["YR_BLT", "MIN"], ["YR_BLT", "MAX"],
             ["M_ACRES", "SUM"], ["M_SQFT", "SUM"]], "SALE")
        arcpy.AddMessage("COMPLETE (12/21): Non-null SaleID Selection and \n"
                         "Calculation of Summary Statistics")

        # 13 - Join summary statistics to parcel fc
        arcpy.AddMessage(
            "START (13/21): Summary Statistics Join and Transfer of \n"
            "Values")
        arcpy.MakeTableView_management("temp_sum", "temp_sum_view")
        arcpy.SelectLayerByAttribute_management("temp1_lyr", "CLEAR_SELECTION")
        arcpy.AddJoin_management("temp1_lyr", "SALE", "temp_sum_view", "SALE")

        # Calculate fields from joined table to feature class
        arcpy.CalculateField_management("temp1_lyr", "temp1.SALE_CNT",
                                        "!temp_sum.FREQUENCY!", "PYTHON3")
        arcpy.AddMessage("PROCESS (1/11): SALE_CNT Complete")
        arcpy.CalculateField_management("temp1_lyr", "temp1.SALE_TOT_VAL",
                                        "!temp_sum.SUM_TOT_VAL!", "PYTHON3")
        arcpy.AddMessage("PROCESS (2/11): SALE_TOT_VAL Complete")
        arcpy.CalculateField_management("temp1_lyr", "temp1.SALE_LND_VAL",
                                        "!temp_sum.SUM_LAN_VAL!", "PYTHON3")
        arcpy.AddMessage("PROCESS (3/11): SALE_LND_VAL Complete")
        arcpy.CalculateField_management("temp1_lyr", "temp1.SALE_IMP_VAL",
                                        "!temp_sum.SUM_IMP_VAL!", "PYTHON3")
        arcpy.AddMessage("PROCESS (4/11): SALE_IMP_VAL Complete")
        arcpy.CalculateField_management("temp1_lyr", "temp1.SALE_LAND_ACRES",
                                        "!temp_sum.SUM_LAND_ACRES!", "PYTHON3")
        arcpy.AddMessage("PROCESS (5/11): SALE_LAND_ACRES Complete")
        arcpy.CalculateField_management("temp1_lyr", "temp1.SALE_LAND_SQFT",
                                        "!temp_sum.SUM_LAND_SQ_FT!", "PYTHON3")
        arcpy.AddMessage("PROCESS (6/11): SALE_LAND_SQFT Complete")
        arcpy.CalculateField_management("temp1_lyr", "temp1.SALE_UBLD_SQFT",
                                        "!temp_sum.SUM_UBLD_SQ_FT!", "PYTHON3")
        arcpy.AddMessage("PROCESS (7/11): SALE_UBLD_SQFT Complete")
        arcpy.CalculateField_management("temp1_lyr", "temp1.SALE_YR_BLT_MIN",
                                        "!temp_sum.MIN_YR_BLT!", "PYTHON3")
        arcpy.AddMessage("PROCESS (8/11): SALE_YR_BLT_MIN Complete")
        arcpy.CalculateField_management("temp1_lyr", "temp1.SALE_YR_BLT_MAX",
                                        "!temp_sum.MAX_YR_BLT!", "PYTHON3")
        arcpy.AddMessage("PROCESS (9/11): SALE_YR_BLT_MAX Complete")
        arcpy.CalculateField_management("temp1_lyr", "temp1.SALE_M_ACRES",
                                        "!temp_sum.SUM_M_ACRES!", "PYTHON3")
        arcpy.AddMessage("PROCESS (10/11): SALE_M_ACRES Complete")
        arcpy.CalculateField_management("temp1_lyr", "temp1.SALE_M_SQFT",
                                        "!temp_sum.SUM_M_SQFT!", "PYTHON3")
        arcpy.AddMessage("PROCESS (11/11): SALE_M_SQFT Complete")

        # Remove temp_sum Join
        arcpy.RemoveJoin_management("temp1_lyr", "temp_sum")
        arcpy.AddMessage(
            "COMPLETE (13/21): Summary Statistics Join and Transfer \n"
            "of Values")

        # 14 - Concatenate Sale APNs
        arcpy.AddMessage("COMPLETE (14/21): Concatenate APNs")
        apnDict = dict()

        def isNotEmpty(val):
            return bool(val is not None and len(str(val).strip()) > 0)

        count = 0
        with arcpy.da.SearchCursor('temp1', ['SALE', 'APN']) as cursor:
            for row in cursor:
                count += 1
                print(count)
                if isNotEmpty(row[0]) and isNotEmpty(row[1]):
                    apnDict.setdefault(row[0], []).append(str(row[1]).strip())

        with arcpy.da.UpdateCursor('temp1', ['SALE', 'SALE_APNS']) as cursor:
            for row in cursor:
                if row[0] in apnDict:
                    row[1] = get_APN_string_list(apnDict[row[0]])
                    cursor.updateRow(row)

        arcpy.AddMessage("COMPLETE (14/21): Concatenate APNs")

        # 15 - Calculate Sale Unit Values
        # Calculate SALE_PR_ACRE
        arcpy.AddMessage("START (15/21): Calculate Sale Unit values")
        expression_SPA = "getPrAcre(!SALE_PRICE!, !SALE_M_ACRES!)"
        codeblock_SPA = """def getPrAcre(SALE_PRICE,SALE_M_ACRES):
            if SALE_PRICE > 0 and SALE_M_ACRES is not None:
                return SALE_PRICE/SALE_M_ACRES
            else:
                return None"""
        arcpy.CalculateField_management("temp1", "SALE_PR_ACRE",
                                        expression_SPA, "PYTHON3",
                                        codeblock_SPA)
        arcpy.AddMessage("PROCESS (1/2): SALE_PR_ACRE Complete")

        # Calculate SALE_PR_SQFT
        expression_SPSF = "getPrSqft(!SALE_PRICE!, !SALE_M_SQFT!)"
        codeblock_SPSF = """def getPrSqft(SALE_PRICE,SALE_M_SQFT):
            if SALE_PRICE > 0 and SALE_M_SQFT is not None:
                return SALE_PRICE/SALE_M_SQFT
            else:
                return None"""
        arcpy.CalculateField_management("temp1", "SALE_PR_SQFT",
                                        expression_SPSF, "PYTHON3",
                                        codeblock_SPSF)

        arcpy.AddMessage("PROCESS (2/2): SALE_PR_SQFT Complete")
        arcpy.AddMessage("COMPLETE (15/21): Calculate Sale Unit values")

        # 16 - Query Sales for SALE_QUERY Attribute
        # 1 = SALE_DT >= "'" + sale_year_query + "0101'" & SALE_PRICE > 100
        # 2 =
        arcpy.AddMessage("START (16/21): Sale Query")
        select_exp1 = str("SALE_DT >= " + sale_year_query +
                          "0101 AND SALE_PRICE > 100")
        select_exp2 = str("SALE_DT >= " + sale_year_query +
                          "0101 AND SALE_PRICE > 100 AND SALE_IMP_VAL <= " +
                          impValQuery)
        select_exp3 = str(
            "SALE_DT >= " + sale_year_query +
            "0101 AND SALE_PRICE > 100 AND SALE_YR_BLT_MAX >= SALE_YEAR")
        select_exp4 = str("SALE_DT >= " + sale_year_query +
                          "0101 AND SALE_PRICE > 100 AND SALE_IMP_VAL <= " +
                          impValQuery + " AND SALE_YR_BLT_MAX >= SALE_YEAR")
        arcpy.MakeFeatureLayer_management("temp1", "temp1_lyr2")
        arcpy.SelectLayerByAttribute_management("temp1_lyr2", "NEW_SELECTION",
                                                select_exp1)
        arcpy.CalculateField_management("temp1_lyr2", "SALE_QUERY", "1",
                                        "PYTHON3")
        arcpy.SelectLayerByAttribute_management("temp1_lyr2", "NEW_SELECTION",
                                                select_exp2)
        arcpy.CalculateField_management("temp1_lyr2", "SALE_QUERY", "2",
                                        "PYTHON3")
        arcpy.SelectLayerByAttribute_management("temp1_lyr2", "NEW_SELECTION",
                                                select_exp3)
        arcpy.CalculateField_management("temp1_lyr2", "SALE_QUERY", "3",
                                        "PYTHON3")
        arcpy.SelectLayerByAttribute_management("temp1_lyr2", "NEW_SELECTION",
                                                select_exp4)
        arcpy.CalculateField_management("temp1_lyr2", "SALE_QUERY", "4",
                                        "PYTHON3")
        arcpy.AddMessage("COMPLETE (16/21): Sale Query")

        # 17 - Delete fields
        arcpy.AddMessage("START (17/21): Delete Unused Attributes")
        del_fields = [
            "PARCEL_ID", "STATE_CODE", "CNTY_CODE", "ZIP", "PLUS", "STD_ADDR",
            "STD_CITY", "STD_STATE", "STD_ZIP", "STD_PLUS", "FIPS_CODE",
            "UNFRM_APN", "APN_SEQ_NO", "ORIG_APN", "ACCT_NO", "TH_BRO_MAP",
            "MAP_REF1", "MAP_REF2", "CENSUS_TR", "M_HOME_IND", "SUB_TR_NUM",
            "SUB_PLT_BK", "SUB_PLT_PG", "OWN_CP_IND", "OWN2_LAST", "OWN2_FRST",
            "MAIL_NBRPX", "MAIL_NBR", "MAIL_NBR2", "MAIL_NBRSX", "MAIL_DIR",
            "MAIL_STR", "MAIL_MODE", "MAIL_QDRT", "MAIL_UNIT", "MAIL_CITY",
            "MAIL_STATE", "MAIL_ZIP", "MAIL_CC", "MAIL_OPT", "TOT_VAL_CD",
            "LAN_VAL_CD", "TAX_AMT", "TAX_YR", "ASSD_YR", "TAX_AREA",
            "TITL_CO_CD", "TITL_CO_NM", "RES_MOD_CD", "MTG_AMT", "MTG_DT",
            "MTG_LOAN", "MTG_DEED", "MTG_TRM_CD", "MTG_TRM", "MTG_DUE_DT",
            "MTG_ASSUM", "MTG_LEN_CD", "MTG_LEN_NM", "MTG2_AMT", "MTG2_LOAN",
            "MTG2_DEED", "FRONT_FT", "DEPTH_FT", "LOT_AREA", "BLD_SQ_IND",
            "BLD_SQ_FT", "LIV_SQ_FT", "GF_SQ_FT", "GR_SQ_FT", "ADJ_SQ_FT",
            "BSMT_SQ_FT", "PKG_SQ_FT", "BEDROOMS", "ROOMS", "BATHS_CAL",
            "BATHS", "FULL_BATHS", "HALF_BATHS", "QTR1_BATHS", "QTR3_BATHS",
            "BATH_FIX", "AIR_COND", "BSMT_FNSH", "BLD_CODE", "BLD_IMP_CD",
            "CONDITION", "CONSTR_TYP", "EXT_WALLS", "FRPLCE_IND", "FRPLCE_NBR",
            "FRPLCE_TYP", "FOUNDATION", "FLOOR", "FRAME", "GARAGE", "HEATING",
            "PKG_SPACES", "PKG_TYP", "POOL", "POOL_CD", "QUALITY",
            "ROOF_COVER", "ROOF_TYP", "STORY_CD", "STORY_NBR", "BLD_VIEW",
            "LOC_INF", "BLD_UNITS", "UNITS_NBR", "ENERGY_USE", "FUEL", "SEWER",
            "WATER"
        ]
        arcpy.DeleteField_management("temp1", del_fields)
        arcpy.AddMessage("COMPLETE (17/21): Delete Unused Attributes")

        # 18/20 - Calculate Distance to Subject
        temp1_desc = arcpy.Describe("temp1")
        yMax = temp1_desc.extent.YMax
        yMin = temp1_desc.extent.YMin
        xMax = temp1_desc.extent.XMax
        xMin = temp1_desc.extent.XMin
        cutoffDistance = math.sqrt(((yMax - yMin)**2) + ((xMax - xMin)**2))

        arcpy.AddMessage("YMax: " + str(yMax))
        arcpy.AddMessage("YMin: " + str(yMin))
        arcpy.AddMessage("XMax: " + str(xMax))
        arcpy.AddMessage("XMin: " + str(xMin))
        arcpy.AddMessage("Cutoff Distance: " + str(cutoffDistance))

        if calculateDistance.lower() == "true":
            # Near - ArcGIS Pro Advanced (Home)
            arcpy.AddMessage(
                "START (18/21): Calculation of Parcel distance to \n"
                "Subject Property - ArcGIS Adv")

            arcpy.Near_analysis("temp1", subjectProperty, cutoffDistance)
            arcpy.AddMessage("PROCESS (1/3): NEAR FEATURE Complete")

            # Calculate MI_TO_SUBJECT (Home)
            arcpy.CalculateField_management("temp1", "MI_TO_SUBJECT",
                                            "!NEAR_DIST!/5280", "PYTHON3")
            arcpy.AddMessage(
                "PROCESS (2/3): MI_TO_SUBJECT Calculation Complete")

            # Delete ET_Closest & ET_Dist (Home)
            arcpy.DeleteField_management("temp1", ["NEAR_FID", "NEAR_DIST"])
            arcpy.AddMessage("PROCESS (3/3): ET Attributes Delete Complete")
            arcpy.AddMessage(
                "COMPLETE (18/21): Calculation of Parcel distance to \n"
                "Subject Property")

        else:
            # No subject distance calculation
            arcpy.AddMessage("Skipping calculation of distance of \n"
                             "parcels to subject property")

        # Copy parcel feature class to Project FGDB (Home)
        arcpy.AddMessage(
            "START (19/21): Copy of Completed Parcels to Project \n"
            "FGDB")
        arcpy.Append_management("temp1",
                                os.path.join(project_fgdb, parcel_output_fc),
                                "NO_TEST")
        arcpy.AddMessage("COMPLETE (19/21): Copy of Completed Parcels to \n"
                         "Project FGDB")

    # 26 - Check for existence of temporary feature classes & tables and delete if exist
    arcpy.AddMessage(
        "START (20/21): Check for temporary features and tables and delete")
    delete_temp_files()
    arcpy.AddMessage(
        "COMPLETE (20/21): Check for temporary features and tables and delete")
    # 27 - Check for existence of temporary feature classes & tables and delete if exist

    # * - Check for existence of temporary feature classes & tables and delete if exist
    arcpy.AddMessage("START (21/21): Add Privileges and Register as Versioned")
    if project_fgdb.lower().endswith(".sde"):
        if create_parcel_fc.lower() == "true":
            arcpy.ChangePrivileges_management(full_parcel_output_fc,
                                              "rmi_editors", "GRANT", "GRANT")
            arcpy.ChangePrivileges_management(full_parcel_output_fc,
                                              "rmi_viewers", "GRANT", "AS_IS")
            arcpy.RegisterAsVersioned_management(full_parcel_output_fc,
                                                 "NO_EDITS_TO_BASE")

        if create_salefc.lower(
        ) == "true" and update_sale_output_fc_permissions:
            arcpy.ChangePrivileges_management(full_sale_parcel_output_fc,
                                              "rmi_editors", "GRANT", "GRANT")
            arcpy.ChangePrivileges_management(full_sale_parcel_output_fc,
                                              "rmi_viewers", "GRANT", "AS_IS")
            arcpy.RegisterAsVersioned_management(full_sale_parcel_output_fc,
                                                 "NO_EDITS_TO_BASE")

        if create_comp_insp_pt_fc.lower(
        ) == "true" and update_comp_insp_pt_fc_permissions:
            arcpy.ChangePrivileges_management(full_comp_insp_pt_output_fc,
                                              "rmi_editors", "GRANT", "GRANT")
            arcpy.ChangePrivileges_management(full_comp_insp_pt_output_fc,
                                              "rmi_viewers", "GRANT", "AS_IS")
            arcpy.RegisterAsVersioned_management(full_comp_insp_pt_output_fc,
                                                 "NO_EDITS_TO_BASE")

    arcpy.AddMessage(
        "COMPLETE (21/21): Add Privileges and Register as Versioned")

    arcpy.AddMessage("COMPLETE PROCESSING CORELOGIC PARCEL DATA")
Esempio n. 12
0
    parser.add_argument('--sde',
                        type=str,
                        required=True,
                        help='Caminho do SDE para conectar ao banco.')
    args = parser.parse_args()

    arcpy.env.workspace = args.sde

    aem.GDBManager.Delete('AEMSDETable')
    aem.GDBManager.CreateTable('AEMSDETable', 'Revisões Empreiteira')
    aem.GDBManager.AddField('AEMSDETable', 'NU_REVEMPREITEIRA_PLANTA_ID',
                            'NU_REVEMPREITEIRA_PLANTA_ID', 'Integer', 5, 0, 4)
    aem.GDBManager.AddField('AEMSDETable', 'NU_PROJETO_ID', 'NU_PROJETO_ID',
                            'Integer', 9, 0, 4)
    aem.GDBManager.AddField('AEMSDETable', 'NU_USUARIO_INFORMANTE_ID',
                            'NU_USUARIO_INFORMANTE_ID', 'Integer', 9, 0, 4)
    aem.GDBManager.AddField('AEMSDETable', 'NU_EMPREITEIRA_ID',
                            'NU_EMPREITEIRA_ID', 'Integer', 9, 0, 4)
    aem.GDBManager.AddField('AEMSDETable', 'DT_DATA', 'DT_DATA', 'Date', 0, 0,
                            36)
    aem.GDBManager.AddField('AEMSDETable', 'NO_ATIVIDADE', 'NO_ATIVIDADE',
                            'String', 0, 0, 15)
    aem.GDBManager.AddField('AEMSDETable', 'NO_RESP_TECNICO',
                            'NO_RESP_TECNICO', 'String', 0, 0, 80)
    aem.GDBManager.AddField('AEMSDETable', 'DE_CREA', 'DE_CREA', 'String', 0,
                            0, 50)
    aem.GDBManager.AddField('AEMSDETable', 'CD_STATUS_PROJETO',
                            'CD_STATUS_PROJETO', 'Integer', 9, 0, 4)
    arcpy.ChangePrivileges_management(arcpy.env.workspace + "\\AEMSDETable",
                                      "NEOGSE", "GRANT", "GRANT")
def mainFunction(
    databaseUsers, 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)

                # Get all the database users
                databaseUsers = string.split(databaseUsers, ",")

                # 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 permissions to be assigned to the dataset
                        viewUsers = row[1]
                        viewUsers = string.split(viewUsers, ",")
                        editUsers = row[2]
                        editUsers = string.split(editUsers, ",")

                        # For each database user
                        for databaseUser in databaseUsers:
                            # Set the default value for privileges assigned
                            viewPrivilegesAssigned = "false"
                            editPrivilegesAssigned = "false"

                            # For each user
                            for viewUser in viewUsers:
                                # If the database user has view privileges
                                if (databaseUser == viewUser):
                                    # Logging
                                    if (enableLogging == "true"):
                                        logger.info(
                                            "Assigning View Permission to " +
                                            viewUser + " on dataset " +
                                            dataset + "...")
                                    arcpy.AddMessage(
                                        "Assigning View Permission to " +
                                        viewUser + " on dataset " + dataset +
                                        "...")
                                    # Change the view privileges for the user on the dataset
                                    arcpy.ChangePrivileges_management(
                                        dataset, viewUser, "GRANT", "")
                                    viewPrivilegesAssigned = "true"

                            # If privileges haven't been granted for this user on this dataset
                            if (viewPrivilegesAssigned == "false"):
                                # Logging
                                if (enableLogging == "true"):
                                    logger.info("Denying View Permission to " +
                                                databaseUser + " on dataset " +
                                                dataset + "...")
                                arcpy.AddMessage(
                                    "Denying View Permission to " +
                                    databaseUser + " on dataset " + dataset +
                                    "...")
                                # Change the view privileges for the user on the dataset
                                arcpy.ChangePrivileges_management(
                                    dataset, databaseUser, "REVOKE", "")

                            # For each user
                            for editUser in editUsers:
                                # If the database user has edit privileges
                                if (databaseUser == editUser):
                                    # Logging
                                    if (enableLogging == "true"):
                                        logger.info(
                                            "Assigning Edit Permission to " +
                                            editUser + " on dataset " +
                                            dataset + "...")
                                    arcpy.AddMessage(
                                        "Assigning Edit Permission to " +
                                        editUser + " on dataset " + dataset +
                                        "...")
                                    # Change the edit privileges for the user on the dataset
                                    arcpy.ChangePrivileges_management(
                                        dataset, editUser, "GRANT", "GRANT")
                                    editPrivilegesAssigned = "true"

                            # If privileges haven't been granted for this user on this dataset
                            if (editPrivilegesAssigned == "false"):
                                # Logging
                                if (enableLogging == "true"):
                                    logger.info("Denying Edit Permission to " +
                                                databaseUser + " on dataset " +
                                                dataset + "...")
                                arcpy.AddMessage(
                                    "Denying Edit Permission to " +
                                    databaseUser + " on dataset " + dataset +
                                    "...")
                                # Change the edit privileges for the user on the dataset
                                arcpy.ChangePrivileges_management(
                                    dataset, databaseUser, "AS_IS", "REVOKE")

                    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)
Esempio n. 14
0
import arcpy

GISusername = "******"

SYSPROD = r"Database Connections/SDEPROD_GIS.sde"  #PROD DB OWNER
SYSDEV = r"Database Connections/SDEDEV_GISDEV.sde"  #DEV DB OWNER
ViewPerm = "GRANT"
EditPerm = "GRANT"  #options are GRANT, AS_IS, REVOKE

#Grant Dev permissions to everything
arcpy.env.workspace = SYSDEV
datasets = arcpy.ListDatasets("*", "Feature")

for dataset in datasets:
    try:
        arcpy.ChangePrivileges_management(SYSDEV + "//" + dataset, GISusername,
                                          ViewPerm, EditPerm)
    except:
        print SYSDEV + " " + dataset + "!!!"
        pass
#PROD
arcpy.env.workspace = SYSPROD
datasets = arcpy.ListDatasets("*", "Feature")

for dataset in datasets:
    try:
        arcpy.ChangePrivileges_management(SYSPROD + "//" + dataset,
                                          GISusername, ViewPerm, EditPerm)
    except:
        print SYSPROD + " " + dataset + "!!!"
        pass
Esempio n. 15
0
def main():

    try:
        if sde_fida is False and del_exists is True:
            create_fgdb()
        load_json_file()
        if sde_fida is True:
            get_connected_user()
            block_connections()
            disconnect_user()
            accept_connections()
        set_workspace()
        if del_exists is True:
            create_fds()
            del_all_domains()
            create_domins()
            create_fcs()
        fill_domains()
        add_field()
        create_rel_classes()
        if sde_fida is True and del_exists is True:
            arcpy.RegisterAsVersioned_management(
                in_dataset=os.path.join(get_workspace(), featuredataset),
            )
            print("Regisert as versioned")

            # # Datenbank ist auf Branch gestellt --> Archiving is already enabled on the dataset.

            # Enable Replica Tracking
            datasetname = os.path.join(get_workspace(), featuredataset)
            arcpy.EnableReplicaTracking_management(datasetname)
            # Execute ChangePrivileges
            arcpy.ChangePrivileges_management(
                datasetname, "ARCSDE_EDITOR", "GRANT", "GRANT"
            )
            arcpy.ChangePrivileges_management(datasetname, "ARCSDE_READER", "GRANT")

            # enable Replica fuer einzelnen Tabellen
            # (Wichtig fuer Branchversioning)
            _uebersetzungtable = os.path.join(get_workspace(), "FIDA_UEBERSETZUNG")
            arcpy.RegisterAsVersioned_management(in_dataset=_uebersetzungtable)
            arcpy.EnableReplicaTracking_management(_uebersetzungtable)
            print("Table: " + _uebersetzungtable + " enableReplica")

            _arbeitskuerzeltable = os.path.join(
                get_workspace(), "FIDA_ARBEITSKUERZELLFP"
            )
            arcpy.RegisterAsVersioned_management(in_dataset=_arbeitskuerzeltable)
            arcpy.EnableReplicaTracking_management(_arbeitskuerzeltable)
            print("Table: " + _arbeitskuerzeltable + " enableReplica")

            _monitortable = os.path.join(get_workspace(), "FIDA_MONITOR")
            arcpy.RegisterAsVersioned_management(in_dataset=_monitortable)
            arcpy.EnableReplicaTracking_management(_monitortable)
            print("Table: " + _monitortable + " enableReplica")

            _inmutationtable = os.path.join(get_workspace(), "FIDA_INMUTATION")
            arcpy.RegisterAsVersioned_management(in_dataset=_inmutationtable)
            arcpy.EnableReplicaTracking_management(_inmutationtable)
            print("Table: " + _inmutationtable + " enableReplica")

    except Exception:
        print("!!! Exception !!!")
        e = sys.exc_info()[1]
        print(e.args[0])
        if sde_fida is True:
            accept_connections()
Esempio n. 16
0
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")