POST
|
Why does this code throw an exception during casting? It worked fine previously in ArcGIS 9.3.1.
public void ShowGPWindow(IGPTool tool)
{
IMdElementDialogEvents events;
IMdProcess process = new MdProcessClass();
process.Tool = tool;
IMdElement element = process as IMdElement;
IMdElementDialog toolDialog = new MdDefaultElementDialogClass();
toolDialog.Title = "Jack Dangermond for Life.";
toolDialog.ElementEditor = toolDialog.GetDefaultElementEditor(process);
toolDialog.SetButtons(esriElementDialogButtonType.esriOkCancel);
toolDialog.Show(m_application.hWnd);
events = (IMdElementDialogEvents)toolDialog;
I get a InvalidCastException, and through intellitrace the error is:
Exception:Thrown: "Unable to cast COM object of type 'ESRI.ArcGIS.GeoprocessingUI.MdDefaultElementDialogClass' to interface type 'ESRI.ArcGIS.GeoprocessingUI.IMdElementDialogEvents'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{A2B1583C-00B8-435F-A57C-58956CFB8503}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))." (System.InvalidCastException)
A System.InvalidCastException was thrown: "Unable to cast COM object of type 'ESRI.ArcGIS.GeoprocessingUI.MdDefaultElementDialogClass' to interface type 'ESRI.ArcGIS.GeoprocessingUI.IMdElementDialogEvents'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{A2B1583C-00B8-435F-A57C-58956CFB8503}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))."
According to the documentation MdDefaultElementDialog coclass can be QI'ed to IMdElementDialogEvents, also MdElementDialogEventsHelper has the same issue. =( What am i doing wrong? This seems valid to me.
... View more
12-03-2010
09:44 PM
|
0
|
0
|
1222
|
POST
|
Hi, Could you please elaborate on this fix? Sometimes my ArcMap add-in breakpoints are recognised, but most of the time Visual Studio just says "This breakpoint will not currently be hit. The source code is different from the original version." I have tried manually deleting and re-adding the add-in but it no longer seems to make a difference. Can you provide the steps you went through? I think part of the problem is that the add-in is copied over to its new location in user-dir\ArcGIS\add-ins etc. when added to the application. Any help much appreciated. Pretty much i just did as i posted, disable extension, delete add-in, close, do a clean, and then manaully clean out your /obj and /bin folders. Rebuild it. However this happened way to frequently for me, so i just dropped the whole add-in model, and went back to the old method.
... View more
12-02-2010
05:06 PM
|
0
|
0
|
433
|
POST
|
Well, take them with a grain of salt - they are not the primary spot for learning python-real python. Thanks for that, what is your opinion of PythonWin? http://www.python.org/download/windows/ Pythonwin has amazing intellisense. However it kinda stops being useful once you move outside of a single python file. When working on a package, things start to get fairly complex and at that point pythonwin stops being useful. Lastly, go to the PyCom conference website. All you ever want to know about advanced Python is there with some excellent presentations. http://us.pycon.org/2010/conference/schedule/ Those presentations are great, however i just wish some of the presentations actually gave out the slides and not just a 45 minute video demo. I know what you mean about the Python.org documentation--it's really good, but thick and lacking in examples. When I was first learning Python, this site was really helpful: http://effbot.org/zone/ Every topic is full of example code. Be aware, though, that some of the samples are a little out-of-date, like for instance the references to the string module, which has been largely replaced by string methods. good luck, Mike Also watch out alot of the stuff on effbot, uses non standard modules or has been added to the python standard library under a slightly different name.
... View more
11-24-2010
10:48 AM
|
0
|
0
|
622
|
POST
|
If you just started to want to learn python, don't use ESRI's tutorials. They do alot of ... questionable things and alot of things that are only specific to their library. Also be extremly weary of ripping off python examples from ESRI's library certain parts of it are meant for previous versions. I also really suggest you actually try and learn how to code, so this doesn't appear "I COPIED SCRIPT X AND SCRIPT Y AND PUT THEM TOGTHER NOW THEY DON"T WORK, HALP" For learning Python: 1. Get Pyscripter (http://code.google.com/p/pyscripter/), run as fast as you possibly can from IDLE and notepad. 2. Read python's offical tutorial: http://docs.python.org/release/2.6.6/tutorial/index.html , they will hold your hand 3. Dive Into Python(http://diveintopython.org/) is free, and is one of the most commonly recommended tutorials Things you should bookmark: Stackoverflow.com: If you have questions about how to do x, post it there. You'll get a response within 5 minutes. Python Library: http://docs.python.org/release/2.6.6/library/index.html keep this under your pillow for looking up specific functionality. Google's Style Documentation(http://google-styleguide.googlecode.com/svn/trunk/pyguide.html) they have very good points, and if you post on stackoverflow.com or other python centric forums, and your code is not formatted atleast sanely they will ridicule you. For ArcGIS: 1. http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/What_is_ArcPy/000v000000v7000000/ ArcPy Library 2. Geoprocessing forum: http://forums.arcgis.com/forums/31-Geoprocessing
... View more
11-24-2010
07:38 AM
|
0
|
0
|
622
|
POST
|
Limitation, can you be more specific? What are some problems that you have encountered? The Free Wing 101 still works good. http://www.wingware.com/downloads/wingide-101/3.2.11-1/binaries I have no association with Wing, other than using the product. "Wing IDE 101 is free scaled down Python IDE designed for use in teaching introductory programming classes. It omits many features found in Wing IDE Professional and makes simplifications appropriate for beginners.The OS X version requires an X11 Server. " Their licensing is based around OS Installs. So i cannot take their IDE and install it on my laptop since it has already been installed on my desktop. So wait. So that ~200$ CAD purchase turns into ~400$ CAD if i want to run it on my desktop and on my laptop. Also if you reinstall or change your hardware configuration you need to plead to technical support to get your key reinitialized. Compared to pycharm i have it happily installed on my desktop, and my laptop, and when i reinstall my os i don't need to contact technical support. WingIDE 101 is a joke. It omits basic functionality that can be found in free IDE's like pyscripter, and Aptana. Once you take away the best features of WingIDE (code completetion, unit testing, debug probing, etc). All your left with is an ugly text editor.
... View more
11-23-2010
05:42 AM
|
0
|
0
|
328
|
POST
|
Hi, I was wondering if there is anyway to use debugging(break points + etc) when working with an ArcGIS addin? It seems that my breakpoints are never hit. Using Visual studio 2010 + ArcGIS 10. Any ideas? *EDIT* Fixed it, for whatever ever reason removing the extension, and deleting the add-in manually, then rebuilding it allowed my breakpoints to actually be hit.
... View more
11-20-2010
06:23 PM
|
0
|
3
|
2657
|
POST
|
Frank, Pycharm sounds interesting. The only thing I know about refractoring tools is what I read in the last 5 minutes. Could you very briefly explain what it takes to set up Pycharm to "fix" your code? I'm curious. Thanks. Huh, i don't know why but ether the forums swallowed most of my post or i screwed up somehow sigh. The easiest way to change your code from arcgisscripting --> arcpy (however i don't know why you need to). Make a project add your scripts. Open up arcgisscripting module from within pycharm (it will generate method stubs) for you from the dll. Copy everything, make a new module called arcgisscripting.py within your project. Just to be safe unload the real arcgisscripting library (remove it via the settings panel). You can now then and go and refactor your copy, if you change the module name from arcgisscripting to arcpy (also unload the real arcpy) your scripts will update them selves. Then do the same for methods. PyCharm looks cool ($100 though - actually $200 for me (govt.)) - but where's the interactive/immediate window? I run this code in PyCharm: import random
randomList = []
for i in range (1,11):
randomList.append(random.random()) How can I view the contents of randomList? I am not sure what you mean exactly by interactive/immediate.. If you want to view the value of something while the program runs ether: Set a break point at the point you want to inspect. Hover over the variable, or go to the debug panel and look at the variables listed in your current stackframe. Or add a watch (it is on the debug panel) and type the current name of the variable you want to monitor. Nice. I use Wingware, but this seems quite slick as well. Thanks for the link. Wingware IDE is amazing, however their licensing costs and limitations are horrific. Pycharms debugging is nowhere near are good as their debugging. However the price differences are night and day. Maybe someone should make a topic about IDE's.
... View more
11-20-2010
05:57 PM
|
0
|
0
|
328
|
POST
|
If your new to programming i suggest you look into esri's python libraries: arcpy(ArcGIS 10) or geoprocessor(Pre 10). Python is pretty easy to get into, and ESRI's python libraries are much more user friendly than ArcObjects. For programming with ArcObjects(ESRI's API), the two best documented languages are C# and VB.net. There is also Java and C++. If you really are new to programming and need to work with ArcGIS i suggest you stick with Python (python hangs out in the Geoprocessing forum).
... View more
11-19-2010
05:27 AM
|
0
|
0
|
152
|
POST
|
import arcpy
def recase():
tools = arcpy.listtools()
for tool_name in tools:
arcpy.globals()[tool_name.lower()] = arcpy.globals()[tool_name]
# add the case syntax
recase()
This should allow you to use lowercase syntax for arcpy. What you guys really need though is a code refactoring tool. To update your code to the new syntax. Most Python IDE's (IDLE, pywin32, notepad, notepad++ ARE NOT IDE's i suggest Pycharm (http://www.jetbrains.com/pycharm/)) can do stuff like this. Took me around 2 minutes for pycharm to refactor all of my scripts to the new arcpy syntax.
... View more
11-19-2010
04:23 AM
|
0
|
0
|
328
|
POST
|
Sounds crazy but you have to trust me here. If you are going to use storbinary, the file cant be opened in binary mode. I know what you are going to say but I just figured this out in the last couple weeks myself and it just doesnt work. fileList=[] for i in os.listdir(dir): if i.split('.')[1] == 'pdf' #if it ends in pdf fileList.append(i) #put it in the list ftp = FTP("XXX.XXX.XXX.XXX",username, password) #save a line and just put your U:P here. for i in fileList: file = open(i, "r") #open in normal read mode ftp.cwd("//data2//ftp//pub//download//maps//") ftp.storbinary('STOR %s' % i, os.path.join('V://GIS//Maps//County//11x17shd//',i)) file.close() ftp.quit() Your using storbinary wrong:
ftp = FTP("XXX.XXX.XXX.XXX",username, password) #save a line and just put your U:P here.
for i in fileList:
# don't use double //, this will rely on the server to properly handle it (most will)
# also don't use a trailing slash since VAX/RSIC will try the folder "maps/"
ftp.cwd("/data2/ftp/pub/download/maps")
# ftp.storbinary takes a FILE object not a path, python will automatically close the file
ftp.storbinary('STOR %s' % i, open(os.path.join('V://GIS//Maps//County//11x17shd//',i), "rb"))
ftp.quit()
storbinary takes a file like object as the second parameter. If you are transfering ANYTHING but a text file, you need to use binary otherwise you will be faced with data corruption: From Python Documentation: On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it�??ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn�??t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files. There are/can be tons of other little nitpicky issues relating to FTP, is old and was not standardized properly, alot of ftp servers have confilicting behaviour, (some servers use binary as a standard mode, others use A, etc etc). In general if you are going to try and transfer a binary file i suggest you manually change the server's connection type (ftplib is flaky about this):
ftp = FTP("XXX.XXX.XXX.XXX",username, password) #save a line and just put your U:P here.
for i in fileList:
ftp.cwd("/data2/ftp/pub/download/maps")
# Manually tell the server to change to binary mode:
# I indicates Binary,
# A indicates text
# There are a few other transfer modes however they are not used very often
# just print the return message, if its an error ftplib will raise an exception
print ftp.sendcmd("TYPE I")
# ftp.storbinary takes a FILE object not a path, python will automatically close the file
ftp.storbinary('STOR %s' % i, open(os.path.join('V://GIS//Maps//County//11x17shd//',i), "rb"))
ftp.quit()
... View more
11-16-2010
05:48 AM
|
0
|
0
|
4658
|
POST
|
Hello, I was wondering if anybody else has experienced this. I'm unable to simply set the workspace (or scratchworkspace). The error I get (in PythonWin/Idle/Executing from Toolbox) is: Traceback (most recent call last): File "C:\Projects\PythonScripts\Script34.py", line 13, in <module> gp.workspace = "C:/Test" AttributeError: Object: Environment <workspace> not found The python script is simple: import arcgisscripting gp = arcgisscripting.create(9.3) gp.workspace = "C:/Test" Things I've tried: - Various formats of the path based on ESRI doc - Checking the versions of Pthon/PythonWin/Numby (and reinstalling several times) - Running in safe mode - Looking at event viewer for error - Using procmon to see if something shows up there - Setting the license level (per others in the forum with same issue) - Creating the geoprocessor various ways from ESRI doc I'm really stuck ... any thoughts as to why this would happen would be MUCH appreciated. Most other properties and methods on the gp seem to work. Windows 7 ArcGIS Editor Single Use 9.3.1 SP2 Jess Do you see workspace listed, if you do : gp.listenviroments() Other wise what happens if you do this? import arcgisscripting
gp = arcgisscripting.create(9.3)
gp.clearenviroment("workspace")
print gp.workspace
gp.workspace = "C:/Test"
print gp.workspace
... View more
11-10-2010
09:37 PM
|
0
|
0
|
887
|
POST
|
So for the last week or so, i have been working on a project, and have been able to generate directions in the past. However now every time i try to generate directions i receive the error "Failed to Generate directions. Network dataset does not support driving directions." I did this several times, didn't work: http://resources.arcgis.com/content/kbase?fa=articleShow&d=29034 The only thing that seems to work i just nuking my entire network dataset and recreating everything (which i absolutely do not want to do). I have restarted ArcGIS, repaired ArcGIS, everything seems fine. I am guessing somehow my network dataset has become corrupt? I am using ArcGIS 10
... View more
11-10-2010
09:25 PM
|
0
|
13
|
5960
|
POST
|
print x is a syntax error in Python 3.0, so you're not future-proofing your code nearly as well as you think. Starting from 2.6, you can import print as a function from the future with from __future__ import print_function directive and use print as a 3.x style function across the board in your script. Also by doing the from __future__ import print_function, you add some amazing functionality in the form of completely breaking any chance of the 9.3 or less crowd from using your script (which is a big reality considering how many people probably still use < 10.0) If you reallllyyyyyy want to futureproof print (because esri is bound to go to python 3.0 any day now :o). Don't use it. Use logging. Or use sys.stdout.write(). Or even just use ESRI's AddMessage. Print is evil.
... View more
11-03-2010
06:16 PM
|
0
|
0
|
407
|
POST
|
Frank...unfortunately it doesn't print to other IDE's output...don't use console...too dark and gloomy and reminds me of the old DOS days Pycharm / Komodo python IDE's are fine with the message printing(I assume wingide is too) :cool: IDLE/pywin32 is not an IDE, they are mistakes. If you really want a decent Python IDE i honestly suggest looking into PyCharm (try it for 30 days, its also 50% off right now). If you don't want to spend money then i suggest NetBeans, or PyScripter. (I refuse to acknowledge pydev since its based off the horror that is known as eclipse). It's for that reason that I wrote my own message(), warning() and error() methods. In addition to logging to a text file, it's exactly 3 places that I need to change if I need print statements or not, not dozens of lines littered throughout the script. Most of the time I don't need print messages, but if I'm debugging in PyScripter or PythonWin (but not winpdb which runs the script in a separate console window from the GUI), I'll uncomment my print statement in each of the 3 methods. # Helper methods for writing messages, warnings and errors to the geoprocessor as well as a logfile
# By default, prepends a timestamp to the message; set second argument to 0 or False to disable
def message(strMessage, stamp = True):
global gp, logFile
if stamp == True:
strMessage = time.asctime() + " - " + strMessage
#print strMessage
gp.AddMessage(strMessage)
if logFile:
logFile.write(strMessage + "\n")
logFile.flush()
def warning(strMessage, stamp = True):
global gp, logFile
if stamp == True:
strMessage = time.asctime() + " - " + strMessage
#print strMessage
gp.AddWarning(strMessage)
if logFile:
logFile.write(strMessage + "\n")
logFile.flush()
def error(strMessage, stamp = True):
global gp, logFile
if stamp == True:
strMessage = time.asctime() + " - " + strMessage
#print strMessage
gp.AddError(strMessage)
if logFile:
logFile.write(strMessage + "\n")
logFile.flush() You should really look into the python logging, its wonderful: http://docs.python.org/library/logging.html However you need to create a gp friendly logger... heres an example: import logging
import sys
_GP_MESSAGE_DEFS = {
logging.CRITICAL : "AddError",
logging.ERROR : "AddError",
logging.WARNING : "AddWarning",
logging.INFO : "AddMessage",
logging.DEBUG : "AddMessage",
}
class GPHandler(logging.Handler):
"""
Geoprocessor friendly logging module
"""
def __init__(self, level=logging.NOTSET, gp=None):
self.gp = gp
logging.Handler.__init__(self, level)
def emit(self, record):
"""
Woop.
"""
message = self.format(record)
if self.gp:
source = gp
else:
source = __import__("arcpy")
# retrive the functor and call it with the message
getattr(source, _GP_MESSAGE_DEFS[record.levelno])(message)
_logger = logging.getLogger("test")
_logger.setLevel(logging.DEBUG)
# sadily i have no idea where this object type is located
if type(sys.stdout) != "<type 'geoprocessing sys.stdout object'>":
handler = logging.StreamHandler()
else:
# change for arc9.3
handler = GPHandler()
handler.setFormatter(logging.Formatter("%(asctime)10s | %(name)s | %(message)s",
"%Y%m%d %H:%M:%S"))
_logger.addHandler(handler)
_logger.debug("Message")
_logger.info("Info message")
_logger.warning("Warning")
_logger.error("error")
_logger.critical("error") This gives an output of:
20101103 21:36:45 | test | Message
20101103 21:36:52 | test | Info message
WARNING: 20101103 21:36:52 | test | Warning
ERROR: 20101103 21:36:52 | test | error
ERROR: 20101103 21:36:52 | test | error
If you run it from not within arcmap it goes to normal console streams. If you run it via arcgis it goes to the gp addmessage/etc.
... View more
11-03-2010
05:40 PM
|
0
|
0
|
407
|
Title | Kudos | Posted |
---|---|---|
1 | 11-03-2010 09:39 AM |
Online Status |
Offline
|
Date Last Visited |
11-11-2020
02:23 AM
|