def GetUIObjectOf(self, hwndOwner, pidls, iid, inout):
     # delegate to the shell.
     assert len(pidls)==1, "oops - arent expecting more than one!"
     pidl = pidls[0]
     folder, child_pidl = self._GetFolderAndPIDLForPIDL(pidl)
     try:
         inout, ret = folder.GetUIObjectOf(hwndOwner, [child_pidl], iid,
                                           inout, iid)
     except pythoncom.com_error as exc:
         raise COMException(hresult=exc.hresult)
     return inout, ret
Example #2
0
    def GetName(self, dnt):
        if dnt == axdebug.DOCUMENTNAMETYPE_APPNODE:
            return self.codeBlock.GetDisplayName()
        elif dnt == axdebug.DOCUMENTNAMETYPE_TITLE:
            return self.codeBlock.GetDisplayName()


#		elif dnt==axdebug.DOCUMENTNAMETYPE_FILE_TAIL:
#		elif dnt==axdebug.DOCUMENTNAMETYPE_URL:
        else:
            raise COMException(scode=winerror.S_FALSE)
 def setrowheight(self, lnRow, lnHeight):
     lnReturn = None
     try:
         lnReturn = self.oXL.SetRowHeight(self.nCurrentSheet, lnRow,
                                          lnHeight)
     except:  # Another bare exception
         lcType, lcValue, lxTrace = sys.exc_info()
         self.local_except_handler(lcType, lcValue, lxTrace)
         raise COMException(description=("Python Error Occurred: " +
                                         repr(lcType)))
     return lnReturn
 def setcolumnwidth(self, lnCol, lnWidth):
     lnReturn = None
     try:
         lnReturn = self.oXL.SetColWidths(self.nCurrentSheet, lnCol,
                                          lnCol + 1, lnWidth)
     except:  # bare exception that stores the error condition and raises the necessary COM error
         lcType, lcValue, lxTrace = sys.exc_info()
         self.local_except_handler(lcType, lcValue, lxTrace)
         raise COMException(description=("Python Error Occurred: " +
                                         repr(lcType)))
     return lnReturn
  def SetCallbackThread(self):
    if self.__marshall_callback is None:
      raise COMException(desc='self.__marshall_callback is not initialized')

    self.__callback = win32com.client.Dispatch (
      pythoncom.CoGetInterfaceAndReleaseStream (
          self.__marshall_callback, 
          pythoncom.IID_IDispatch
      )
    )

    logging.info("SetCallbackThread Done")
Example #6
0
    def SetServiceInfo(self, serviceURI, serviceName):
        try:
            parts = serviceName.split('.')
            item = __import__('.'.join(parts[:-1]))
            for part in parts[1:]:
                item = getattr(item, part)

            self.client_type = item()
            self.client = make_service_client(str(serviceURI),
                                              self.client_type)
        except:
            raise COMException('No such service', winerror.DISP_E_BADVARTYPE)
Example #7
0
 def BindToObject(self, pidl, bc, iid):
     tail = pidl_to_item(pidl)
     # assert tail['is_folder'], "BindToObject should only be called on folders?"
     # *sob*
     # No point creating object just to have QI fail.
     if iid not in ShellFolder._com_interfaces_:
         raise COMException(hresult=winerror.E_NOTIMPL)
     child = ShellFolder(self.current_level+1)
     # hrmph - not sure what multiple PIDLs here mean?
     #        assert len(pidl)==1, pidl # expecting just relative child PIDL
     child.Initialize(self.pidl + pidl)
     return wrap(child, iid)
Example #8
0
 def dumb_query(self, word):
     word = str(word)
     if self.debug_mode_flag:
         try:
             return word + word
         except Exception as e:
             with open('../error_log.txt', 'w') as f:
                 f.truncate()
                 f.write(traceback.format_exc())
             raise COMException(desc=repr(e))
     else:
         return word + word
Example #9
0
 def GetParamCtz(self, moneda_id='DOL'):
     "Recuperar cotización de moneda"
     try:
         param = wsfex.get_param_ctz(self.client, self.Token, self.Sign,
                                     self.Cuit, moneda_id)
         return "%(fecha)s: %(ctz)s" % param
     except wsfex.FEXError, e:
         self.ErrCode = unicode(e.code)
         self.ErrMsg = unicode(e.msg)
         raise COMException(scode=vbObjectError + int(e.code),
                            desc=unicode(e.msg),
                            source="WebService")
Example #10
0
 def _dynamic_(self, name, lcid, wFlags, args):
     # Get the requested attribute from the string module.
     try:
         item = getattr(string, string.lower(name))
     except AttributeError:
         raise COMException("No attribute of that name", \
                            winerror.DISP_E_MEMBERNOTFOUND)
     # Massage the arguments...
     args = FixArgs(args)
     # VB will often make calls with wFlags set to
     # DISPATCH_METHOD | DISPATCH_PROPERTYGET, as the VB
     # syntax makes the distinction impossible to make.
     # Therefore, we also check the object being referenced is
     # in fact a Python function
     if (wFlags & pythoncom.DISPATCH_METHOD) and \
        type(item) in [types.BuiltinFunctionType, types.FunctionType]:
         return apply(item, args)
     elif wFlags & pythoncom.DISPATCH_PROPERTYGET:
         return item
     else:
         raise COMException("You can not set this attribute", 
                            winerror.DISP_E_BADVARTYPE)
Example #11
0
    def _dynamic_(self, name, lcid, wFlags, args):
        # Ensure any newly added items are available.
        self.engine.RegisterNewNamedItems()
        self.engine.ProcessNewNamedItemsConnections()
        if wFlags & pythoncom.INVOKE_FUNC:
            # attempt to call a function
            try:
                func = getattr(self.scriptNamespace, name)
                if not _is_callable(func):
                    raise AttributeError(name)  # Not a function.
                realArgs = []
                for arg in args:
                    if type(arg) == PyIDispatchType:
                        realArgs.append(Dispatch(arg))
                    else:
                        realArgs.append(arg)
                # xxx - todo - work out what code block to pass???
                return self.engine.ApplyInScriptedSection(
                    None, func, tuple(realArgs))

            except AttributeError:
                if not wFlags & pythoncom.DISPATCH_PROPERTYGET:
                    raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND)
        if wFlags & pythoncom.DISPATCH_PROPERTYGET:
            # attempt to get a property
            try:
                ret = getattr(self.scriptNamespace, name)
                if _is_callable(ret):
                    raise AttributeError(name)  # Not a property.
            except AttributeError:
                raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND)
            except COMException as instance:
                raise
            except:
                ret = self.engine.HandleException()
            return ret

        raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND)
Example #12
0
    def GetData(self, fe):
        ret_stg = None
        cf, target, aspect, index, tymed = fe
        if aspect & pythoncom.DVASPECT_CONTENT and tymed == pythoncom.TYMED_HGLOBAL:
            if cf == win32con.CF_TEXT:
                ret_stg = pythoncom.STGMEDIUM()
                ret_stg.set(pythoncom.TYMED_HGLOBAL, self.bytesval)
            elif cf == win32con.CF_UNICODETEXT:
                ret_stg = pythoncom.STGMEDIUM()
                ret_stg.set(pythoncom.TYMED_HGLOBAL, self.bytesval.decode("latin1"))

        if ret_stg is None:
            raise COMException(hresult=winerror.E_NOTIMPL)
        return ret_stg
    def writecellvalue(self, lpnrow, lpncol, lpxvalue, isformula=False):
        """
        Note that from the Visual FoxPro (or other COM client) side, the lpxvalue may be passed in native format.
        The conversions to a form required by the excel module are handled here.
        """
        try:
            if type(lpxvalue) == int:
                lxType = "N"
                lcTempVal = "%d" % lpxvalue

            elif type(lpxvalue) == float:
                lxType = "N"
                lcTempVal = "%f" % lpxvalue

            elif mTools.isunicode(lpxvalue):
                if isformula:
                    lxType = "F"
                    lcTempVal = lpxvalue
                else:
                    lxType = "S"
                    lcTempVal = lpxvalue

            elif type(lpxvalue).__name__ == "time":
                lxType = "D"
                # Note that the win32 module makes an automatic conversion to the PyTime type object, which
                # is found only here.  This solution comes from online wikis and is NOT documented in the Py Win32 book.
                lcTempVal = lpxvalue.Format("%Y") + lpxvalue.Format("%m") + lpxvalue.Format("%d") + \
                            lpxvalue.Format("%H") + lpxvalue.Format("%M") + lpxvalue.Format("%S")
                if lcTempVal.endswith("000000"):
                    lcTempVal = lcTempVal[
                        0:8]  # This is plain date, no time portion.

            elif type(lpxvalue) == bool:
                lxType = "L"
                lcTempVal = ("T" if lpxvalue else "F")
            else:
                lxType = "X"
                lcTempVal = ""
            self.cLastType = lxType
            lcTempVal = lcTempVal.strip("\x00 ")
            lnresult = self.oXL.WriteCellValue(self.nCurrentSheet, lpnrow,
                                               lpncol, lcTempVal, lxType)
            if lnresult == 0:
                self.cErrorMessage = self.oXL.GetErrorMessage()
        except:  # bare exception that stores the error condition and raises the necessary COM error
            lcType, lcValue, lxTrace = sys.exc_info()
            self.local_except_handler(lcType, lcValue, lxTrace)
            raise COMException(description=("Python Error Occurred: " +
                                            repr(lcType)))
        return lnresult
Example #14
0
 def CreateViewObject(self, hwnd, iid):
     if iid == shell.IID_IShellView:
         com_folder = wrap(self)
         return shell.SHCreateShellFolderView(com_folder)
     elif iid == shell.IID_ICategoryProvider:
         return wrap(ViewCategoryProvider(self))
     elif iid == shell.IID_IContextMenu:
         ws = wrap(self)
         dcm = (hwnd, None, self.pidl, ws, None)
         return shell.SHCreateDefaultContextMenu(dcm, iid)
     elif iid == shell.IID_IExplorerCommandProvider:
         return wrap(ExplorerCommandProvider())
     else:
         raise COMException(hresult=winerror.E_NOINTERFACE)
Example #15
0
  def ServerStart(self, CallbackObject):
    """Excel has just created us... We take its callback for later, and set up shop."""
    self.IsAlive = self.ALIVE

    if CallbackObject is None:
      raise COMException(desc='Excel did not provide a callback')
      
    # Need to "cast" the raw PyIDispatch object to the IRTDUpdateEvent interface
    IRTDUpdateEventKlass = win32com.client.CLSIDToClass.GetClass('{A43788C1-D91B-11D3-8F39-00C04F3651B8}')
    self.__callback = IRTDUpdateEventKlass(CallbackObject)
    
    self.OnServerStart()

    return self.IsAlive
Example #16
0
    def _dynamic_(self, name, lcid, wFlags, args):
        # Look up the requested method.  First, check to see if the
        # method is present on ourself (utility functions), then
        # check to see if it exists on the client service.
        is_service_method = False
        item = getattr(self, name, None)
        if item is None and hasattr(self, 'client'):
            item = getattr(self.client, name)
            is_service_method = True

        if item is None:
            raise COMException('No attribute of that name.',
                               winerror.DISP_E_MEMBERNOTFOUND)

        # Figure out what parameters this web service call accepts,
        # and what it returns, so that we can properly wrap the objects
        # on the way in and unwrap them on the way out.
        if is_service_method:
            all_methods = self.client_type.methods()
            method_descriptor = [
                method for method in all_methods if method.name == name
            ][0]
            return_type = method_descriptor.outMessage.params[0][1]
            parameter_types = [
                parameter[1]
                for parameter in method_descriptor.inMessage.params
            ]

            # Now that we have this data, go ahead and unwrap any
            # wrapped parameters recursively.
            newargs = []
            for param_type, param in zip(parameter_types, args):
                if (hasattr(param_type, '__bases__')
                        and ClassSerializer in param_type.__bases__):
                    param = unwrap_complex_type(param, param_type)
                elif param_type is DateTime:
                    param = coerce_date_time(param)
                newargs.append(param)
            args = newargs

        # Call the supplied method
        result = apply(item, args)

        # Now wrap the return value, recursively.
        if isinstance(result, ClassSerializer):
            result = wrap_complex_type(result, return_type)

        # Return our data
        return result
 def setprintaspect(self, lpcHow="PORTRAIT"):
     """
     Sets the output printing format to either "PORTRAIT" or "LANDSCAPE".  Pass the string as the second
     parameter.  If unrecognized value is passed, defaults to PORTRAIT.  Returns 1 if the lnSheet value is
     recognized as a valid work sheet index, otherwise returns 0.
     """
     lnReturn = 0
     try:
         lnReturn = self.oXL.SetPrintAspect(self.nCurrentSheet, lpcHow)
     except:
         lcType, lcValue, lxTrace = sys.exc_info()
         self.local_except_handler(lcType, lcValue, lxTrace)
         raise COMException(description=("Python Error Occurred: " +
                                         repr(lcType)))
     return lnReturn
 def getsheetstats(self):
     """
     Get row and column counts, etc. from the currently select worksheet.  See the ExcelTools documentation
     for all the details.
     :return: A tuple of values.
     """
     try:
         lcSheet, lnR0, lnRn, lnC0, lnCn = self.oXL.GetSheetStats(
             self.nCurrentSheet)
     except:  # bare exception that stores the error condition and raises the necessary COM error
         lcType, lcValue, lxTrace = sys.exc_info()
         self.local_except_handler(lcType, lcValue, lxTrace)
         raise COMException(description=("Python Error Occurred: " +
                                         repr(lcType)))
     return [lcSheet, lnR0, lnRn, lnC0, lnCn]
 def setcellcolor(self, lnFromRow, lnToRow, lnFromCol, lnToCol,
                  lcColorCode):
     try:
         if lcColorCode in xlColor:
             lnReturn = self.oXL.SetCellColor(self.nCurrentSheet, lnFromRow,
                                              lnToRow, lnFromCol, lnToCol,
                                              xlColor[lcColorCode])
         else:
             lnReturn = 0
     except:  # bare exception that stores the error condition and raises the necessary COM error
         lcType, lcValue, lxTrace = sys.exc_info()
         self.local_except_handler(lcType, lcValue, lxTrace)
         raise COMException(description=("Python Error Occurred: " +
                                         repr(lcType)))
     return lnReturn
Example #20
0
 def GetDetailsOf(self, pidl, iCol):
     key = self.MapColumnToSCID(iCol);
     if pidl is None:
         data = [(commctrl.LVCFMT_LEFT, "Name"),
                 (commctrl.LVCFMT_CENTER, "Size"),
                 (commctrl.LVCFMT_CENTER, "Sides"),
                 (commctrl.LVCFMT_CENTER, "Level"),]
         if iCol >= len(data):
             raise COMException(hresult=winerror.E_FAIL)
         fmt, val = data[iCol]
     else:
         fmt = 0 # ?
         val = self._GetColumnDisplayName(pidl, key)
     cxChar = 24
     return fmt, cxChar, val
Example #21
0
    def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider):
        if dispid == 0:  # item
            l = len(args)
            if l < 1:
                raise COMException(desc="not enough parameters",
                                   scode=winerror.DISP_E_BADPARAMCOUNT)

            key = args[0]
            if type(key) == UnicodeType:
                pass
            elif type(key) == StringType:
                key = pywintypes.Unicode(key)
            else:
                ### the nArgErr thing should be 0-based, not reversed... sigh
                raise COMException(desc="Key must be a string",
                                   scode=winerror.DISP_E_TYPEMISMATCH)

            key = key.lower()

            if wFlags & (DISPATCH_METHOD | DISPATCH_PROPERTYGET):
                if l > 1:
                    raise COMException(scode=winerror.DISP_E_BADPARAMCOUNT)
                try:
                    return self._obj_[key]
                except KeyError:
                    return None  # unknown keys return None (VT_NULL)

            if l <> 2:
                raise COMException(scode=winerror.DISP_E_BADPARAMCOUNT)
            if args[1] is None:
                # delete a key when None is assigned to it
                try:
                    del self._obj_[key]
                except KeyError:
                    pass
            else:
                self._obj_[key] = args[1]
            return S_OK

        if dispid == 1:  # count
            if not wFlags & DISPATCH_PROPERTYGET:
                raise COMException(
                    scode=winerror.DISP_E_MEMBERNOTFOUND)  # not found
            if len(args) != 0:
                raise COMException(scode=winerror.DISP_E_BADPARAMCOUNT)
            return len(self._obj_)

        if dispid == pythoncom.DISPID_NEWENUM:
            return util.NewEnum(self._obj_.keys())

        raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND)
Example #22
0
    def ServerStart(self, CallbackObject):
        """Excel has just created us... We take its callback for later, and set up shop."""
        self.IsAlive = self.ALIVE

        if CallbackObject is None:
            raise COMException(desc='Excel did not provide a callback')

        # EXCELTYPES_MODIFICATION
        # Need to "cast" the raw PyIDispatch object to the IRTDUpdateEvent interface
        self.__callback = CallbackObject.QueryInterface(
            exceltypes.IID_IRTDUpdateEvent)

        self.OnServerStart()

        return self.IsAlive
Example #23
0
 def GetLastID(self):
     "Recuperar último número de transacción (ID)"
     try:
         # limpio errores
         self.Exception = self.Traceback = ""
         self.ErrCode = self.ErrMsg = ""
         id, events = wsbfe.get_last_id(self.client, self.Token, self.Sign,
                                        self.Cuit)
         return id
     except wsbfe.BFEError, e:
         self.ErrCode = unicode(e.code)
         self.ErrMsg = unicode(e.msg)
         if self.LanzarExcepciones:
             raise COMException(scode=vbObjectError + int(e.code),
                                desc=unicode(e.msg),
                                source="WebService")
Example #24
0
    def GetData(self, fe):
        ret_stg = None
        cf, target, aspect, index, tymed = fe
        if aspect & pythoncom.DVASPECT_CONTENT and \
                tymed == pythoncom.TYMED_HGLOBAL:
            if cf == win32con.CF_TEXT:
                ret_stg = pythoncom.STGMEDIUM()
                # ensure always 'bytes' by encoding string.
                ret_stg.set(pythoncom.TYMED_HGLOBAL, str2bytes(self.strval))
            elif cf == win32con.CF_UNICODETEXT:
                ret_stg = pythoncom.STGMEDIUM()
                ret_stg.set(pythoncom.TYMED_HGLOBAL, str(self.strval))

        if ret_stg is None:
            raise COMException(hresult=winerror.E_NOTIMPL)
        return ret_stg
 def setpapersize(self, lpcType):
     """
     Determines the paper size for any printed output.  This overrides the printer setting based on Excel
     typical operation.  The lpcType value may be one of three text values: LETTER, LEGAL, and A3.  If the text
     string is unrecognized, the default will be set to LETTER.  Returns 1 if the lnSheet value is recognized as a
     valid work sheet index, otherwise returns 0.
     """
     lnReturn = 0
     try:
         lnReturn = self.oXL.SetPaperSize(self.nCurrentSheet, lpcType)
     except:
         lcType, lcValue, lxTrace = sys.exc_info()
         self.local_except_handler(lcType, lcValue, lxTrace)
         raise COMException(description=("Python Error Occurred: " +
                                         repr(lcType)))
     return lnReturn
 def setprintarea(self, lnFromRow, lnToRow, lnFromCol, lnToCol):
     """
     Defines the Excel "print area" or portion of the worksheet that is "printable".  Returns 1 if the lnSheet
     value is recognized as a valid work sheet index, otherwise returns 0. Note that row and column counters
     are 0 (zero) based.
     """
     lnReturn = 0
     try:
         lnReturn = self.oXL.SetPrintArea(self.nCurrentSheet, lnFromRow,
                                          lnToRow, lnFromCol, lnToCol)
     except:
         lcType, lcValue, lxTrace = sys.exc_info()
         self.local_except_handler(lcType, lcValue, lxTrace)
         raise COMException(description=("Python Error Occurred: " +
                                         repr(lcType)))
     return lnReturn
Example #27
0
 def GetLastCMP(self, tipo_cbte, punto_vta):
     "Recuperar último número de comprobante emitido"
     try:
         # limpio errores
         self.Exception = self.Traceback = ""
         self.ErrCode = self.ErrMsg = ""
         cbte_nro, cbte_fecha, events = wsbfe.get_last_cmp(
             self.client, self.Token, self.Sign, self.Cuit, tipo_cbte,
             punto_vta)
         return cbte_nro
     except wsbfe.BFEError, e:
         self.ErrCode = unicode(e.code)
         self.ErrMsg = unicode(e.msg)
         if self.LanzarExcepciones:
             raise COMException(scode=vbObjectError + int(e.code),
                                desc=unicode(e.msg),
                                source="WebService")
 def setpagemargins(self, lcWhich, lnWidth):
     """
     Defines the printed output page margins for the specified worksheet.  The values to pass in lcWhich
     are TOP, BOTTOM, LEFT, RIGHT, or ALL.  Width of the margins is affected based on that selection and should
     be specified in inches as a decimal fraction.  Returns 1 if the lnSheet value is recognized as a valid
     work sheet index, otherwise returns 0.
     """
     lnReturn = 0
     try:
         lnReturn = self.oXL.SetPageMargins(self.nCurrentSheet, lcWhich,
                                            lnWidth)
     except:
         lcType, lcValue, lxTrace = sys.exc_info()
         self.local_except_handler(lcType, lcValue, lxTrace)
         raise COMException(description=("Python Error Occurred: " +
                                         repr(lcType)))
     return lnReturn
Example #29
0
 def ConnectData(self, TopicID, Strings, GetNewValues):
   """Creates a new topic out of the Strings excel gives us."""
   try:
     self.topics[TopicID] = self.CreateTopic(Strings)
   except Exception as why:
     raise COMException(desc=str(why))
   GetNewValues = True
   result = self.topics[TopicID]
   if result is None:
     result = "# %s: Waiting for update" % self.__class__.__name__
   else:
     result = result.GetValue()
     
   # fire out internal event...
   self.OnConnectData(TopicID)
     
   # GetNewValues as per interface is ByRef, so we need to pass it back too.
   return result, GetNewValues
Example #30
0
 def GetCategoryForSCID(self, scid):
     if scid==PKEY_ItemNameDisplay:
         guid = CAT_GUID_NAME
     elif scid == PKEY_Sample_AreaSize:
         guid = CAT_GUID_SIZE
     elif scid == PKEY_Sample_NumberOfSides:
         guid = CAT_GUID_SIDES
     elif scid == PKEY_Sample_DirectoryLevel:
         guid = CAT_GUID_LEVEL
     elif scid == pythoncom.IID_NULL:
         # This can be called with a NULL
         # format ID. This will happen if you have a category,
         # not based on a column, that gets stored in the
         # property bag. When a return is made to this item,
         # it will call this function with a NULL format id.
         guid = CAT_GUID_VALUE
     else:
         raise COMException(hresult=winerror.E_INVALIDARG)
     return guid