Esempio n. 1
0
def main():
    login_info = {}
    login_info['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    login_info['username'] = raw_input("Enter User Name: ")  #<UserName>
    login_info['password'] = raw_input("Enter password: "******"http://arcgis.com/"

    item_Id = "d4718e6a27a04deab6f764cd70e102f4"  #<Item ID>
    sql = "OBJECTID>0"
    layerName = "Bus_Stops"  #layer1, layer2
    saveLocation = r"C:\PythonBook\Scripts\SanFrancisco.gdb\demo"
    fea_service_tool = featureservicetools.featureservicetools(login_info)
    feature_service = fea_service_tool.GetFeatureService(item_Id, False)
    print "Service is ", feature_service
    if feature_service != None:
        feature_service_url = fea_service_tool.GetLayerFromFeatureService(
            feature_service, layerName, True)
        print "url is ", feature_service_url
        if feature_service_url != None:
            demo = fea_service_tool.QueryAllFeatures(feature_service_url,
                                                     where="1=1",
                                                     out_fields="*",
                                                     timeFilter=None,
                                                     geometryFilter=None,
                                                     returnFeatureClass=True,
                                                     out_fc=saveLocation,
                                                     outSR=None,
                                                     chunksize=1000,
                                                     printIndent="")
Esempio n. 2
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""  #<UserName>
    securityinfo['password'] = ""  #<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    itemId = ""  #<Item ID>

    layerName = ""  #layer1
    id_field = 'PARCELID'  # ID Field

    pathToFeatureClass = r""  #Path to FC
    try:
        startTime = datetime.datetime.now()
        print "Starting process at %s" % (configFile,
                                          startTime.strftime(dateTimeFormat))

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print fst.message
        else:

            fs = fst.GetFeatureService(itemId=itemId, returnURLOnly=False)
            if not fs is None:

                fs_url = fst.GetLayerFromFeatureService(fs=fs,
                                                        layerName=layerName,
                                                        returnURLOnly=True)
                if not fs_url is None:
                    results = fst.RemoveAndAddFeatures(
                        url=fs_url,
                        pathToFeatureClass=pathToFeatureClass,
                        id_field=id_field,
                        chunksize=50)

        print "process completed in %s" % (
            configFile, str(datetime.datetime.now() - startTime))
    except (common.ArcRestHelperError), e:
        print "error in function: %s" % e[0]['function']
        print "error on line: %s" % e[0]['line']
        print "error in file name: %s" % e[0]['filename']
        print "with error message: %s" % e[0]['synerror']
        if 'arcpyError' in e[0]:
            print "with arcpy message: %s" % e[0]['arcpyError']
def main():
    proxy_port = None
    proxy_url = None    

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""#<UserName>
    securityinfo['password'] = ""#<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None   


    itemId = ""#<Item ID>
   
    layerName = "" #layer1
    id_field ='PARCELID' # ID Field
    
    pathToFeatureClass = r""#Path to FC
    try:      
        startTime = datetime.datetime.now()
        print "Starting process at %s" % (configFile,startTime.strftime(dateTimeFormat))
            
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print fst.message
        else:         

            fs = fst.GetFeatureService(itemId=itemId,returnURLOnly=False)
            if not fs is None:
               
                fs_url = fst.GetLayerFromFeatureService(fs=fs,layerName=layerName,returnURLOnly=True)
                if not fs_url is None:
                    results =  fst.RemoveAndAddFeatures(url=fs_url,
                                                        pathToFeatureClass=pathToFeatureClass,
                                                        id_field=id_field,
                                                      chunksize=50)
                    
        print "process completed in %s" % (configFile, str(datetime.datetime.now() - startTime))
    except (common.ArcRestHelperError),e:
        print "error in function: %s" % e[0]['function']
        print "error on line: %s" % e[0]['line']
        print "error in file name: %s" % e[0]['filename']
        print "with error message: %s" % e[0]['synerror']
        if 'arcpyError' in e[0]:
            print "with arcpy message: %s" % e[0]['arcpyError']
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""#<UserName>
    securityinfo['password'] = ""#<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None


    itemId = ""#<Item ID>
    sql = "status = 3" #Completed work
    saveLocation = r"c:\temp\completedWork.gdb" #GDB or folder to save result
    outName = "completedWork" #Name of result

    try:

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print (fst.message)
        else:
            fs = fst.GetFeatureService(itemId=itemId,returnURLOnly=False)
            if not fs is None:
                fls = fs.layers
                if len(fls) > 0 :
                    fl = fls[0]

                    res =  fst.QueryAllFeatures(url=fl.url,
                                    sql=sql,
                                    chunksize=300,
                                    saveLocation=saveLocation,
                                    outName=outName)
                    print (res)
                    res = fst.DeleteFeaturesFromFeatureLayer(url=fl.url, sql=sql)
                    print (res)

    except (common.ArcRestHelperError),e:
        print ("error in function: %s" % e[0]['function'])
        print ("error on line: %s" % e[0]['line'])
        print ("error in file name: %s" % e[0]['filename'])
        print ("with error message: %s" % e[0]['synerror'])
        if 'arcpyError' in e[0]:
            print ("with arcpy message: %s" % e[0]['arcpyError'])
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""  #<UserName>
    securityinfo['password'] = ""  #<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    itemId = ""  #<Item ID>
    sql = "status = 3"  #Completed work
    saveLocation = r"c:\temp\completedWork.gdb"  #GDB or folder to save result
    outName = "completedWork"  #Name of result

    try:

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print(fst.message)
        else:
            fs = fst.GetFeatureService(itemId=itemId, returnURLOnly=False)
            if not fs is None:
                fls = fs.layers
                if len(fls) > 0:
                    fl = fls[0]

                    res = fst.QueryAllFeatures(url=fl.url,
                                               sql=sql,
                                               chunksize=300,
                                               saveLocation=saveLocation,
                                               outName=outName)
                    print(res)
                    res = fst.DeleteFeaturesFromFeatureLayer(url=fl.url,
                                                             sql=sql)
                    print(res)

    except (common.ArcRestHelperError), e:
        print("error in function: %s" % e[0]['function'])
        print("error on line: %s" % e[0]['line'])
        print("error in file name: %s" % e[0]['filename'])
        print("with error message: %s" % e[0]['synerror'])
        if 'arcpyError' in e[0]:
            print("with arcpy message: %s" % e[0]['arcpyError'])
Esempio n. 6
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""  #<UserName>
    securityinfo['password'] = ""  #<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    itemId = ""  #<Item ID>

    layerName = ""  #layer1
    pathToFeatureClass = r""
    try:

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print fst.message
        else:

            fs = fst.GetFeatureService(itemId=itemId, returnURLOnly=False)
            if not fs is None:

                fs_url = fst.GetLayerFromFeatureService(fs=fs,
                                                        layerName=layerName,
                                                        returnURLOnly=True)
                if not fs_url is None:
                    results = fst.AddFeaturesToFeatureLayer(
                        url=fs_url,
                        pathToFeatureClass=pathToFeatureClass,
                        chunksize=2000)
                    if 'addResults' in results:
                        print "%s features processed" % len(
                            results['addResults'])
    except (common.ArcRestHelperError), e:
        print "error in function: %s" % e[0]['function']
        print "error on line: %s" % e[0]['line']
        print "error in file name: %s" % e[0]['filename']
        print "with error message: %s" % e[0]['synerror']
        if 'arcpyError' in e[0]:
            print "with arcpy message: %s" % e[0]['arcpyError']
Esempio n. 7
0
def main():
    securityinfo = {}
    securityinfo['security_type'] = 'Portal'
    securityinfo['username'] = "******"
    securityinfo['password'] = "******"
    securityinfo['org_url'] = "http://www.arcgis.com"
   
    itemCSVFile =  r'<Path to CSV>'
    
    sciptPath = os.getcwd()
    try:
        print "###############Script Started#################"
        print datetime.datetime.now().strftime(dateTimeFormat)
        if os.path.exists(itemCSVFile) == False:
            itemCSVFile = os.path.join(sciptPath,itemCSVFile)
        elif os.path.isabs(itemCSVFile) == False:
            itemCSVFile = os.path.join(sciptPath,itemCSVFile)
        if os.path.exists(itemCSVFile) == False:            
            print "CSV %s could not be located" % itemCSVFile
            return
        if os.path.isfile(itemCSVFile) == False:
            print "csv file %s could not be located" % itemCSVFile
            return
                       
        fst = featureservicetools.featureservicetools(securityinfo=securityinfo)
        if fst.valid:
            with open(itemCSVFile, 'rb') as csvfile:
                
                for row in csv.DictReader(csvfile,dialect='excel'):
                    
                    if not 'itemid' in row:
                        print "itemID could not be found if table"
                        return
                    itemid = row['itemid']
                    fs = fst.GetFeatureService(itemId=itemid,returnURLOnly=False)
                    print fst.disableSync(url=fs.url)
        else:
            print "Error: %s" % fst.message
                                          
    except:
        line, filename, synerror = trace()
        print "error on line: %s" % line)
        print "error in file name: %s" % filename
        print "with error message: %s" % synerror

    finally:
        print datetime.datetime.now().strftime(dateTimeFormat)
        print "###############Script Completed#################"
Esempio n. 8
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'AGS'
    securityinfo['username'] = ""  #<UserName>
    securityinfo['password'] = ""  #<Password>
    securityinfo[
        'org_url'] = ""  #<ArcGIS Server URL, ex: https://myserver/arcgis
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    pathToFeatureClass = r""  #local path to feature class to load
    fs_url = ''  #url to layer, not service, make sure it ends with a \Number

    try:

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print(fst.message)
        else:
            results = fst.AddFeaturesToFeatureLayer(
                url=fs_url,
                pathToFeatureClass=pathToFeatureClass,
                chunksize=2000)
            if 'addResults' in results:
                print("%s features processed" % len(results['addResults']))
    except (common.ArcRestHelperError) as e:
        print("error in function: %s" % e[0]['function'])
        print("error on line: %s" % e[0]['line'])
        print("error in file name: %s" % e[0]['filename'])
        print("with error message: %s" % e[0]['synerror'])
        if 'arcpyError' in e[0]:
            print("with arcpy message: %s" % e[0]['arcpyError'])

    except:
        line, filename, synerror = trace()
        print("error on line: %s" % line)
        print("error in file name: %s" % filename)
        print("with error message: %s" % synerror)
Esempio n. 9
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""  #<UserName>
    securityinfo['password'] = ""  #<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    itemId = ""  #<Item ID>
    sql = "1=1"
    layerNames = ""  #layer1, layer2
    try:

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print fst.message
        else:

            fs = fst.GetFeatureService(itemId=itemId, returnURLOnly=False)
            if not fs is None:

                for layerName in layerNames.split(','):
                    fs_url = fst.GetLayerFromFeatureService(
                        fs=fs, layerName=layerName, returnURLOnly=True)
                    if not fs_url is None:
                        print fst.QueryAllFeatures(url=fs_url,
                                                   sql=sql,
                                                   chunksize=300,
                                                   saveLocation=r"c:\temp",
                                                   outName="test.shp")
    except (common.ArcRestHelperError), e:
        print "error in function: %s" % e[0]['function']
        print "error on line: %s" % e[0]['line']
        print "error in file name: %s" % e[0]['filename']
        print "with error message: %s" % e[0]['synerror']
        if 'arcpyError' in e[0]:
            print "with arcpy message: %s" % e[0]['arcpyError']
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""#<UserName>
    securityinfo['password'] = ""#<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None


    itemId = ""#<Item ID>
    sql = "1=1"
    layerNames = "" #layer1, layer2
    try:

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print fst.message
        else:

            fs = fst.GetFeatureService(itemId=itemId,returnURLOnly=False)
            if not fs is None:

                for layerName in layerNames.split(','):
                    fs_url = fst.GetLayerFromFeatureService(fs=fs,layerName=layerName,returnURLOnly=True)
                    if not fs_url is None:
                        print fst.QueryAllFeatures(url=fs_url,
                                                    sql=sql,
                                                    chunksize=300,
                                                    saveLocation=r"c:\temp",
                                                    outName="test.shp")
    except (common.ArcRestHelperError),e:
        print "error in function: %s" % e[0]['function']
        print "error on line: %s" % e[0]['line']
        print "error in file name: %s" % e[0]['filename']
        print "with error message: %s" % e[0]['synerror']
        if 'arcpyError' in e[0]:
            print "with arcpy message: %s" % e[0]['arcpyError']
Esempio n. 11
0
def main():
    proxy_port = None
    proxy_url = None    

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""#<UserName>
    securityinfo['password'] = ""#<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None   


    itemId = "660c9dde3a24428e9143473f6ee7f77d"#<Item ID>
   
    layerName = "Road Centerlines" #layer1
    pathToFeatureClass = r"C:\temp\teodatabase.gdb\RoadCenterline"
    try:      

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print fst.message
        else:         

            fs = fst.GetFeatureService(itemId=itemId,returnURLOnly=False)
            if not fs is None:
               
                fs_url = fst.GetLayerFromFeatureService(fs=fs,layerName=layerName,returnURLOnly=True)
                if not fs_url is None:
                    results =  fst.AddFeaturesToFeatureLayer(url=fs_url, pathToFeatureClass=pathToFeatureClass, 
                                                      chunksize=2000)
                    if 'addResults' in results:
                        print "%s features added" % len(results['addResults'])
    except (common.ArcRestHelperError),e:
        print "error in function: %s" % e[0]['function']
        print "error on line: %s" % e[0]['line']
        print "error in file name: %s" % e[0]['filename']
        print "with error message: %s" % e[0]['synerror']
        if 'arcpyError' in e[0]:
            print "with arcpy message: %s" % e[0]['arcpyError']
Esempio n. 12
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'AGS'
    securityinfo['username'] = ""#<UserName>
    securityinfo['password'] = ""#<Password>
    securityinfo['org_url'] = ""#<ArcGIS Server URL, ex: https://myserver/arcgis
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None
    
    pathToFeatureClass = r""#local path to feature class to load
    fs_url = ''#url to layer, not service, make sure it ends with a \Number
    
    try:

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print (fst.message)
        else:
            results =  fst.AddFeaturesToFeatureLayer(url=fs_url, pathToFeatureClass=pathToFeatureClass,
                                                      chunksize=2000)
            if 'addResults' in results:
                print ("%s features processed" % len(results['addResults']))
    except (common.ArcRestHelperError) as e:
        print ("error in function: %s" % e[0]['function'])
        print ("error on line: %s" % e[0]['line'])
        print ("error in file name: %s" % e[0]['filename'])
        print ("with error message: %s" % e[0]['synerror'])
        if 'arcpyError' in e[0]:
            print ("with arcpy message: %s" % e[0]['arcpyError'])

    except:
        line, filename, synerror = trace()
        print ("error on line: %s" % line)
        print ("error in file name: %s" % filename)
        print ("with error message: %s" % synerror)
Esempio n. 13
0
def main():
    securityinfo = {}
    securityinfo['security_type'] = 'Portal'
    securityinfo['username'] = ""
    securityinfo['password'] = ""
    securityinfo['org_url'] = "http://www.arcgis.com"
    try:
        fst = featureservicetools.featureservicetools(securityinfo=securityinfo)
        fs = fst.GetFeatureService(itemId='',returnURLOnly=False)
        result = fst.disableSync(url=fs.url)
        print (result)


    except:
        line, filename, synerror = trace()
        print ("error on line: %s" % line)
        print ("error in file name: %s" % filename)
        print ("with error message: %s" % synerror)

    finally:
        print (datetime.datetime.now().strftime(dateTimeFormat))
        print ("###############Script Completed#################")
Esempio n. 14
0
def main():
    securityinfo = {}
    securityinfo['security_type'] = 'Portal'
    securityinfo['username'] = ""
    securityinfo['password'] = ""
    securityinfo['org_url'] = "http://www.arcgis.com"
    try:
        fst = featureservicetools.featureservicetools(
            securityinfo=securityinfo)
        fs = fst.GetFeatureService(itemId='', returnURLOnly=False)
        result = fst.disableSync(url=fs.url)
        print(result)

    except:
        line, filename, synerror = trace()
        print("error on line: %s" % line)
        print("error in file name: %s" % filename)
        print("with error message: %s" % synerror)

    finally:
        print(datetime.datetime.now().strftime(dateTimeFormat))
        print("###############Script Completed#################")
Esempio n. 15
0
def main(*argv):

    fsId = None
    layerName = None
    dataToAppend = None
    fst = None
    fs = None
    results = None
    fl = None
    existingDef= None
    scratchGDB = None
    scratchLayName = None
    scratchLayer = None
    try:
        arcpy.env.overwriteOutput = True

        proxy_port = None
        proxy_url = None

        securityinfo = {}

        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None

        username = argv[0]
        password = argv[1]
        siteURL = argv[2]

        version = arcpy.GetInstallInfo()['Version']
        if re.search("^10\.[0-2]", version) is not None:
            bReqUserName = True
        else:
            bReqUserName = False

        if bReqUserName and \
           (username == None or username == "#" or str(username).strip() == "" or \
            password == None or password== "#" or password== "*" or str(password).strip() == ""):
            outputPrinter ("{0} Requires a username and password".format(version), typeOfMessage='error')
            return

        if bReqUserName:
            securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
            securityinfo['username'] = username
            securityinfo['password'] = password
            securityinfo['org_url'] = siteURL

        else:
            securityinfo['security_type'] = 'ArcGIS'#LDAP, NTLM, OAuth, Portal, PKI

        fsId = argv[3]
        layerName = argv[4]
        dataToAppend = argv[5]
        projection = argv[6]
        lowerCaseFieldNames =argv[7]
        showFullResponse =argv[8]

        scratchGDB = arcpy.env.scratchWorkspace
        scratchLayName = random_string_generator()
        scratchLayer = os.path.join(scratchGDB,scratchLayName)

        if str(lowerCaseFieldNames).upper() == 'TRUE':
            lowerCaseFieldNames = True
        else:
            lowerCaseFieldNames = False

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid:
            fs = fst.GetFeatureService(itemId=fsId,returnURLOnly=False)

            if not fs is None:

                if arcpy.Exists(dataset=dataToAppend) == True:

                    lyr = arcpy.Describe(dataToAppend)
                    result =  arcpy.GetCount_management(dataToAppend)
                    count = int(result.getOutput(0))
                    outputPrinter(message="\t\t%s features" % (count))
                    if count > 0:
                        if projection is not None and projection != "#" and \
                                projection.strip() !='' :

                            outputPrinter(message="\t\tProjecting %s" % (lyr.name))
                            result = arcpy.Project_management(dataToAppend,
                                                              scratchLayer,
                                                              projection)
                        else:
                            outputPrinter(message="\t\tCopying %s feature from %s" % (count,lyr.name))
                            arcpy.FeatureClassToFeatureClass_conversion(dataToAppend,scratchGDB,scratchLayName)
                        desc = arcpy.Describe(scratchLayer)
                        if desc.shapeType == 'Polygon':
                            outputPrinter(message="\t\tDensifying %s" % lyr.name)
                            arcpy.Densify_edit(scratchLayer, "ANGLE", "33 Unknown", "0.33 Unknown", "4")
                        if desc.shapeType == 'Polyline':
                            outputPrinter(message="\t\tDensifying %s" % lyr.name)
                            arcpy.Densify_edit(scratchLayer, "ANGLE", "33 Unknown", "0.33 Unknown", "4")

                        syncLayer(fst, fs, scratchLayer, layerName, lyr.name,lowerCaseFieldNames,showFullResponse)
                        outputPrinter (message="\tComplete")
                        outputPrinter (message="\t")

                    else:
                        outputPrinter (message="\t\t%s does not contain any features, skipping" % lyr.name)
                        outputPrinter (message="\tComplete")
                        outputPrinter (message="\t")
                else:
                    outputPrinter (message="\t%s does not exist" % dataToAppend)
                    outputPrinter (message="\tComplete")
                    outputPrinter (message="\t")


            else:
                outputPrinter(message="\tFeature Service with id %s was not found" % fsId,typeOfMessage='error')
                arcpy.SetParameterAsText(9, "false")
        else:
            outputPrinter(message=fst.message, typeOfMessage="error")
            arcpy.SetParameterAsText(9, "false")
    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),typeOfMessage='error')
        arcpy.SetParameterAsText(9, "false")
    except (common.ArcRestHelperError),e:
        outputPrinter(message=e,typeOfMessage='error')
        arcpy.SetParameterAsText(9, "false")
Esempio n. 16
0
def main(*argv):

    fsId = None
    layerName = None
    dataToAppend = None
    fst = None
    fs = None
    results = None
    fl = None
    existingDef = None
    scratchGDB = None
    scratchLayName = None
    scratchLayer = None
    try:
        arcpy.env.overwriteOutput = True

        proxy_port = None
        proxy_url = None

        securityinfo = {}

        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None

        username = argv[0]
        password = argv[1]
        siteURL = argv[2]

        version = arcpy.GetInstallInfo()['Version']
        if re.search("^10\.[0-2]", version) is not None:
            bReqUserName = True
        else:
            bReqUserName = False

        if bReqUserName and \
           (username == None or username == "#" or str(username).strip() == "" or \
            password == None or password== "#" or password== "*" or str(password).strip() == ""):
            outputPrinter(
                "{0} Requires a username and password".format(version),
                typeOfMessage='error')
            return

        if bReqUserName:
            securityinfo[
                'security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
            securityinfo['username'] = username
            securityinfo['password'] = password
            securityinfo['org_url'] = siteURL

        else:
            securityinfo[
                'security_type'] = 'ArcGIS'  #LDAP, NTLM, OAuth, Portal, PKI

        fsId = argv[3]
        layerName = argv[4]
        dataToAppend = argv[5]
        projection = argv[6]
        lowerCaseFieldNames = argv[7]
        showFullResponse = argv[8]

        scratchGDB = arcpy.env.scratchWorkspace
        scratchLayName = random_string_generator()
        scratchLayer = os.path.join(scratchGDB, scratchLayName)

        if str(lowerCaseFieldNames).upper() == 'TRUE':
            lowerCaseFieldNames = True
        else:
            lowerCaseFieldNames = False

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid:
            fs = fst.GetFeatureService(itemId=fsId, returnURLOnly=False)

            if not fs is None:

                if arcpy.Exists(dataset=dataToAppend) == True:

                    lyr = arcpy.Describe(dataToAppend)
                    result = arcpy.GetCount_management(dataToAppend)
                    count = int(result.getOutput(0))
                    outputPrinter(message="\t\t%s features" % (count))
                    if count > 0:
                        if projection is not None and projection != "#" and \
                                projection.strip() !='' :

                            outputPrinter(message="\t\tProjecting %s" %
                                          (lyr.name))
                            result = arcpy.Project_management(
                                dataToAppend, scratchLayer, projection)
                        else:
                            outputPrinter(
                                message="\t\tCopying %s feature from %s" %
                                (count, lyr.name))
                            arcpy.FeatureClassToFeatureClass_conversion(
                                dataToAppend, scratchGDB, scratchLayName)
                        desc = arcpy.Describe(scratchLayer)
                        if desc.shapeType == 'Polygon':
                            outputPrinter(message="\t\tDensifying %s" %
                                          lyr.name)
                            arcpy.Densify_edit(scratchLayer, "ANGLE",
                                               "33 Unknown", "0.33 Unknown",
                                               "4")
                        if desc.shapeType == 'Polyline':
                            outputPrinter(message="\t\tDensifying %s" %
                                          lyr.name)
                            arcpy.Densify_edit(scratchLayer, "ANGLE",
                                               "33 Unknown", "0.33 Unknown",
                                               "4")

                        syncLayer(fst, fs, scratchLayer, layerName, lyr.name,
                                  lowerCaseFieldNames, showFullResponse)
                        outputPrinter(message="\tComplete")
                        outputPrinter(message="\t")

                    else:
                        outputPrinter(
                            message=
                            "\t\t%s does not contain any features, skipping" %
                            lyr.name)
                        outputPrinter(message="\tComplete")
                        outputPrinter(message="\t")
                else:
                    outputPrinter(message="\t%s does not exist" % dataToAppend)
                    outputPrinter(message="\tComplete")
                    outputPrinter(message="\t")

            else:
                outputPrinter(
                    message="\tFeature Service with id %s was not found" %
                    fsId,
                    typeOfMessage='error')
                arcpy.SetParameterAsText(9, "false")
        else:
            outputPrinter(message=fst.message, typeOfMessage="error")
            arcpy.SetParameterAsText(9, "false")
    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,
                      typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,
                      typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,
                      typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),
                      typeOfMessage='error')
        arcpy.SetParameterAsText(9, "false")
    except (common.ArcRestHelperError), e:
        outputPrinter(message=e, typeOfMessage='error')
        arcpy.SetParameterAsText(9, "false")
Esempio n. 17
0
def main(*argv):

    fsId = None
    layerName = None
    dataToAppend = None
    fst = None
    fs = None
    results = None
    fl = None
    existingDef = None
    try:

        proxy_port = None
        proxy_url = None

        securityinfo = {}
        securityinfo[
            'security_type'] = 'ArcGIS'  #LDAP, NTLM, OAuth, Portal, PKI

        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None

        fsId = argv[0]
        layerName = argv[1]
        dataToAppend = argv[2]
        lowerCaseFieldNames = argv[3]

        if str(lowerCaseFieldNames).upper() == 'TRUE':
            lowerCaseFieldNames = True
        else:
            lowerCaseFieldNames = False
        if arcpy.Exists(dataset=dataToAppend) == False:
            outputPrinter(message="Data layer not found: " + dataToAppend)
        else:
            fst = featureservicetools.featureservicetools(securityinfo)
            if fst.valid:
                outputPrinter(message="Security handler created")

                fs = fst.GetFeatureService(itemId=fsId, returnURLOnly=False)

                if not fs is None:

                    fl = fst.GetLayerFromFeatureService(fs=fs,
                                                        layerName=layerName,
                                                        returnURLOnly=False)
                    if not fl is None:
                        results = fl.addFeatures(
                            fc=dataToAppend,
                            lowerCaseFieldNames=lowerCaseFieldNames)

                        if 'error' in results:
                            outputPrinter(
                                message="Error in response from server:  %s" %
                                results['error'],
                                typeOfMessage='error')
                            arcpy.SetParameterAsText(4, "false")

                        else:
                            if results['addResults'] is not None:
                                outputPrinter(message="%s features added" %
                                              len(results['addResults']))
                            else:
                                outputPrinter(message="0 features added")

                            arcpy.SetParameterAsText(4, "true")

                    else:
                        outputPrinter(
                            message=
                            "Layer %s was not found, please check your credentials and layer name"
                            % layerName,
                            typeOfMessage='error')
                        arcpy.SetParameterAsText(4, "false")
                else:
                    outputPrinter(
                        message="Feature Service with id %s was not found" %
                        fsId,
                        typeOfMessage='error')
                    arcpy.SetParameterAsText(4, "false")
            else:
                outputPrinter(fst.message, typeOfMessage='error')
                arcpy.SetParameterAsText(4, "false")

    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,
                      typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,
                      typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,
                      typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),
                      typeOfMessage='error')
        arcpy.SetParameterAsText(4, "false")
    except (common.ArcRestHelperError), e:
        outputPrinter(message=e, typeOfMessage='error')
        arcpy.SetParameterAsText(4, "false")
Esempio n. 18
0
def main(*argv):
    userName = None
    password = None
    org_url = None
    fsId = None
    layerName = None
    dataToAppend = None
    fst = None
    fs = None
    results = None
    fl = None
    existingDef = None
    try:

        userName = argv[0]
        password = argv[1]
        org_url = argv[2]
        fsId = argv[3]
        layerName = argv[4]
        dataToAppend = argv[5]
        toggleEditCapabilities = argv[6]

        if arcpy.Exists(dataset=dataToAppend) == False:
            outputPrinter(message="Data layer not found: %" % dataToAppend)
        else:
            fst = featureservicetools.featureservicetools(username=userName,
                                                          password=password,
                                                          org_url=org_url,
                                                          token_url=None,
                                                          proxy_url=None,
                                                          proxy_port=None)
            if fst.valid:
                outputPrinter(message="Security handler created")

                fs = fst.GetFeatureService(itemId=fsId, returnURLOnly=False)

                if not fs is None:
                    if str(toggleEditCapabilities).upper() == 'TRUE':
                        existingDef = fst.EnableEditingOnService(url=fs.url)
                    fl = fst.GetLayerFromFeatureService(fs=fs,
                                                        layerName=layerName,
                                                        returnURLOnly=False)
                    if not fl is None:
                        results = fl.addFeatures(fc=dataToAppend)

                        if 'error' in results:
                            outputPrinter(
                                message="Error in response from server: " %
                                results['error'],
                                typeOfMessage='error')
                            arcpy.SetParameterAsText(6, "false")

                        else:
                            outputPrinter(message="%s features added" %
                                          len(results['addResults']))
                            if toggleEditCapabilities == 'True':
                                existingDef = fst.EnableEditingOnService(
                                    url=fs.url, definition=existingDef)
                            arcpy.SetParameterAsText(6, "true")

                    else:
                        outputPrinter(
                            message=
                            "Layer %s was not found, please check your credentials and layer name"
                            % layerName,
                            typeOfMessage='error')
                        arcpy.SetParameterAsText(6, "false")
                else:
                    outputPrinter(
                        message="Feature Service with id %s was not found" %
                        fsId,
                        typeOfMessage='error')
                    arcpy.SetParameterAsText(6, "false")
            else:
                outputPrinter(fst.message, typeOfMessage='error')
                arcpy.SetParameterAsText(6, "false")

    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,
                      typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,
                      typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,
                      typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),
                      typeOfMessage='error')
        arcpy.SetParameterAsText(6, "false")
    except (common.ArcRestHelperError), e:
        outputPrinter(message=e, typeOfMessage='error')
        arcpy.SetParameterAsText(6, "false")
Esempio n. 19
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""#<UserName>
    securityinfo['password'] = ""#<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None


    itemId = ""#<Item ID>
    csvPath = r".\dataToLoad.csv"#<Path with data>

    xCol = "x"
    yCol = "y"
    descriptionCol = "description"
    statusCol = "status"
    priorityCol = "priority"
    assignmentTypeCol = "assignmentType"
    workorderCol = "workOrderId"
    locationCol = "location"
    dateTimeFormat = "%m/%d/%Y %I:%M:%S %p"#1/28/2016 4:59:59 AM
    dueDateCol = "dueDate"
    notesCol = "notes"

    fl = None
    fls = None
    fs = None
    try:
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print (fst.message)
        else:
            fs = fst.GetFeatureService(itemId=itemId,returnURLOnly=False)
            if not fs is None:
                fls = fs.layers
                if len(fls) > 0 :
                    fl = fls[0]
            if fl is None:
                print ("Layer Not Found")
                return
            features = []
            with open(csvPath) as csvfile:
                reader = UnicodeDictReader(csvfile)
                for row in reader:
                    json_string={}
                    json_string['geometry'] = {}
                    if xCol not in row or yCol not in row:
                        print ("X or Y col not found")
                        return
                    json_string['geometry']['x'] = row[xCol]
                    json_string['geometry']['y'] = row[yCol]
                    json_string['attributes'] ={}
                    if descriptionCol is not None:
                        if descriptionCol in row:
                            json_string['attributes']['description'] = row[descriptionCol]
                        else:
                            json_string['attributes']['description'] = descriptionCol
                    if statusCol is not None:
                        if statusCol in row:
                            json_string['attributes']['status'] = row[statusCol]
                        else:
                            json_string['attributes']['status'] = statusCol
                    if notesCol is not None:
                        if notesCol in row:
                            json_string['attributes']['notes'] = row[notesCol]
                        else:
                            json_string['attributes']['notes'] = notesCol
                    if priorityCol is not None:
                        if priorityCol in row:
                            json_string['attributes']['priority'] = row[priorityCol]
                        else:
                            json_string['attributes']['priority'] = priorityCol
                    if assignmentTypeCol is not None:
                        if assignmentTypeCol in row:
                            json_string['attributes']['assignmentType'] = row[assignmentTypeCol]
                        else:
                            json_string['attributes']['assignmentType'] = assignmentTypeCol
                    if workorderCol is not None:
                        if workorderCol in row:
                            json_string['attributes']['workorder'] = row[workorderCol]
                        else:
                            json_string['attributes']['workorder'] = workorderCol
                    if locationCol is not None:
                        if locationCol in row:
                            json_string['attributes']['location'] = row[locationCol]
                        else:
                            json_string['attributes']['location'] = locationCol
                    if dueDateCol is not None:
                        if dueDateCol in row:
                            timeVal = datetime.strptime(row[dueDateCol], dateTimeFormat)
                        else:
                            timeVal = datetime.strptime(dueDateCol, dateTimeFormat)
                        json_string['attributes']['dueDate'] = common.local_time_to_online(dt=timeVal)

                    features.append(Feature(json_string=json_string))
                results = fl.addFeature(features=features)

                if 'error' in results:
                    print ("Error in response from server:  %s" % results['error'])

                else:
                    if results['addResults'] is not None:
                        featSucces = 0
                        for result in results['addResults']:
                            if 'success' in result:
                                if result['success'] == False:
                                    if 'error' in result:
                                        print ("Error info: %s" % (result['error']))
                                else:
                                    featSucces = featSucces + 1

                        print ("%s features added to %s" % (featSucces,fl.name))
                    else:
                        print ("0 features added to %s /n result info %s" % (fl.name,str(results)))

    except (common.ArcRestHelperError),e:
        print ("error in function: %s" % e[0]['function'])
        print ("error on line: %s" % e[0]['line'])
        print ("error in file name: %s" % e[0]['filename'])
        print ("with error message: %s" % e[0]['synerror'])
        if 'arcpyError' in e[0]:
            print ("with arcpy message: %s" % e[0]['arcpyError'])
Esempio n. 20
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""  #<UserName>
    securityinfo['password'] = ""  #<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    itemId = ""  #<Item ID>
    csvPath = r".\dataToLoad.csv"  #<Path with data>

    xCol = "x"
    yCol = "y"
    descriptionCol = "description"
    statusCol = "status"
    priorityCol = "priority"
    assignmentTypeCol = "assignmentType"
    workorderCol = "workOrderId"
    locationCol = "location"
    dateTimeFormat = "%m/%d/%Y %I:%M:%S %p"  #1/28/2016 4:59:59 AM
    dueDateCol = "dueDate"
    notesCol = "notes"

    fl = None
    fls = None
    fs = None
    try:
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print(fst.message)
        else:
            fs = fst.GetFeatureService(itemId=itemId, returnURLOnly=False)
            if not fs is None:
                fls = fs.layers
                if len(fls) > 0:
                    fl = fls[0]
            if fl is None:
                print("Layer Not Found")
                return
            features = []
            with open(csvPath) as csvfile:
                reader = UnicodeDictReader(csvfile)
                for row in reader:
                    json_string = {}
                    json_string['geometry'] = {}
                    if xCol not in row or yCol not in row:
                        print("X or Y col not found")
                        return
                    json_string['geometry']['x'] = row[xCol]
                    json_string['geometry']['y'] = row[yCol]
                    json_string['attributes'] = {}
                    if descriptionCol is not None:
                        if descriptionCol in row:
                            json_string['attributes']['description'] = row[
                                descriptionCol]
                        else:
                            json_string['attributes'][
                                'description'] = descriptionCol
                    if statusCol is not None:
                        if statusCol in row:
                            json_string['attributes']['status'] = row[
                                statusCol]
                        else:
                            json_string['attributes']['status'] = statusCol
                    if notesCol is not None:
                        if notesCol in row:
                            json_string['attributes']['notes'] = row[notesCol]
                        else:
                            json_string['attributes']['notes'] = notesCol
                    if priorityCol is not None:
                        if priorityCol in row:
                            json_string['attributes']['priority'] = row[
                                priorityCol]
                        else:
                            json_string['attributes']['priority'] = priorityCol
                    if assignmentTypeCol is not None:
                        if assignmentTypeCol in row:
                            json_string['attributes']['assignmentType'] = row[
                                assignmentTypeCol]
                        else:
                            json_string['attributes'][
                                'assignmentType'] = assignmentTypeCol
                    if workorderCol is not None:
                        if workorderCol in row:
                            json_string['attributes']['workOrderId'] = row[
                                workorderCol]
                        else:
                            json_string['attributes'][
                                'workOrderId'] = workorderCol
                    if locationCol is not None:
                        if locationCol in row:
                            json_string['attributes']['location'] = row[
                                locationCol]
                        else:
                            json_string['attributes']['location'] = locationCol
                    if dueDateCol is not None:
                        if dueDateCol in row:
                            timeVal = datetime.strptime(
                                row[dueDateCol], dateTimeFormat)
                        else:
                            timeVal = datetime.strptime(
                                dueDateCol, dateTimeFormat)
                        json_string['attributes'][
                            'dueDate'] = common.local_time_to_online(
                                dt=timeVal)

                    features.append(Feature(json_string=json_string))
                results = fl.addFeature(features=features)

                if 'error' in results:
                    print("Error in response from server:  %s" %
                          results['error'])

                else:
                    if results['addResults'] is not None:
                        featSucces = 0
                        for result in results['addResults']:
                            if 'success' in result:
                                if result['success'] == False:
                                    if 'error' in result:
                                        print("Error info: %s" %
                                              (result['error']))
                                else:
                                    featSucces = featSucces + 1

                        print("%s features added to %s" %
                              (featSucces, fl.name))
                    else:
                        print("0 features added to %s /n result info %s" %
                              (fl.name, str(results)))

    except (common.ArcRestHelperError), e:
        print("error in function: %s" % e[0]['function'])
        print("error on line: %s" % e[0]['line'])
        print("error in file name: %s" % e[0]['filename'])
        print("with error message: %s" % e[0]['synerror'])
        if 'arcpyError' in e[0]:
            print("with arcpy message: %s" % e[0]['arcpyError'])
Esempio n. 21
0
def main(*argv):

    fsId = None
    groupLayer = None
    layerMap = None
    matchEntireName = None
    projection = None
    scratchGDB = None
    scratchLayer = None
    fst = None
    rows = None
    fieldList = None
    layerToServiceLayer = None
    matches = False
    showFullResponse = False

    try:
        arcpy.env.overwriteOutput = True

        proxy_port = None
        proxy_url = None

        securityinfo = {}

        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None

        username = argv[0]
        password = argv[1]
        siteURL = argv[2]

        version = arcpy.GetInstallInfo()['Version']
        if re.search("^10\.[0-2]", version) is not None:
            bReqUserName = True
        else:
            bReqUserName = False

        if bReqUserName and \
            (username == None or username == "#" or str(username).strip() == "" or \
             password == None or password== "#" or password== "*" or str(password).strip() == ""):
            outputPrinter ("{0} Requires a username and password".format(version), typeOfMessage='error')
            return

        if bReqUserName:
            securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
            securityinfo['username'] = username
            securityinfo['password'] = password
            securityinfo['org_url'] = siteURL

        else:
            securityinfo['security_type'] = 'ArcGIS'#LDAP, NTLM, OAuth, Portal, PKI

        groupLayer = argv[3]
        fsId = argv[4]
        layerMap = argv[5]
        matchEntireName = argv[6]
        projection = argv[7]
        lowerCaseFieldNames =argv[8]
        showFullResponse =argv[9]

        if str(lowerCaseFieldNames).upper() == 'TRUE':
            lowerCaseFieldNames = True
        else:
            lowerCaseFieldNames = False
        if projection is not None and projection != '#' and projection != '':
            #outputPrinter(message="Projecting %s" % str(projection))
            pass
        else:
            projection = None
            #outputPrinter(message="No Projection defined")
        arcpy.SetParameterAsText(10, "true")

        scratchGDB = arcpy.env.scratchWorkspace
        scratchLayName = "tempAppGrpFS"
        scratchLayer = os.path.join(scratchGDB,scratchLayName)

        groupLayer = arcpy.mapping.Layer(groupLayer)
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid:
            #outputPrinter(message="Security handler created")

            fs = fst.GetFeatureService(itemId=fsId,returnURLOnly=False)

            if not fs is None:
                #Get a cursor to the layer map recordset
                rows = arcpy.SearchCursor(layerMap)

                #Get the fields
                fieldList = arcpy.ListFields(layerMap)

                #initialize the Translation Dictionary
                layerToServiceLayer = {}

                #Loop through each input row and add it to the conversion dict
                for row in rows:
                    layerToServiceLayer[row.getValue(fieldList[1].name)] = row.getValue(fieldList[2].name)
                    del row
                if groupLayer.isGroupLayer:
                    for lyr in groupLayer:
                        for key, value in layerToServiceLayer.items():
                            if str(matchEntireName).lower() =='true' and key == lyr.name:
                                matches = True
                            elif str(matchEntireName).lower() =='false' and str(lyr.name).startswith(key):
                                matches = True
                            else:
                                matches = False
                            if matches:
                                #arcpy.env.workspace = lyr.workspacePath
                                if arcpy.Exists(dataset=lyr) == True:
                                    outputPrinter(message="\tProcessing %s" % (lyr.name))
                                    result =  arcpy.GetCount_management(lyr.name)
                                    count = int(result.getOutput(0))
                                    outputPrinter(message="\t\t%s features" % (count))
                                    if count > 0:
                                        layerNameFull = groupLayer.name + '\\' + lyr.name

                                        if projection is not None and projection != "#" and \
                                                projection.strip() !='' :
                                            outputPrinter(message="\t\tProjecting %s" % (lyr.name))
                                            result = arcpy.Project_management(layerNameFull,
                                                                    scratchLayer,
                                                                    projection)


                                        else:
                                            outputPrinter(message="\t\tCopying %s feature from %s" % (count,lyr.name))
                                            arcpy.FeatureClassToFeatureClass_conversion(layerNameFull,scratchGDB,scratchLayName)

                                        desc = arcpy.Describe(scratchLayer)
                                        if desc.shapeType == 'Polygon':
                                            outputPrinter(message="\t\tDensifying %s" % lyr.name)
                                            arcpy.Densify_edit(scratchLayer, "ANGLE", "33 Unknown", "0.33 Unknown", "4")
                                        if desc.shapeType == 'Polyline':
                                            outputPrinter(message="\t\tDensifying %s" % lyr.name)
                                            arcpy.Densify_edit(scratchLayer, "ANGLE", "33 Unknown", "0.33 Unknown", "4")
                                        syncLayer(fst, fs, scratchLayer, value, lyr.name,lowerCaseFieldNames,showFullResponse)
                                        outputPrinter (message="\tComplete")
                                        outputPrinter (message="\t")

                                    else:
                                        outputPrinter (message="\t\t%s does not contain any features, skipping" % lyr.name)
                                        outputPrinter (message="\tComplete")
                                        outputPrinter (message="\t")
                                else:
                                    outputPrinter (message="\t%s does not exist, skipping" % lyr.name)
                                    outputPrinter (message="\tComplete")
                                    outputPrinter (message="\t")
                                break

                else:
                    outputPrinter (message="Group layer is not a group layer", typeOfMessage='error')
            else:
                outputPrinter(message="Feature Service with id %s was not found" % fsId, typeOfMessage='error')
                arcpy.SetParameterAsText(10, "false")
        else:
            outputPrinter(fst.message,typeOfMessage='error')
            arcpy.SetParameterAsText(10, "false")



    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),typeOfMessage='error')
        arcpy.SetParameterAsText(10, "false")
    except (common.ArcRestHelperError),e:
        outputPrinter(message=e,typeOfMessage='error')
        arcpy.SetParameterAsText(10, "false")
Esempio n. 22
0
def main(*argv):

    proxy_port = None
    proxy_url = None

    layerNames = None
    layerName = None
    layerName = None
    sql = None
    fst = None
    fs = None
    results = None
    fl = None
    existingDef = None
    try:

        proxy_port = None
        proxy_url = None

        securityinfo = {}

        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None

        username = argv[0]
        password = argv[1]
        siteURL = argv[2]

        version = arcpy.GetInstallInfo()['Version']
        if re.search("^10\.[0-2]", version) is not None:
            bReqUserName = True
        else:
            bReqUserName = False

        if bReqUserName and \
           (username == None or username == "#" or str(username).strip() == "" or \
            password == None or password== "#" or password== "*" or str(password).strip() == ""):
            outputPrinter(
                "{0} Requires a username and password".format(version),
                typeOfMessage='error')
            return

        if bReqUserName:
            securityinfo[
                'security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
            securityinfo['username'] = username
            securityinfo['password'] = password
            securityinfo['org_url'] = siteURL

        else:
            securityinfo[
                'security_type'] = 'ArcGIS'  #LDAP, NTLM, OAuth, Portal, PKI

        fsId = argv[3]
        layerNames = argv[4]
        sql = argv[5]
        showFullResponse = argv[6]

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid:

            fs = fst.GetFeatureService(itemId=fsId, returnURLOnly=False)
            if not fs is None:
                for layerName in layerNames.split(','):
                    layerName = layerName.strip()
                    fl = fst.GetLayerFromFeatureService(fs=fs,
                                                        layerName=layerName,
                                                        returnURLOnly=False)
                    if not fl is None:
                        outputPrinter(
                            message=
                            "\tAttempting to delete features matching this query: %s "
                            % sql)
                        results = fl.deleteFeatures(where=sql)

                        if str(showFullResponse).lower() == 'true':
                            outputPrinter(message="\t\tResponse:  %s" %
                                          results)
                        if 'error' in results:
                            outputPrinter(
                                message="\t\tError in response from server:  %s"
                                % results['error'],
                                typeOfMessage='error')
                            arcpy.SetParameterAsText(7, "false")
                        else:
                            if results['deleteResults'] is not None:
                                featSucces = 0
                                for result in results['deleteResults']:
                                    if 'success' in result:
                                        if result['success'] == False:
                                            if 'error' in result:

                                                outputPrinter(
                                                    message=
                                                    "\t\t\tError info: %s" %
                                                    (result['error']))
                                        else:
                                            featSucces = featSucces + 1

                                outputPrinter(
                                    message="\t\t%s features deleted from %s" %
                                    (featSucces, layerName))
                            else:
                                outputPrinter(
                                    message=
                                    "\t\t0 features deleted from %s /n result info %s"
                                    % (layerName, str(results)))
                    else:
                        outputPrinter(
                            message=
                            "\t\tLayer %s was not found, please check your credentials and layer name"
                            % layerName,
                            typeOfMessage='error')
                        arcpy.SetParameterAsText(7, "false")
                        break
            else:
                outputPrinter(
                    message="\tFeature Service with id %s was not found" %
                    fsId,
                    typeOfMessage='error')
                arcpy.SetParameterAsText(7, "false")

        else:
            outputPrinter(message=fst.message, typeOfMessage='error')
            arcpy.SetParameterAsText(7, "false")

    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,
                      typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,
                      typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,
                      typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),
                      typeOfMessage='error')
        arcpy.SetParameterAsText(7, "false")
    except (common.ArcRestHelperError) as e:
        outputPrinter(message=e, typeOfMessage='error')
        arcpy.SetParameterAsText(7, "false")
    except:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,
                      typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,
                      typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,
                      typeOfMessage='error')
        arcpy.SetParameterAsText(7, "false")
    finally:
        existingDef = None
        fsId = None
        layerNames = None
        layerName = None
        sql = None
        fst = None
        fs = None
        results = None
        fl = None

        del existingDef

        del fsId
        del layerNames
        del layerName
        del sql
        del fst
        del fs
        del results
        del fl

        gc.collect()
def main(*argv):

    layerNames = None
    layerName = None
    layerName = None
    sql = None
    fst = None
    fs = None
    results = None
    fl = None
    existingDef = None
    try:

     
        fsId = argv[0]
        layerNames = argv[1]
        sql = argv[2]
        toggleEditCapabilities = argv[3]

        fst = featureservicetools.featureservicetools(proxy_url=None,
                                                      proxy_port=None,
                                                      use_arcgis_creds=True)
        if fst.valid:

            fs = fst.GetFeatureService(itemId=fsId,returnURLOnly=False)

            outputPrinter("Logged in successful")
            if not fs is None:
                if str(toggleEditCapabilities).upper() == 'TRUE':
                    existingDef = fst.EnableEditingOnService(url=fs.url)
                for layerName in layerNames.split(','):
                    fl = fst.GetLayerFromFeatureService(fs=fs,layerName=layerName,returnURLOnly=False)
                    if not fl is None:
                        outputPrinter(message="Attempting to delete features matching this query: %s " % sql)
                        results = fl.deleteFeatures(where=sql)

                        if 'error' in results:
                            outputPrinter(message="Error in response from server: " % results['error'],typeOfMessage='error')
                            arcpy.SetParameterAsText(4, "false")
                            break

                        else:
                            outputPrinter (message="%s features deleted" % len(results['deleteResults']) )
                            if toggleEditCapabilities:
                                existingDef = fst.EnableEditingOnService(url=fs.url)
                            arcpy.SetParameterAsText(4, "true")
                    else:
                        outputPrinter(message="Layer %s was not found, please check your credentials and layer name" % layerName,typeOfMessage='error')
                        arcpy.SetParameterAsText(4, "false")
                        break
            else:
                outputPrinter(message="Feature Service with id %s was not found" % fsId,typeOfMessage='error')
                arcpy.SetParameterAsText(4, "false")

        else:
            outputPrinter(message="Security handler not created, exiting")
            arcpy.SetParameterAsText(4, "false")

    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),typeOfMessage='error')
        arcpy.SetParameterAsText(4, "false")
    except (common.ArcRestHelperError),e:
        outputPrinter(message=e,typeOfMessage='error')
        arcpy.SetParameterAsText(4, "false")
Esempio n. 24
0
def main():

    fsId = None
    groupLayer = None
    layerMap = None
    matchEntireName = None
    projection = None
    scratchGDB = None
    scratchLayer = None
    fst = None
    rows = None
    fieldList = None
    layerToServiceLayer = None
    matches = False
    try:

        proxy_port = None
        proxy_url = None

        securityinfo = {}
        securityinfo['security_type'] = 'ArcGIS'#LDAP, NTLM, OAuth, Portal, PKI

        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None

        fsId = arcpy.GetParameterAsText(1)
        groupLayer = arcpy.GetParameterAsText(0)
        layerMap = arcpy.GetParameterAsText(2)
        matchEntireName = arcpy.GetParameterAsText(3)
        projection = arcpy.GetParameterAsText(4)
        if projection is not None and projection != '#' and projection != '':
            #outputPrinter(message="Projecting %s" % str(projection))
            pass
        else:
            projection = None
            #outputPrinter(message="No Projection defined")
        arcpy.SetParameterAsText(5, "true")

        scratchGDB = arcpy.env.scratchWorkspace
        scratchLayName = "tempAppGrpFS"
        scratchLayer = os.path.join(scratchGDB,scratchLayName)

        groupLayer = arcpy.mapping.Layer(groupLayer)
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid:
            #outputPrinter(message="Security handler created")

            fs = fst.GetFeatureService(itemId=fsId,returnURLOnly=False)

            if not fs is None:
                #Get a cursor to the layer map recordset
                rows = arcpy.SearchCursor(layerMap)

                #Get the fields
                fieldList = arcpy.ListFields(layerMap)

                #initialize the Translation Dictionary
                layerToServiceLayer = {}

                #Loop through each input row and add it to the conversion dict
                for row in rows:
                    layerToServiceLayer[row.getValue(fieldList[1].name)] = row.getValue(fieldList[2].name)
                    del row
                if groupLayer.isGroupLayer:
                    for lyr in groupLayer:
                        for key, value in layerToServiceLayer.iteritems():
                            if matchEntireName =='true' and key == lyr.name:
                                matches = True
                            elif matchEntireName =='false' and key in lyr.name:
                                matches = True
                            else:
                                matches = False
                            if matches:
                                if arcpy.Exists(lyr.name) == True:
                                    result =  arcpy.GetCount_management(lyr.name)
                                    count = int(result.getOutput(0))
                                    if count > 0:
                                        layerNameFull = groupLayer.name + '\\' + lyr.name

                                        if projection is not None:
                                            outputPrinter(message="Projecting %s" % lyr.name)
                                            arcpy.Project_management(layerNameFull,
                                                                    scratchLayer,
                                                                    projection,
                                                                    "",
                                                                    "",
                                                                    "NO_PRESERVE_SHAPE",
                                                                    "")

                                        else:
                                            outputPrinter(message="Copying %s" % lyr.name)
                                            arcpy.FeatureClassToFeatureClass_conversion(layerNameFull,scratchGDB,scratchLayName)

                                        desc = arcpy.Describe(scratchLayer)
                                        if desc.shapeType == 'Polygon':
                                            outputPrinter(message="Densifying %s" % lyr.name)
                                            arcpy.Densify_edit(scratchLayer, "ANGLE", "33 Unknown", "0.33 Unknown", "4")
                                        syncLayer(fst, fs, scratchLayer, value, lyr.name)

                                    else:
                                        outputPrinter (message="%s does not contain any features, skipping" % lyr.name)
                                else:
                                    outputPrinter (message="%s does not exist, skipping" % lyr.name)
                                break

                else:
                    outputPrinter (message="Group layer is not a group layer", typeOfMessage='error')
            else:
                outputPrinter(message="Feature Service with id %s was not found" % fsId, typeOfMessage='error')
                arcpy.SetParameterAsText(5, "false")
        else:
            outputPrinter(fst.message,typeOfMessage='error')
            arcpy.SetParameterAsText(5, "false")



    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),typeOfMessage='error')
        arcpy.SetParameterAsText(5, "false")
    except (common.ArcRestHelperError),e:
        outputPrinter(message=e,typeOfMessage='error')
        arcpy.SetParameterAsText(5, "false")
def main():
    arcpy.env.overwriteOutput = True
    fsId = None
    pointLayer = None
    pointLayerProj = None
    projection = None
    scratchGDB = None
    scratchLayer = None
    scratchLayName = None
    fst = None
    rows = None
    features = None
    sr_web = None
    priority = None
    status = None
    description = None
    assignmentType = None
    workOrderId = None
    json_string = None
    try:

        proxy_port = None
        proxy_url = None

        securityinfo = {}
        securityinfo["security_type"] = "ArcGIS"  # LDAP, NTLM, OAuth, Portal, PKI

        securityinfo["proxy_url"] = proxy_url
        securityinfo["proxy_port"] = proxy_port
        securityinfo["referer_url"] = None
        securityinfo["token_url"] = None
        securityinfo["certificatefile"] = None
        securityinfo["keyfile"] = None
        securityinfo["client_id"] = None
        securityinfo["secret_id"] = None

        pointLayer = arcpy.GetParameterAsText(0)
        fsId = arcpy.GetParameterAsText(1)
        priority = arcpy.GetParameterAsText(2)
        status = arcpy.GetParameterAsText(3)
        description = arcpy.GetParameterAsText(4)
        assignmentType = arcpy.GetParameterAsText(5)
        workOrderId = arcpy.GetParameterAsText(6)
        location = arcpy.GetParameterAsText(7)
        locationField = arcpy.GetParameterAsText(8)
        showFullResponse = arcpy.GetParameterAsText(9)

        sr_web = arcpy.SpatialReference(102100)
        scratchGDB = arcpy.env.scratchWorkspace
        scratchLayName = "tempAppGrpFS"
        scratchLayer = os.path.join(scratchGDB, scratchLayName)
        if arcpy.Exists(pointLayer):

            features = []
            fst = featureservicetools.featureservicetools(securityinfo)
            if fst is not None and fst.valid:

                fs = fst.GetFeatureService(itemId=fsId, returnURLOnly=False)
                if not fs is None:
                    fls = fs.layers
                    if len(fls) > 0:
                        fl = fls[0]
                        pointLayerProj = arcpy.Project_management(
                            pointLayer, scratchLayer, sr_web, "", "", "PRESERVE_SHAPE", ""
                        )

                        field_names = ["SHAPE@X", "SHAPE@Y", workOrderId]
                        if locationField is not None and locationField != "#" and locationField != "":
                            field_names.append(locationField)
                        # Get a cursor to the point layer
                        rows = arcpy.da.SearchCursor(in_table=pointLayerProj, field_names=field_names)
                        for row in rows:
                            json_string = {}
                            json_string["geometry"] = {}
                            json_string["geometry"]["x"] = row[0]
                            json_string["geometry"]["y"] = row[1]
                            json_string["attributes"] = {}
                            json_string["attributes"]["description"] = description
                            json_string["attributes"]["status"] = status
                            # json_string['attributes']['notes'] = ''
                            json_string["attributes"]["priority"] = priority
                            json_string["attributes"]["assignmentType"] = assignmentType
                            json_string["attributes"]["workOrderId"] = row[2]
                            if locationField is not None and locationField != "#" and locationField != "":
                                json_string["attributes"]["location"] = location + ": " + row[3]
                            else:
                                json_string["attributes"]["location"] = location

                            features.append(Feature(json_string=json_string))

                        results = fl.addFeature(features=features)
                        if str(showFullResponse).lower() == "true":
                            outputPrinter(message="\t\tResponse:  %s" % results)
                        else:
                            if "error" in results:
                                outputPrinter(
                                    message="\t\tError in response from server:  %s" % results["error"],
                                    typeOfMessage="error",
                                )
                                arcpy.SetParameterAsText(8, "false")
                            else:
                                if results["addResults"] is not None:
                                    featSucces = 0
                                    for result in results["addResults"]:
                                        if "success" in result:
                                            if result["success"] == False:
                                                if "error" in result:
                                                    outputPrinter(message="\t\t\tError info: %s" % (result["error"]))
                                            else:
                                                featSucces = featSucces + 1

                                    outputPrinter(message="\t\t%s features added to %s" % (featSucces, fl.name))
                                else:
                                    outputPrinter(
                                        message="\t\t0 features added to %s /n result info %s" % (fl.name, str(results))
                                    )

                        arcpy.SetParameterAsText(8, "true")
                    else:
                        outputPrinter(
                            message="Assignment feature service not found in item with ID: " % fsId,
                            typeOfMessage="error",
                        )
                        arcpy.SetParameterAsText(8, "false")
                else:
                    outputPrinter(message="Feature Service with id %s was not found" % fsId, typeOfMessage="error")
                    arcpy.SetParameterAsText(8, "false")
            else:
                outputPrinter(fst.message, typeOfMessage="error")
                arcpy.SetParameterAsText(8, "false")
        else:
            outputPrinter(message="Point layer does not exist", typeOfMessage="error")
            arcpy.SetParameterAsText(8, "false")

    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line, typeOfMessage="error")
        outputPrinter(message="error in file name: %s" % filename, typeOfMessage="error")
        outputPrinter(message="with error message: %s" % synerror, typeOfMessage="error")
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2), typeOfMessage="error")
        arcpy.SetParameterAsText(8, "false")
    except (common.ArcRestHelperError), e:
        outputPrinter(message=e, typeOfMessage="error")
        arcpy.SetParameterAsText(8, "false")
Esempio n. 26
0
def main():

    fsId = None
    groupLayer = None
    layerMap = None
    matchEntireName = None
    projection = None
    scratchGDB = None
    scratchLayer = None
    fst = None
    rows = None
    fieldList = None
    layerToServiceLayer = None
    matches = False
    try:

        proxy_port = None
        proxy_url = None

        securityinfo = {}
        securityinfo[
            'security_type'] = 'ArcGIS'  #LDAP, NTLM, OAuth, Portal, PKI

        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None

        fsId = arcpy.GetParameterAsText(1)
        groupLayer = arcpy.GetParameterAsText(0)
        layerMap = arcpy.GetParameterAsText(2)
        matchEntireName = arcpy.GetParameterAsText(3)
        projection = arcpy.GetParameterAsText(4)
        if projection is not None and projection != '#' and projection != '':
            #outputPrinter(message="Projecting %s" % str(projection))
            pass
        else:
            projection = None
            #outputPrinter(message="No Projection defined")
        arcpy.SetParameterAsText(5, "true")

        scratchGDB = arcpy.env.scratchWorkspace
        scratchLayName = "tempAppGrpFS"
        scratchLayer = os.path.join(scratchGDB, scratchLayName)

        groupLayer = arcpy.mapping.Layer(groupLayer)
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid:
            #outputPrinter(message="Security handler created")

            fs = fst.GetFeatureService(itemId=fsId, returnURLOnly=False)

            if not fs is None:
                #Get a cursor to the layer map recordset
                rows = arcpy.SearchCursor(layerMap)

                #Get the fields
                fieldList = arcpy.ListFields(layerMap)

                #initialize the Translation Dictionary
                layerToServiceLayer = {}

                #Loop through each input row and add it to the conversion dict
                for row in rows:
                    layerToServiceLayer[row.getValue(
                        fieldList[1].name)] = row.getValue(fieldList[2].name)
                    del row
                if groupLayer.isGroupLayer:
                    for lyr in groupLayer:
                        for key, value in layerToServiceLayer.iteritems():
                            if matchEntireName == 'true' and key == lyr.name:
                                matches = True
                            elif matchEntireName == 'false' and key in lyr.name:
                                matches = True
                            else:
                                matches = False
                            if matches:
                                if arcpy.Exists(lyr.name) == True:
                                    result = arcpy.GetCount_management(
                                        lyr.name)
                                    count = int(result.getOutput(0))
                                    if count > 0:
                                        layerNameFull = groupLayer.name + '\\' + lyr.name

                                        if projection is not None:
                                            outputPrinter(
                                                message="Projecting %s" %
                                                lyr.name)
                                            arcpy.Project_management(
                                                layerNameFull, scratchLayer,
                                                projection, "", "",
                                                "NO_PRESERVE_SHAPE", "")

                                        else:
                                            outputPrinter(
                                                message="Copying %s" %
                                                lyr.name)
                                            arcpy.FeatureClassToFeatureClass_conversion(
                                                layerNameFull, scratchGDB,
                                                scratchLayName)

                                        desc = arcpy.Describe(scratchLayer)
                                        if desc.shapeType == 'Polygon':
                                            outputPrinter(
                                                message="Densifying %s" %
                                                lyr.name)
                                            arcpy.Densify_edit(
                                                scratchLayer, "ANGLE",
                                                "33 Unknown", "0.33 Unknown",
                                                "4")
                                        syncLayer(fst, fs, scratchLayer, value,
                                                  lyr.name)

                                    else:
                                        outputPrinter(
                                            message=
                                            "%s does not contain any features, skipping"
                                            % lyr.name)
                                else:
                                    outputPrinter(
                                        message="%s does not exist, skipping" %
                                        lyr.name)
                                break

                else:
                    outputPrinter(message="Group layer is not a group layer",
                                  typeOfMessage='error')
            else:
                outputPrinter(
                    message="Feature Service with id %s was not found" % fsId,
                    typeOfMessage='error')
                arcpy.SetParameterAsText(5, "false")
        else:
            outputPrinter(fst.message, typeOfMessage='error')
            arcpy.SetParameterAsText(5, "false")

    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,
                      typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,
                      typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,
                      typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),
                      typeOfMessage='error')
        arcpy.SetParameterAsText(5, "false")
    except (common.ArcRestHelperError), e:
        outputPrinter(message=e, typeOfMessage='error')
        arcpy.SetParameterAsText(5, "false")
Esempio n. 27
0
def main():
    arcpy.env.overwriteOutput = True
    fsId = None
    pointLayer = None
    pointLayerProj = None
    projection = None
    scratchGDB = None
    scratchLayer = None
    scratchLayName = None
    fst = None
    rows = None
    features = None
    sr_web = None
    priority = None
    status = None
    description = None
    assignmentType = None
    workOrderId = None
    json_string = None
    try:

        proxy_port = None
        proxy_url = None

        securityinfo = {}
        securityinfo[
            'security_type'] = 'ArcGIS'  #LDAP, NTLM, OAuth, Portal, PKI

        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None

        pointLayer = arcpy.GetParameterAsText(0)
        fsId = arcpy.GetParameterAsText(1)
        priority = arcpy.GetParameterAsText(2)
        status = arcpy.GetParameterAsText(3)
        description = arcpy.GetParameterAsText(4)
        assignmentType = arcpy.GetParameterAsText(5)
        workOrderId = arcpy.GetParameterAsText(6)
        location = arcpy.GetParameterAsText(7)
        locationField = arcpy.GetParameterAsText(8)
        showFullResponse = arcpy.GetParameterAsText(9)

        sr_web = arcpy.SpatialReference(102100)
        scratchGDB = arcpy.env.scratchWorkspace
        scratchLayName = "tempAppGrpFS"
        scratchLayer = os.path.join(scratchGDB, scratchLayName)
        if arcpy.Exists(pointLayer):

            features = []
            fst = featureservicetools.featureservicetools(securityinfo)
            if fst is not None and fst.valid:

                fs = fst.GetFeatureService(itemId=fsId, returnURLOnly=False)
                if not fs is None:
                    fls = fs.layers
                    if len(fls) > 0:
                        fl = fls[0]
                        pointLayerProj = arcpy.Project_management(
                            pointLayer, scratchLayer, sr_web, "", "",
                            "PRESERVE_SHAPE", "")

                        field_names = ["SHAPE@X", "SHAPE@Y", workOrderId]
                        if locationField is not None and locationField != '#' and locationField != '':
                            field_names.append(locationField)
                        #Get a cursor to the point layer
                        rows = arcpy.da.SearchCursor(in_table=pointLayerProj,
                                                     field_names=field_names)
                        for row in rows:
                            json_string = {}
                            json_string['geometry'] = {}
                            json_string['geometry']['x'] = row[0]
                            json_string['geometry']['y'] = row[1]
                            json_string['attributes'] = {}
                            json_string['attributes'][
                                'description'] = description
                            json_string['attributes']['status'] = status
                            #json_string['attributes']['notes'] = ''
                            json_string['attributes']['priority'] = priority
                            json_string['attributes'][
                                'assignmentType'] = assignmentType
                            json_string['attributes']['workOrderId'] = row[2]
                            if locationField is not None and locationField != '#' and locationField != '':
                                json_string['attributes'][
                                    'location'] = location + ": " + row[3]
                            else:
                                json_string['attributes'][
                                    'location'] = location

                            features.append(Feature(json_string=json_string))

                        results = fl.addFeature(features=features)
                        if str(showFullResponse).lower() == 'true':
                            outputPrinter(message="\t\tResponse:  %s" %
                                          results)
                        else:
                            if 'error' in results:
                                outputPrinter(
                                    message=
                                    "\t\tError in response from server:  %s" %
                                    results['error'],
                                    typeOfMessage='error')
                                arcpy.SetParameterAsText(8, "false")
                            else:
                                if results['addResults'] is not None:
                                    featSucces = 0
                                    for result in results['addResults']:
                                        if 'success' in result:
                                            if result['success'] == False:
                                                if 'error' in result:
                                                    outputPrinter(
                                                        message=
                                                        "\t\t\tError info: %s"
                                                        % (result['error']))
                                            else:
                                                featSucces = featSucces + 1

                                    outputPrinter(
                                        message="\t\t%s features added to %s" %
                                        (featSucces, fl.name))
                                else:
                                    outputPrinter(
                                        message=
                                        "\t\t0 features added to %s /n result info %s"
                                        % (fl.name, str(results)))

                        arcpy.SetParameterAsText(8, "true")
                    else:
                        outputPrinter(
                            message=
                            "Assignment feature service not found in item with ID: "
                            % fsId,
                            typeOfMessage='error')
                        arcpy.SetParameterAsText(8, "false")
                else:
                    outputPrinter(
                        message="Feature Service with id %s was not found" %
                        fsId,
                        typeOfMessage='error')
                    arcpy.SetParameterAsText(8, "false")
            else:
                outputPrinter(fst.message, typeOfMessage='error')
                arcpy.SetParameterAsText(8, "false")
        else:
            outputPrinter(message="Point layer does not exist",
                          typeOfMessage='error')
            arcpy.SetParameterAsText(8, "false")

    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,
                      typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,
                      typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,
                      typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),
                      typeOfMessage='error')
        arcpy.SetParameterAsText(8, "false")
    except (common.ArcRestHelperError), e:
        outputPrinter(message=e, typeOfMessage='error')
        arcpy.SetParameterAsText(8, "false")
Esempio n. 28
0
def main(*argv):

    proxy_port = None
    proxy_url = None

    layerNames = None
    layerName = None
    layerName = None
    sql = None
    fst = None
    fs = None
    results = None
    fl = None
    existingDef = None
    try:


        proxy_port = None
        proxy_url = None

        securityinfo = {}

        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None

        username = argv[0]
        password = argv[1]
        siteURL = argv[2]

        version = arcpy.GetInstallInfo()['Version']
        if re.search("^10\.[0-2]", version) is not None:
            bReqUserName = True
        else:
            bReqUserName = False

        if bReqUserName and \
           (username == None or username == "#" or str(username).strip() == "" or \
            password == None or password== "#" or password== "*" or str(password).strip() == ""):
            outputPrinter ("{0} Requires a username and password".format(version), typeOfMessage='error')
            return

        if bReqUserName:
            securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
            securityinfo['username'] = username
            securityinfo['password'] = password
            securityinfo['org_url'] = siteURL

        else:
            securityinfo['security_type'] = 'ArcGIS'#LDAP, NTLM, OAuth, Portal, PKI

        fsId = argv[3]
        layerNames = argv[4]
        sql = argv[5]
        showFullResponse = argv[6]

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid:

            fs = fst.GetFeatureService(itemId=fsId,returnURLOnly=False)
            if not fs is None:
                for layerName in layerNames.split(','):
                    layerName = layerName.strip()
                    fl = fst.GetLayerFromFeatureService(fs=fs,layerName=layerName,returnURLOnly=False)
                    if not fl is None:
                        outputPrinter(message="\tAttempting to delete features matching this query: %s " % sql)
                        results = fl.deleteFeatures(where=sql)

                        if str(showFullResponse).lower() =='true':
                            outputPrinter(message="\t\tResponse:  %s" % results)
                        if 'error' in results:
                            outputPrinter(message="\t\tError in response from server:  %s" % results['error'],typeOfMessage='error')
                            arcpy.SetParameterAsText(7, "false")
                        else:
                            if results['deleteResults'] is not None:
                                featSucces = 0
                                for result in results['deleteResults']:
                                    if 'success' in result:
                                        if result['success'] == False:
                                            if 'error' in result:

                                                outputPrinter (message="\t\t\tError info: %s" % (result['error']) )
                                        else:
                                            featSucces = featSucces + 1

                                outputPrinter (message="\t\t%s features deleted from %s" % (featSucces,layerName) )
                            else:
                                outputPrinter (message="\t\t0 features deleted from %s /n result info %s" % (layerName,str(results)))
                    else:
                        outputPrinter(message="\t\tLayer %s was not found, please check your credentials and layer name"    % layerName,typeOfMessage='error')
                        arcpy.SetParameterAsText(7, "false")
                        break
            else:
                outputPrinter(message="\tFeature Service with id %s was not found" % fsId, typeOfMessage='error')
                arcpy.SetParameterAsText(7, "false")

        else:
            outputPrinter(message=fst.message, typeOfMessage='error')
            arcpy.SetParameterAsText(7, "false")

    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),typeOfMessage='error')
        arcpy.SetParameterAsText(7, "false")
    except (common.ArcRestHelperError),e:
        outputPrinter(message=e,typeOfMessage='error')
        arcpy.SetParameterAsText(7, "false")
Esempio n. 29
0
def main(*argv):
    userName = None
    password = None
    org_url = None
    layerNames = None
    layerName = None
    layerName = None
    sql = None
    fst = None
    fs = None
    results = None
    fl = None
    existingDef = None
    try:

        proxy_port = None
        proxy_url = None    

        securityinfo = {}
        securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
        securityinfo['username'] = argv[0]
        securityinfo['password'] = argv[1]
        securityinfo['org_url'] = argv[2]
        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None   
        
        fsId = argv[3]
        layerNames = argv[4]
        sql = argv[5]
        toggleEditCapabilities = argv[6]

        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid:

            fs = fst.GetFeatureService(itemId=fsId,returnURLOnly=False)

            outputPrinter("Logged in successful")
            if not fs is None:
                if str(toggleEditCapabilities).upper() == 'TRUE':
                    existingDef = fst.EnableEditingOnService(url=fs.url)
                for layerName in layerNames.split(','):
                    fl = fst.GetLayerFromFeatureService(fs=fs,layerName=layerName,returnURLOnly=False)
                    if not fl is None:
                        outputPrinter(message="Attempting to delete features matching this query: %s " % sql)
                        results = fl.deleteFeatures(where=sql)

                        if 'error' in results:
                            outputPrinter(message="Error in response from server: " % results['error'],typeOfMessage='error')
                            arcpy.SetParameterAsText(7, "false")
                            break

                        else:
                            outputPrinter (message="%s features deleted" % len(results['deleteResults']) )
                            if toggleEditCapabilities:
                                existingDef = fst.EnableEditingOnService(url=fs.url)
                            arcpy.SetParameterAsText(7, "true")
                    else:
                        outputPrinter(message="Layer %s was not found, please check your credentials and layer name" % layerName,typeOfMessage='error')
                        arcpy.SetParameterAsText(7, "false")
                        break
            else:
                outputPrinter(message="Feature Service with id %s was not found" % fsId,typeOfMessage='error')
                arcpy.SetParameterAsText(7, "false")

        else:
            outputPrinter(message="Security handler not created, exiting")
            arcpy.SetParameterAsText(7, "false")

    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),typeOfMessage='error')
        arcpy.SetParameterAsText(7, "false")
    except (common.ArcRestHelperError),e:
        outputPrinter(message=e,typeOfMessage='error')
        arcpy.SetParameterAsText(7, "false")
Esempio n. 30
0
    #
    synerror = traceback.format_exc().splitlines()[-1]
    return line, filename, synerror


if __name__ == "__main__":
    username = "******"
    password = "******"
    url = "<portal or AGOL url>"
    itemId = "<Id of feature service item>"
    layerName = "<Name of layer in Feature Service>"
    fc = r"<Path to Feature Class to append>"
    atTable = r"<Attachment table of Feature Class - Optional>"
    try:
        fst = featureservicetools.featureservicetools(
            username=username, password=password, org_url=url, token_url=None, proxy_url=None, proxy_port=None
        )
        if fst.valid:
            fs = fst.GetFeatureService(itemId=itemId, returnURLOnly=False)

            if not fs is None:
                fl = fst.GetLayerFromFeatureService(fs=fs, layerName=layerName, returnURLOnly=False)
                if not fl is None:
                    results = fl.addFeatures(fc=fc, attachmentTable=atTable)
                    print json.dumps(results)
                else:
                    print "Layer %s was not found, please check your credentials and layer name" % layerName
            else:
                print "Feature Service with id %s was not found" % fsId

    except:
Esempio n. 31
0
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    itemId = ""  #<Item ID>
    layerName = ''  #Name of layer in the service
    fc = r''  #Path to Feature Class
    atTable = None
    try:
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print fst.message
        else:

            fs = fst.GetFeatureService(itemId=itemId, returnURLOnly=False)
            if not fs is None:

                fl = fst.GetLayerFromFeatureService(fs=fs,
                                                    layerName=layerName,
                                                    returnURLOnly=False)
                if not fl is None:
                    results = fl.addFeatures(fc=fc, attachmentTable=atTable)
                    print json.dumps(results)
                else:
                    print "Layer %s was not found, please check your credentials and layer name" % layerName
    login_info = {}
    #create Key:Pair values for dictionary
    login_info['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    login_info['username'] = "******"  #<UserName>
    login_info['password'] = "******"  #<Password>
    login_info['org_url'] = "http://www.arcgis.com"

    print login_info

    item_Id = "0e8ea33c42f040aaa51ef845c0a9cd23"  #<Item ID>
    layer_name = 'mta_Bicycle_Route_Network'  #Name of layer in the service
    feature_class = r'C:\PythonBook\Scripts\SanFrancisco.gdb\SanFrancisco\mta_Bicycle_Route_Network'  #Path to Feature Class
    atTable = None

    #activate the feature service tool
    fea_service_tool = featureservicetools.featureservicetools(login_info)
    if fea_service_tool.valid == False:
        print fea_service_tool.message
    else:
        feature_service = fea_service_tool.GetFeatureService(
            itemId=item_Id, returnURLOnly=False)
        if feature_service is not None:
            feature_layer = fea_service_tool.GetLayerFromFeatureService(
                fs=feature_service, layerName=layer_name, returnURLOnly=False)
            if feature_layer is not None:
                #add the features from the feature class to the feature service
                results = feature_layer.addFeatures(fc=feature_class,
                                                    attachmentTable=atTable)
                print json.dumps(results)
            else:
                print "Layer %s was not found, please check your credentials and layer name" % layer_name
Esempio n. 33
0
def main(*argv):

    fsId = None
    groupLayer = None
    layerMap = None
    matchEntireName = None
    projection = None
    scratchGDB = None
    scratchLayer = None
    fst = None
    rows = None
    fieldList = None
    layerToServiceLayer = None
    matches = False
    showFullResponse = False

    try:
        arcpy.env.overwriteOutput = True

        proxy_port = None
        proxy_url = None

        securityinfo = {}

        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None

        username = argv[0]
        password = argv[1]
        siteURL = argv[2]

        version = arcpy.GetInstallInfo()['Version']
        if re.search("^10\.[0-2]", version) is not None:
            bReqUserName = True
        else:
            bReqUserName = False

        if bReqUserName and \
            (username == None or username == "#" or str(username).strip() == "" or \
             password == None or password== "#" or password== "*" or str(password).strip() == ""):
            outputPrinter(
                "{0} Requires a username and password".format(version),
                typeOfMessage='error')
            return

        if bReqUserName:
            securityinfo[
                'security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
            securityinfo['username'] = username
            securityinfo['password'] = password
            securityinfo['org_url'] = siteURL

        else:
            securityinfo[
                'security_type'] = 'ArcGIS'  #LDAP, NTLM, OAuth, Portal, PKI

        groupLayer = argv[3]
        fsId = argv[4]
        layerMap = argv[5]
        matchEntireName = argv[6]
        projection = argv[7]
        lowerCaseFieldNames = argv[8]
        showFullResponse = argv[9]

        if str(lowerCaseFieldNames).upper() == 'TRUE':
            lowerCaseFieldNames = True
        else:
            lowerCaseFieldNames = False
        if projection is not None and projection != '#' and projection != '':
            #outputPrinter(message="Projecting %s" % str(projection))
            pass
        else:
            projection = None
            #outputPrinter(message="No Projection defined")
        arcpy.SetParameterAsText(10, "true")

        scratchGDB = arcpy.env.scratchWorkspace
        scratchLayName = "tempAppGrpFS"
        scratchLayer = os.path.join(scratchGDB, scratchLayName)

        groupLayer = arcpy.mapping.Layer(groupLayer)
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid:
            #outputPrinter(message="Security handler created")

            fs = fst.GetFeatureService(itemId=fsId, returnURLOnly=False)

            if not fs is None:
                #Get a cursor to the layer map recordset
                rows = arcpy.SearchCursor(layerMap)

                #Get the fields
                fieldList = arcpy.ListFields(layerMap)

                #initialize the Translation Dictionary
                layerToServiceLayer = {}

                #Loop through each input row and add it to the conversion dict
                for row in rows:
                    layerToServiceLayer[row.getValue(
                        fieldList[1].name)] = row.getValue(fieldList[2].name)
                    del row
                if groupLayer.isGroupLayer:
                    for lyr in groupLayer:
                        for key, value in layerToServiceLayer.items():
                            if str(matchEntireName).lower(
                            ) == 'true' and key == lyr.name:
                                matches = True
                            elif str(matchEntireName).lower(
                            ) == 'false' and str(lyr.name).startswith(key):
                                matches = True
                            else:
                                matches = False
                            if matches:
                                #arcpy.env.workspace = lyr.workspacePath
                                if arcpy.Exists(dataset=lyr) == True:
                                    outputPrinter(message="\tProcessing %s" %
                                                  (lyr.name))
                                    result = arcpy.GetCount_management(
                                        lyr.name)
                                    count = int(result.getOutput(0))
                                    outputPrinter(message="\t\t%s features" %
                                                  (count))
                                    if count > 0:
                                        layerNameFull = groupLayer.name + '\\' + lyr.name

                                        if projection is not None and projection != "#" and \
                                                projection.strip() !='' :
                                            outputPrinter(
                                                message="\t\tProjecting %s" %
                                                (lyr.name))
                                            result = arcpy.Project_management(
                                                layerNameFull, scratchLayer,
                                                projection)

                                        else:
                                            outputPrinter(
                                                message=
                                                "\t\tCopying %s feature from %s"
                                                % (count, lyr.name))
                                            arcpy.FeatureClassToFeatureClass_conversion(
                                                layerNameFull, scratchGDB,
                                                scratchLayName)

                                        desc = arcpy.Describe(scratchLayer)
                                        if desc.shapeType == 'Polygon':
                                            outputPrinter(
                                                message="\t\tDensifying %s" %
                                                lyr.name)
                                            arcpy.Densify_edit(
                                                scratchLayer, "ANGLE",
                                                "33 Unknown", "0.33 Unknown",
                                                "4")
                                        if desc.shapeType == 'Polyline':
                                            outputPrinter(
                                                message="\t\tDensifying %s" %
                                                lyr.name)
                                            arcpy.Densify_edit(
                                                scratchLayer, "ANGLE",
                                                "33 Unknown", "0.33 Unknown",
                                                "4")
                                        syncLayer(fst, fs, scratchLayer, value,
                                                  lyr.name,
                                                  lowerCaseFieldNames,
                                                  showFullResponse)
                                        outputPrinter(message="\tComplete")
                                        outputPrinter(message="\t")

                                    else:
                                        outputPrinter(
                                            message=
                                            "\t\t%s does not contain any features, skipping"
                                            % lyr.name)
                                        outputPrinter(message="\tComplete")
                                        outputPrinter(message="\t")
                                else:
                                    outputPrinter(
                                        message="\t%s does not exist, skipping"
                                        % lyr.name)
                                    outputPrinter(message="\tComplete")
                                    outputPrinter(message="\t")
                                break

                else:
                    outputPrinter(message="Group layer is not a group layer",
                                  typeOfMessage='error')
            else:
                outputPrinter(
                    message="Feature Service with id %s was not found" % fsId,
                    typeOfMessage='error')
                arcpy.SetParameterAsText(10, "false")
        else:
            outputPrinter(fst.message, typeOfMessage='error')
            arcpy.SetParameterAsText(10, "false")

    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,
                      typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,
                      typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,
                      typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),
                      typeOfMessage='error')
        arcpy.SetParameterAsText(10, "false")
    except (common.ArcRestHelperError), e:
        outputPrinter(message=e, typeOfMessage='error')
        arcpy.SetParameterAsText(10, "false")
Esempio n. 34
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI, ArcGIS
    securityinfo['username'] = "" #User Name
    securityinfo['password'] = "" #Password
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    itemId = ""#<Item ID>
    sql = "workOrderId = 'jCYverjadj'" #sql to return records to update
    fieldToChange = 'status' #field to change
    valueToSet = '3' #value to set

    fl = None
    fls = None
    fs = None
    try:
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print (fst.message)
        else:
            fs = fst.GetFeatureService(itemId=itemId,returnURLOnly=False)
            if not fs is None:
                fls = fs.layers
                if len(fls) > 0 :
                    fl = fls[0]
            if fl is None:
                print ("Layer Not Found")
                return

            features = fl.query(where=sql,out_fields='OBJECTID' + "," + fieldToChange,returnGeometry=False)
            if len(features) == 0:
                print ("No Matching features")
                return
            for feature in features:
                feature.set_value(fieldToChange,valueToSet)

            results = fl.updateFeature(features=features)

            if 'error' in results:
                print ("Error in response from server:  %s" % results['error'])

            else:
                if results['updateResults'] is not None:
                    featSucces = 0
                    for result in results['updateResults']:
                        if 'success' in result:
                            if result['success'] == False:
                                if 'error' in result:
                                    print ("Error info: %s" % (result['error']))
                            else:
                                featSucces = featSucces + 1

                    print ("%s features updated in %s" % (featSucces,fl.name))
                else:
                    print ("0 features updated in %s /n result info %s" % (fl.name,str(results)))

    except (common.ArcRestHelperError),e:
        print ("error in function: %s" % e[0]['function'])
        print ("error on line: %s" % e[0]['line'])
        print ("error in file name: %s" % e[0]['filename'])
        print ("with error message: %s" % e[0]['synerror'])
        if 'arcpyError' in e[0]:
            print ("with arcpy message: %s" % e[0]['arcpyError'])
def main():
    #Path and name of file to store log
    logFile = r"c:\temp\log.log"
    logFile = common.init_log(logFile)    
    try:
        proxy_port = None
        proxy_url = None
    
        securityinfo = {}
        securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
        securityinfo['username'] = ""#<UserName>
        securityinfo['password'] = ""#<Password>
        securityinfo['org_url'] = "http://www.arcgis.com"
        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None
        
        #Date time format of the service, example'2016-04-26 04:00:00'
        dateTimeFormat = "%Y/%m/%d %H:%M:%S"
        #log file to store details
        
        print ("###### Date Extraction Process Started ######")
        print ("\tStarted at {0}".format(datetime.datetime.now().strftime(dateTimeFormat)))
        
        fst = featureservicetools.featureservicetools(securityinfo)
        
        """Settings"""
        #URL to service
        url = ''#url to feature layer, make sure it ends in \layer number 
        
        #Base sql expression to find features of a type
        sql = "1=1"
  
        #Field used to restrict query to only records since last query
        statusUpdateField = 'Laststatusupdate'
        #Fields to save to the output CSV, format Field1,Field2,...
        out_fields ='OBJECTID,GIS_ID,Nickname'
    
        """The location and file name to save the results to"""
        #Option are a folder or a GDB
        outputLocation = r"c:\temp"
        
        #Output filename
        #  Options:
        #    *.csv - output is a csv file, outputLocation must be a folder
        #    *.json - output is a json text file, outputLocation must be a folder
        #    * - output is a Shapefile or GDB featureclass depending on outputLocation
        outputFileName = "results.csv" 
        
        #File with the date of the last run, if it does not exist, all features are returned and file is created for next run
        lastRunDetails = r"c:\temp\lastrundate.txt"
        
        lastQueryDate = None
        
        #Open the file with the last run date
        if os.path.isfile(lastRunDetails):
            print("\tLast run file exist")
            with open(lastRunDetails, 'r') as configFile:
                lastQueryDate = configFile.read()
                configFile.close()
            print("\t\tLast query date: {0}".format(lastQueryDate))
            
        #If the last query date file was found and value is a date
        queryDate = datetime.datetime.now().strftime(dateTimeFormat)
        if lastQueryDate is not None and validate(date_text=lastQueryDate, dateTimeFormat=dateTimeFormat):
            sql = sql + " AND " + statusUpdateField + " >= " + "'" + lastQueryDate + "'"
            #Add current time to query
            sql = sql + " AND " + statusUpdateField + " <= " + "'" + queryDate + "'"
        
        print("\tSQL: {0}".format(sql))
        
        #query the layer
        featureSet  = fst.QueryAllFeatures(url=url,
                            where=sql,
                            out_fields=out_fields,
                            chunksize=300,
                            printIndent="\t")
        if (isinstance(featureSet,arcrest.common.general.FeatureSet)):
            if len(featureSet.features) == 0:
                print ("\tNo features matching the query where found")
            else:
                print("\t{0} feature(s) returned".format(len(featureSet.features)))
                #Create a new output writer
                saveLocation = os.path.join(outputLocation, outputFileName)
                if (len(featureSet.features) == 0):
                    if os.path.isfile(saveLocation):
                        os.remove(saveLocation)
                else:
                    #Save the results to a file
                    result = featureSet.save(saveLocation=outputLocation, outName=outputFileName)
                    print ("\t{0} created".format(result))
                    """
                    If you want to process the results of the query without saving to a file
                    uncomment the process below and add your code.  The example below loops
                    through each field in a feature in a featureset.
                    
                    """
                    #for feature in featureSet:
                        #print ("\t----------------------")
                        #for field in featureSet.fields:
                            #print ("\t\tField Name: {0} | Field Value: {1}".format(field['name'],feature.get_value(field['name'])))
                        #print ("\t######################")
        else:
            print ("\tNo features matching the query where found")
                
        #Update the last run file
        with open(lastRunDetails, 'w') as configFile:
            configFile.write(queryDate)
            configFile.close()
            print("\t{0} saved to last run file".format(queryDate))
        print ("\tCompleted at {0}".format(datetime.datetime.now().strftime(dateTimeFormat)))
        print ("###### Completed ######")
    except (common.ArcRestHelperError) as e:
        print ("error in function: %s" % e[0]['function'])
        print ("error on line: %s" % e[0]['line'])
        print ("error in file name: %s" % e[0]['filename'])
        print ("with error message: %s" % e[0]['synerror'])
        if 'arcpyError' in e[0]:
            print ("with arcpy message: %s" % e[0]['arcpyError'])
    except:
        line, filename, synerror = trace()
        print ("error on line: %s" % line)
        print ("error in file name: %s" % filename)
        print ("with error message: %s" % synerror)
    finally:
        if (logFile):
            common.close_log(logFile)
Esempio n. 36
0
def main(*argv):

    fsId = None
    groupLayer = None
    layerMap = None
    matchEntireName = None
    projection = None
    scratchGDB = None
    scratchLayer = None
    fst = None
    rows = None
    fieldList = None
    layerToServiceLayer = None
    matches = False
    showFullResponse = False

    try:
        arcpy.env.overwriteOutput = True

        proxy_port = None
        proxy_url = None

        securityinfo = {}
        securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
        securityinfo['username'] = ""#<UserName>
        securityinfo['password'] = ""#<Password>
        securityinfo['org_url'] = "http://www.arcgis.com"
        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None

        itemId = "660c9dde3a24428e9143473f6ee7f77d"#Item ID of the feature service

        path = r'C:\sampleData\ElectricNetwork.gdb'#Path to GDB with layers to post
        #List of layers in the gdb and name of layer in the service
        featureClasses = [
            {
              "FeatureClass":"SafetyViolation",
              "Layer":"Violations"
              },
            {
              "FeatureClass":"VoltageRegulator",
              "Layer":"Voltage Regulator"
              },
            {
              "FeatureClass":"Capacitor",
              "Layer":"Power Factor Correcting Equipment"
              },
            {
              "FeatureClass":"Elbow",
              "Layer":"Elbow"
              },
            {
              "FeatureClass":"Fuse",
              "Layer":"Fuse"
              },
            {
              "FeatureClass":"CircuitBreaker",
              "Layer":"Protective Device"
              },
            {
              "FeatureClass":"Switch",
              "Layer":"Switch"
              },
            {
              "FeatureClass":"ServicePoint",
              "Layer":"Service Point"
              },
            {
              "FeatureClass":"Transformer",
              "Layer":"Transformer"
              },
            {
              "FeatureClass":"UndergroundStructures",
              "Layer":"Underground Structure"
              },
            {
              "FeatureClass":"Streetlights",
              "Layer":"Streetlight"
              },
            {
              "FeatureClass":"Poles",
              "Layer":"Poles"
              },
            {
              "FeatureClass":"SurfaceStructures",
              "Layer":"Surface Structure"
              },
            {
              "FeatureClass":"Substation",
              "Layer":"Electric Station"
              },
            {
              "FeatureClass":"BoundarySubstation",
              "Layer":"Substation Boundary"
              },
            {
              "FeatureClass":"SwitchingFacility",
              "Layer":"Switching Facility"
              },
            {
              "FeatureClass":"OHMediumVoltage",
              "Layer":"Primary Overhead Conductor"
              },
            {
              "FeatureClass":"UGMediumVoltage",
              "Layer":"Primary Underground Conductor"
              },     {
                "FeatureClass":"UGLowVoltage",
                "Layer":"Secondary Underground Conductor"
                },
            {
              "FeatureClass":"OHLowVoltage",
              "Layer":"Secondary Overhead Conductor"
              },
            {
              "FeatureClass":"MediumVoltageBusBar",
              "Layer":"Bus Bar"
            }
          ]

        sr = arcpy.SpatialReference(3587) #to project the data, set to None to skip projection
        lowerCaseFieldNames = False #option to convert all fields to lowercase for portal data store services
        showFullResponse = True #option to return the entire response string

        if str(lowerCaseFieldNames).upper() == 'TRUE' or lowerCaseFieldNames == True:
            lowerCaseFieldNames = True
        else:
            lowerCaseFieldNames = False
        if projection is not None and projection != '#' and projection != '':
            #outputPrinter(message="Projecting %s" % str(projection))
            pass
        else:
            projection = None
            #outputPrinter(message="No Projection defined")

        scratchGDB = arcpy.env.scratchWorkspace
        scratchLayName = random_string_generator()
        scratchLayer = os.path.join(scratchGDB,scratchLayName)

        groupLayer = arcpy.mapping.Layer(groupLayer)
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid:
            #outputPrinter(message="Security handler created")

            fs = fst.GetFeatureService(itemId=fsId,returnURLOnly=False)

            if not fs is None:

                #Loop through each input row and add it to the conversion dict
                for featureClass in featureClasses:
                    localLayer = os.path.join(path,featureClass["FeatureClass"])
                    layerName = featureClass["FeatureClass"]
                    if (arcpy.Exists(localLayer)):

                        outputPrinter(message="\tProcessing %s" % (layerName))
                        result =  arcpy.GetCount_management(localLayer)
                        count = int(result.getOutput(0))
                        outputPrinter(message="\t\t%s features" % (count))
                        if count > 0:

                            if projection is not None and projection != "#" and \
                                    projection.strip() !='' :
                                outputPrinter(message="\t\tProjecting %s" % (layerName))
                                result = arcpy.Project_management(localLayer,
                                                        scratchLayer,
                                                        projection)

                            else:
                                outputPrinter(message="\t\tCopying %s feature from %s" % (count,layerName))
                                arcpy.FeatureClassToFeatureClass_conversion(localLayer,scratchGDB,scratchLayName)

                            desc = arcpy.Describe(scratchLayer)
                            if desc.shapeType == 'Polygon':
                                outputPrinter(message="\t\tDensifying %s" % layerName)
                                arcpy.Densify_edit(scratchLayer, "ANGLE", "33 Unknown", "0.33 Unknown", "4")
                            if desc.shapeType == 'Polyline':
                                outputPrinter(message="\t\tDensifying %s" % layerName)
                                arcpy.Densify_edit(scratchLayer, "ANGLE", "33 Unknown", "0.33 Unknown", "4")
                            syncLayer(fst, fs, scratchLayer, layerName, layerName,lowerCaseFieldNames,showFullResponse)
                            outputPrinter (message="\tComplete")
                            outputPrinter (message="\t")

                        else:
                            outputPrinter (message="\t\t%s does not contain any features, skipping" % layerName)
                            outputPrinter (message="\tComplete")
                            outputPrinter (message="\t")

            else:
                outputPrinter(message="Feature Service with id %s was not found" % fsId, typeOfMessage='error')

        else:
            outputPrinter(fst.message,typeOfMessage='error')

    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),typeOfMessage='error')
        arcpy.SetParameterAsText(10, "false")
    except (common.ArcRestHelperError),e:
        outputPrinter(message=e,typeOfMessage='error')
        arcpy.SetParameterAsText(10, "false")
Esempio n. 37
0
def main():
    try:
        proxy_port = None
        proxy_url = None

        securityinfo = {}
        securityinfo[
            'security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
        securityinfo['username'] = ""  #<UserName>
        securityinfo['password'] = ""  #<Password>
        securityinfo['org_url'] = "http://www.arcgis.com"
        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None

        workforceProjectID = ''  #Workforce project number

        assignmentAreasID = ''  #ID of service to get centroids from
        assignmentAreaLayerName = ''  #layer in servuce
        assignmentAreaNameField = ''  #field with name of id area

        csvPath = r".\dataToLookup.csv"  #<Path with data>
        workerCol = 'worker'
        areaCol = 'area'
        descriptionCol = "description"
        notesCol = "notes"
        supervisorCol = "supervisor"

        assignmentType = 2
        status = 1

        workerNameToID = {}
        dispatcherNameToID = {}
        areaNameToID = {}
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print(fst.message)
        else:
            portalAdmin = arcrest.manageorg.Administration(
                securityHandler=fst.securityhandler)
            #Get the assignment areas
            fs = fst.GetFeatureService(itemId=assignmentAreasID,
                                       returnURLOnly=False)
            if not fs is None:
                fs_url = fst.GetLayerFromFeatureService(
                    fs=fs,
                    layerName=assignmentAreaLayerName,
                    returnURLOnly=True)
                if not fs_url is None:

                    fl = FeatureLayer(url=fs_url,
                                      securityHandler=fst.securityhandler,
                                      proxy_port=proxy_port,
                                      proxy_url=proxy_url,
                                      initialize=True)
                    areaResults = fl.query(
                        **{
                            'where': "1=1",
                            'outSR': '102100',
                            'out_fields': assignmentAreaNameField,
                            'returnGeometry': False,
                            'returnCentroid': True
                        })

                    for area in areaResults:
                        arDict = area.asDictionary
                        areaNameToID[arDict['attributes'][
                            assignmentAreaNameField]] = arDict['centroid']

            #Get the workers
            item = portalAdmin.content.getItem(itemId=workforceProjectID)
            itemData = item.itemData()
            if 'workers' in itemData:
                fl = FeatureLayer(url=itemData['workers']['url'],
                                  securityHandler=fst.securityhandler,
                                  proxy_port=proxy_port,
                                  proxy_url=proxy_url,
                                  initialize=True)

                workersResults = fl.query(where="1=1",
                                          out_fields='OBJECTID, NAME',
                                          returnGeometry=False)
                for worker in workersResults:
                    workerNameToID[worker.get_value(
                        'name')] = worker.get_value('OBJECTID')

            if 'dispatchers' in itemData:
                fl = FeatureLayer(url=itemData['dispatchers']['url'],
                                  securityHandler=fst.securityhandler,
                                  proxy_port=proxy_port,
                                  proxy_url=proxy_url,
                                  initialize=True)

                dispatcherResults = fl.query(where="1=1",
                                             out_fields='OBJECTID, NAME',
                                             returnGeometry=False)
                for dispatcher in dispatcherResults:
                    dispatcherNameToID[dispatcher.get_value(
                        'name')] = dispatcher.get_value('OBJECTID')

            if 'assignments' in itemData:
                features = []

                fl = FeatureLayer(url=itemData['assignments']['url'],
                                  securityHandler=fst.securityhandler,
                                  proxy_port=proxy_port,
                                  proxy_url=proxy_url,
                                  initialize=True)
                print(fl.deleteFeatures(where="1=1"))
                with open(csvPath) as csvfile:
                    reader = UnicodeDictReader(csvfile)
                    for row in reader:
                        json_string = {}
                        json_string['geometry'] = {}

                        centroidInfo = areaNameToID[row[areaCol].strip()]

                        json_string['geometry']['x'] = centroidInfo['x']
                        json_string['geometry']['y'] = centroidInfo['y']
                        json_string['attributes'] = {}
                        json_string['attributes']['workerId'] = workerNameToID[
                            row[workerCol].strip()]
                        json_string['attributes']['description'] = row[
                            descriptionCol]
                        json_string['attributes']['notes'] = row[notesCol]
                        json_string['attributes'][
                            'assignmentType'] = assignmentType
                        json_string['attributes']['status'] = status
                        json_string['attributes'][
                            'dispatcherId'] = dispatcherNameToID[
                                row[supervisorCol].strip()]

                        features.append(Feature(json_string=json_string))
                    results = fl.addFeature(features=features)

                    if 'error' in results:
                        print("Error in response from server:  %s" %
                              results['error'])

                    else:
                        if results['addResults'] is not None:
                            featSucces = 0
                            for result in results['addResults']:
                                if 'success' in result:
                                    if result['success'] == False:
                                        if 'error' in result:
                                            print("Error info: %s" %
                                                  (result['error']))
                                    else:
                                        featSucces = featSucces + 1

                            print("%s features added to %s" %
                                  (featSucces, fl.name))
                        else:
                            print("0 features added to %s /n result info %s" %
                                  (fl.name, str(results)))

    except (common.ArcRestHelperError) as e:
        print("error in function: %s" % e[0]['function'])
        print("error on line: %s" % e[0]['line'])
        print("error in file name: %s" % e[0]['filename'])
        print("with error message: %s" % e[0]['synerror'])
        if 'arcpyError' in e[0]:
            print("with arcpy message: %s" % e[0]['arcpyError'])

    except:
        line, filename, synerror = trace()
        print("error on line: %s" % line)
        print("error in file name: %s" % filename)
        print("with error message: %s" % synerror)
Esempio n. 38
0
    # Get Python syntax error
    #
    synerror = traceback.format_exc().splitlines()[-1]
    return line, filename, synerror

if __name__ == "__main__":
    username = "******"
    password = "******"
    url = "<portal or AGOL url>"
    itemId = "<Id of feature service item>"    
    layerName='<Name of layer in Feature Service>'
    fc=r'<Path to Feature Class to append>'
    atTable=r'<Attachment table of Feature Class - Optional>'    
    try:   
        fst = featureservicetools.featureservicetools(username = username, password=password,org_url=url,
                                           token_url=None, 
                                           proxy_url=None, 
                                           proxy_port=None)
        if fst.valid:
            fs = fst.GetFeatureService(itemId=itemId,returnURLOnly=False)
          
            if not fs is None:                
                fl = fst.GetLayerFromFeatureService(fs=fs,layerName=layerName,returnURLOnly=False)
                if not fl is None:
                    results = fl.addFeatures(fc=fc,attachmentTable=atTable)        
                    print json.dumps(results)
                else:
                    print "Layer %s was not found, please check your credentials and layer name" % layerName     
            else:
                print "Feature Service with id %s was not found" % fsId                                               
          
    except:
Esempio n. 39
0
def main(*argv):
    userName = None
    password = None
    org_url = None
    fsId = None
    layerName = None
    dataToAppend = None
    fst = None
    fs = None
    results = None
    fl = None
    existingDef= None
    try:
        proxy_port = None
        proxy_url = None    
    
        securityinfo = {}
        securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
        securityinfo['username'] = argv[0]
        securityinfo['password'] = argv[1]
        securityinfo['org_url'] = argv[2]
        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None   
        
        fsId = argv[3]
        layerName = argv[4]
        dataToAppend = argv[5]
        toggleEditCapabilities = argv[6]
       
        if arcpy.Exists(dataset=dataToAppend) == False:
            outputPrinter(message="Data layer not found: " + dataToAppend)
        else:
            fst = featureservicetools.featureservicetools(securityinfo)
            if fst.valid:
                outputPrinter(message="Security handler created")

                fs = fst.GetFeatureService(itemId=fsId,returnURLOnly=False)

                if not fs is None:
                    if str(toggleEditCapabilities).upper() == 'TRUE':
                        existingDef = fst.EnableEditingOnService(url=fs.url)
                    fl = fst.GetLayerFromFeatureService(fs=fs,layerName=layerName,returnURLOnly=False)
                    if not fl is None:
                        results = fl.addFeatures(fc=dataToAppend)

                        if 'error' in results:
                            outputPrinter(message="Error in response from server:  %s" % results['error'],typeOfMessage='error')
                            arcpy.SetParameterAsText(7, "false")

                        else:
                            outputPrinter (message="%s features added" % len(results['addResults']) )
                            if toggleEditCapabilities == 'True':
                                existingDef = fst.EnableEditingOnService(url=fs.url,definition = existingDef)
                            arcpy.SetParameterAsText(7, "true")

                    else:
                        outputPrinter(message="Layer %s was not found, please check your credentials and layer name" % layerName,typeOfMessage='error')
                        arcpy.SetParameterAsText(7, "false")
                else:
                    outputPrinter(message="Feature Service with id %s was not found" % fsId,typeOfMessage='error')
                    arcpy.SetParameterAsText(7, "false")
            else:
                outputPrinter(fst.message,typeOfMessage='error')
                arcpy.SetParameterAsText(7, "false")



    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),typeOfMessage='error')
        arcpy.SetParameterAsText(7, "false")
    except (common.ArcRestHelperError),e:
        outputPrinter(message=e,typeOfMessage='error')
        arcpy.SetParameterAsText(7, "false")
def main():
    try:
        proxy_port = None
        proxy_url = None
    
        securityinfo = {}
        securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
        securityinfo['username'] = ""#<UserName>
        securityinfo['password'] = ""#<Password>
        securityinfo['org_url'] = "http://www.arcgis.com"
        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None
    
    
        workforceProjectID = '' #Workforce project number

        assignmentAreasID = '' #ID of service to get centroids from
        assignmentAreaLayerName = ''#layer in servuce
        assignmentAreaNameField = ''#field with name of id area
        
        csvPath = r".\dataToLookup.csv"#<Path with data>
        workerCol = 'worker'
        areaCol  = 'area'
        descriptionCol = "description"
        notesCol = "notes"
        supervisorCol = "supervisor"
         
        assignmentType = 2
        status = 1
        
        workerNameToID = {}
        dispatcherNameToID = {}
        areaNameToID = {}
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print (fst.message)
        else:
            portalAdmin = arcrest.manageorg.Administration(securityHandler=fst.securityhandler)
            #Get the assignment areas
            fs = fst.GetFeatureService(itemId=assignmentAreasID,returnURLOnly=False)
            if not fs is None:
                fs_url = fst.GetLayerFromFeatureService(fs=fs,layerName=assignmentAreaLayerName,returnURLOnly=True)
                if not fs_url is None:

                    fl = FeatureLayer(
                        url=fs_url,
                        securityHandler=fst.securityhandler,
                        proxy_port=proxy_port,
                        proxy_url=proxy_url,
                        initialize=True)                    
                    areaResults =  fl.query(**{'where':"1=1",'outSR':'102100','out_fields':assignmentAreaNameField,'returnGeometry':False,'returnCentroid':True})
                   
                    for area in areaResults:
                        arDict = area.asDictionary
                        areaNameToID[arDict['attributes'][assignmentAreaNameField]] = arDict['centroid']
                    
            #Get the workers
            item = portalAdmin.content.getItem(itemId=workforceProjectID)
            itemData = item.itemData()
            if 'workers' in itemData:
                fl = FeatureLayer(
                    url=itemData['workers']['url'],
                    securityHandler=fst.securityhandler,
                    proxy_port=proxy_port,
                    proxy_url=proxy_url,
                    initialize=True)
            
                workersResults = fl.query(where="1=1",out_fields='OBJECTID, NAME',returnGeometry=False)
                for worker in workersResults:
                    workerNameToID[worker.get_value('name')] = worker.get_value('OBJECTID')
            
            if 'dispatchers' in itemData:
                fl = FeatureLayer(
                    url=itemData['dispatchers']['url'],
                    securityHandler=fst.securityhandler,
                    proxy_port=proxy_port,
                    proxy_url=proxy_url,
                    initialize=True)
            
                dispatcherResults = fl.query(where="1=1",out_fields='OBJECTID, NAME',returnGeometry=False)
                for dispatcher in dispatcherResults:
                    dispatcherNameToID[dispatcher.get_value('name')] = dispatcher.get_value('OBJECTID')
                    
    
            if 'assignments' in itemData:
                features = []
                
                fl = FeatureLayer(
                    url=itemData['assignments']['url'],
                    securityHandler=fst.securityhandler,
                    proxy_port=proxy_port,
                    proxy_url=proxy_url,
                    initialize=True)
                print(fl.deleteFeatures(where="1=1"))
                with open(csvPath) as csvfile:
                    reader = UnicodeDictReader(csvfile)
                    for row in reader:
                        json_string={}
                        json_string['geometry'] = {}
                       
                        centroidInfo = areaNameToID[row[areaCol].strip()]
                        
                        json_string['geometry']['x'] = centroidInfo['x']
                        json_string['geometry']['y'] = centroidInfo['y']
                        json_string['attributes'] ={}
                        json_string['attributes']['workerId'] = workerNameToID[row[workerCol].strip()]
                        json_string['attributes']['description'] = row[descriptionCol]
                        json_string['attributes']['notes'] = row[notesCol]
                        json_string['attributes']['assignmentType'] = assignmentType
                        json_string['attributes']['status'] = status
                        json_string['attributes']['dispatcherId'] = dispatcherNameToID[row[supervisorCol].strip()]
                        
                         
                        features.append(Feature(json_string=json_string))
                    results = fl.addFeature(features=features)
    
                    if 'error' in results:
                        print ("Error in response from server:  %s" % results['error'])
    
                    else:
                        if results['addResults'] is not None:
                            featSucces = 0
                            for result in results['addResults']:
                                if 'success' in result:
                                    if result['success'] == False:
                                        if 'error' in result:
                                            print ("Error info: %s" % (result['error']))
                                    else:
                                        featSucces = featSucces + 1
    
                            print ("%s features added to %s" % (featSucces,fl.name))
                        else:
                            print ("0 features added to %s /n result info %s" % (fl.name,str(results)))             

    except (common.ArcRestHelperError) as e:
        print ("error in function: %s" % e[0]['function'])
        print ("error on line: %s" % e[0]['line'])
        print ("error in file name: %s" % e[0]['filename'])
        print ("with error message: %s" % e[0]['synerror'])
        if 'arcpyError' in e[0]:
            print ("with arcpy message: %s" % e[0]['arcpyError'])

    except:
        line, filename, synerror = trace()
        print ("error on line: %s" % line)
        print ("error in file name: %s" % filename)
        print ("with error message: %s" % synerror)
Esempio n. 41
0
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None   

    
    itemId = ""#<Item ID>
    layerName=''#Name of layer in the service
    fc=r''#Path to Feature Class
    atTable=None   
    try:   
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print fst.message
        else:         

            fs = fst.GetFeatureService(itemId=itemId,returnURLOnly=False)
            if not fs is None:

                fl = fst.GetLayerFromFeatureService(fs=fs,layerName=layerName,returnURLOnly=False)
                if not fl is None:
                    results = fl.addFeatures(fc=fc,attachmentTable=atTable)        
                    print json.dumps(results)
                else:
                    print "Layer %s was not found, please check your credentials and layer name" % layerName     
            else:
                print "Feature Service with id %s was not found" % fsId                                               
def main(*argv):

    fsId = None
    layerName = None
    dataToAppend = None
    fst = None
    fs = None
    results = None
    fl = None
    existingDef= None
    try:


        fsId = argv[0]
        layerName = argv[1]
        dataToAppend = argv[2]
        toggleEditCapabilities = argv[3]

        if arcpy.Exists(dataset=dataToAppend) == False:
            outputPrinter(message="Data layer not found: %" % dataToAppend)
        else:
            fst = featureservicetools.featureservicetools(proxy_url=None,
                                                       proxy_port=None,
                                                        use_arcgis_creds=True)
            if fst.valid:
                outputPrinter(message="Security handler created")

                fs = fst.GetFeatureService(itemId=fsId,returnURLOnly=False)

                if not fs is None:
                    if str(toggleEditCapabilities).upper() == 'TRUE':
                        existingDef = fst.EnableEditingOnService(url=fs.url)
                    fl = fst.GetLayerFromFeatureService(fs=fs,layerName=layerName,returnURLOnly=False)
                    if not fl is None:
                        results = fl.addFeatures(fc=dataToAppend)

                        if 'error' in results:
                            outputPrinter(message="Error in response from server:  %s" % results['error'],typeOfMessage='error')
                            arcpy.SetParameterAsText(4, "false")

                        else:
                            if results['addResults'] is not None:
                                outputPrinter (message="%s features added" % len(results['addResults']) )
                            else:
                                outputPrinter (message="0 features added" )
                            if toggleEditCapabilities == 'True':
                                existingDef = fst.EnableEditingOnService(url=fs.url,definition = existingDef)
                            arcpy.SetParameterAsText(4, "true")

                    else:
                        outputPrinter(message="Layer %s was not found, please check your credentials and layer name" % layerName,typeOfMessage='error')
                        arcpy.SetParameterAsText(4, "false")
                else:
                    outputPrinter(message="Feature Service with id %s was not found" % fsId,typeOfMessage='error')
                    arcpy.SetParameterAsText(4, "false")
            else:
                outputPrinter(fst.message,typeOfMessage='error')
                arcpy.SetParameterAsText(4, "false")



    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        outputPrinter(message="error on line: %s" % line,typeOfMessage='error')
        outputPrinter(message="error in file name: %s" % filename,typeOfMessage='error')
        outputPrinter(message="with error message: %s" % synerror,typeOfMessage='error')
        outputPrinter(message="ArcPy Error Message: %s" % arcpy.GetMessages(2),typeOfMessage='error')
        arcpy.SetParameterAsText(4, "false")
    except (common.ArcRestHelperError),e:
        outputPrinter(message=e,typeOfMessage='error')
        arcpy.SetParameterAsText(4, "false")