home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_win32com_demos_trybag.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  2.0 KB  |  75 lines

  1. import pythoncom
  2. from win32com.server import util
  3. from win32com.server import exception
  4.  
  5. VT_EMPTY = pythoncom.VT_EMPTY
  6.  
  7. class Bag:
  8.   _public_methods_ = [ 'Read', 'Write' ]
  9.   _com_interfaces_ = [ pythoncom.IID_IPropertyBag ]
  10.  
  11.   def __init__(self):
  12.     self.data = { }
  13.  
  14.   def Read(self, propName, varType, errorLog):
  15.     print "read: name=", propName, "type=", varType
  16.     if not self.data.has_key(propName):
  17.       if errorLog:
  18.         hr = 0x80070057
  19.         errorLog.AddError(propName, (0, "Bag.Read", "no such item", None, 0, hr))
  20.       raise exception.Exception(scode=hr)
  21.     return self.data[propName]
  22.  
  23.   def Write(self, propName, value):
  24.     print "write: name=", propName, "value=", value
  25.     self.data[propName] = value
  26.  
  27.  
  28. class Target:
  29.   _public_methods_ = [ 'GetClassID', 'InitNew', 'Load', 'Save' ]
  30.   _com_interfaces_ = [ pythoncom.IID_IPersist,
  31.                        pythoncom.IID_IPersistPropertyBag ]
  32.  
  33.   def GetClassID(self):
  34.     raise exception.Exception(scode=0x80004005)    # E_FAIL
  35.  
  36.   def InitNew(self):
  37.     pass
  38.  
  39.   def Load(self, bag, log):
  40.     print bag.Read('prop1', VT_EMPTY, log)
  41.     print bag.Read('prop2', VT_EMPTY, log)
  42.     try:
  43.       print bag.Read('prop3', VT_EMPTY, log)
  44.     except exception.Exception:
  45.       pass
  46.  
  47.   def Save(self, bag, clearDirty, saveAllProps):
  48.     bag.Write('prop1', 'prop1.hello')
  49.     bag.Write('prop2', 'prop2.there')
  50.  
  51. class Log:
  52.   _public_methods_ = [ 'AddError' ]
  53.   _com_interfaces_ = [ pythoncom.IID_IErrorLog ]
  54.  
  55.   def AddError(self, propName, excepInfo):
  56.     print "error: propName=", propName, "error=", excepInfo
  57.  
  58. def test():
  59.   bag = Bag()
  60.   target = Target()
  61.   log = Log()
  62.  
  63.   target.Save(bag, 1, 1)
  64.   target.Load(bag, log)
  65.  
  66.   comBag = util.wrap(bag, pythoncom.IID_IPropertyBag)
  67.   comTarget = util.wrap(target, pythoncom.IID_IPersistPropertyBag)
  68.   comLog = util.wrap(log, pythoncom.IID_IErrorLog)
  69.  
  70.   comTarget.Save(comBag, 1, 1)
  71.   comTarget.Load(comBag, comLog)
  72.  
  73. if __name__ == '__main__':
  74.   test()
  75.