Re: big single sql string

From: Eric Hill (eric_at_ijack.net)
Date: 11/07/03


Date: Fri, 7 Nov 2003 13:04:32 -0600


> Search the newsgroup archives for ClipToStringconst, that should find an
older
> message of mine that contains the source code for a little tool program.
It
> takes the content of the clipboard and converts it to a proper multiline
> string constant, which it puts back on the clipboard. I have this on the
IDEs
> Tools menu.

I needed this again (new computer install) and couldn't find it in Google.
It's in Tamraka FYI.

// SNIP HERE

That is the style I use. But you don't have to create this by hand (which
is a
bore, granted). Usually you will develop and test the SQL statement in some
database tool, like SQL*Plus or ISQL, or using the design-time database
functionality in the Delphi IDE. This leaves you with the statement as a
block
of plain text, which you can copy to the clipboard and then reformat
automatically with a little program to the syntax of a string constant. I
have
such a program sitting in my Tools menu (it is an external program since I
also use it from CodeWright, one could turn it into an IDE expert easily).

{ This program takes a set of lines from the clipboard, converts it
  to a multiline string constant and puts that back on the clipboard.
  Clipboard content

  A
  B
  C

  will be converted to

      'A '+
      'B '+
      'C '; }
Program ClipToStringconst;

Uses
  Windows, Classes, Sysutils, APIClipboard;

Const
  cIndent = ' '; // 4 spaces
  cSingleQuote = '''';
  EndChar : Array [Boolean] of Char = ('+',';');

Procedure Process;
  Var
    sl: TStringlist;
    i, max: Integer;
  Begin
    If ClipboardHasFormat( CF_TEXT ) Then Begin
      sl:= TStringlist.Create;
      Try
        sl.Text := ClipboardAsString;
        max := sl.count-1;
        For i:= 0 To max Do
          sl[i] :=
            cIndent
            + AnsiQuotedStr( TrimRight(sl[i])+#32, cSingleQuote )
            + EndChar[i = max];
        StringToClipboard( sl.Text );
      Finally
        sl.Free;
      End; { Finally }
    End
  End;

Begin
  try
    Process;
  except
    On E: Exception Do
      ShowException( E, ExceptAddr );
  end;
End.

{== Unit APIClipboard =================================================}
{: Clipboard access routines using only API functions
@author Dr. Peter Below
@desc Version 1.0 created 5 Juli 2000<BR>
        Current revision 1.0<BR>
        Last modified 5 Juli 2000<P>

This unit provides simply clipboard access routines that do not rely on
the VCL Clipbrd unit. That unit drags in Dialogs and Forms and a major
part of the VCL as a consequence, not appropriate for simple console
or non-form programs. This unit uses only API routines, the only VCL
units used are Classes (for exceptions and streams) and SysUtils.
}{=====================================================================}
Unit APIClipboard;

Interface
Uses Windows, Classes;

  Procedure StringToClipboard( Const S: String );
  Function ClipboardAsString: String;
  Procedure CopyDataToClipboard( fmt: DWORD; Const data; datasize: Integer;
                                 emptyClipboardFirst: Boolean = true );
  Procedure CopyDataFromClipboard( fmt: DWORD; S: TStream );
  Function ClipboardHasFormat( fmt: DWORD ): Boolean;

Implementation

Uses Sysutils;

Type
  {: This is an internal exception class used by the <see
unit=APIClipboard> }
  EclipboardError = class( Exception )
  public
    Constructor Create( Const msg: String );
  end;

resourcestring
  eSystemOutOfMemory =
    'could not allocate memory for clipboard data.';
  eLockfailed =
    'could not lock global memory handle.';
  eSetDataFailed =
    'could not copy data block to clipboard.';
  eCannotOpenClipboard =
    'could not open the clipboard.';
  eErrorTemplate =
    'APIClipboard: %s'#13#10+
    'System error code: %d'#13#10+
    'System error message: %s';

{-- EClipboardError.Create --------------------------------------------}
{: Creates a new EclipboardError object
@Param msg is the string to embed into the error message
@Precondition none
@Postcondition none
@desc Composes an error message that contains the passed message and the
  API error code and matching error message. The CreateFmt constructor
  inherited from the basic Exception class is used to do the work.
Created 5.7.2000 by P. Below
}{---------------------------------------------------------------------}
Constructor EClipboardError.Create( const msg: String );
  Begin { Create }
    CreateFmt( eErrorTemplate,
               [msg, GetLastError, SysErrorMessage(GetLastError)] );
  End; { EClipboardError.Create }

{-- DataToClipboard ---------------------------------------------------}
{: Copies a block of memory to the clipboard in a given format
@Param fmt is the clipboard format to use
@Param data is an untyped const parameter that addresses the data to copy
@Param datasize is the size of the data, in bytes
@Precondition The clipboard is already open. If not an EClipboardError
  will result. This precondition cannot be asserted, unfortunately.
@Postcondition Any previously exisiting data of this format will have
  been replaced by the new data, unless datasize was 0 or we run into an
  exception. In this case the clipboard will be unchanged.
@desc Uses API methods to allocate and lock a global memory block of
  approproate size, copies the data to it and submits the block to the
  clipboard. Any error on the way will raise an EClipboardError
  exception.<BR>
Created 5.7.2000 by P. Below
@Raises EClipboardError
}{---------------------------------------------------------------------}
Procedure DataToClipboard( fmt: DWORD; Const data; datasize: Integer );
  Var
    hMem: THandle;
    pMem: Pointer;
  Begin { DataToClipboard }
    If datasize <= 0 Then Exit;
    hMem := GlobalAlloc( GMEM_MOVEABLE or GMEM_SHARE or GMEM_ZEROINIT ,
                         datasize );
    If hmem = 0 Then
      raise EclipboardError.Create( eSystemOutOfMemory );

    pMem := GlobalLock( hMem );
    If pMem = Nil Then Begin
      GlobalFree( hMem );
      raise EclipboardError.Create( eLockFailed );
    End;

    Move( data, pMem^, datasize );
    GlobalUnlock( hMem );
    If SetClipboardData( fmt, hMem ) = 0 Then
      raise EClipboarderror( eSetDataFailed );
    // Note: API docs are unclear as to whether the memory block has
    // to be freed in case of failure. Since failure is unlikely here
    // lets blithly ignore this issue for now.
  End; { DataToClipboard }

{-- DataFromClipboard -------------------------------------------------}
{: Copies data from the clipboard into a stream
@Param fmt is the clipboard format to look for
@Param S is the stream to copy to
@precondition S <> nil
@postcondition If data was copied the streams position will have moved
@desc Tries to get a memory block for the requested clipboard format.
Nothing
  further is done if this fails (because the format is not available or
  the clipboard is not open, we treat neither as error here), otherwise
  the memory handle is locked and the data copied into the stream. <P>
  Note that we cannot determine the actual size of the data originally
  copied to the clipboard, only the allocated size of the memory block!
  Since GlobalAlloc works with a granularity of 32 bytes the block may be
  larger than required for the data and thus the stream may contain some
  spurious bytes at the end. There is no guarantee that these bytes will
  be 0. <P>
  If the memory handle obtained from the clipboard cannot be locked we
  raise an <see class=EClipboardError> exception.
Created 5.7.2000 by P. Below
@Raises EClipboardError
}{---------------------------------------------------------------------}
Procedure DataFromClipboard( fmt: DWORD; S: TStream );
  Var
    hMem: THandle;
    pMem: Pointer;
    datasize: DWORD;
  Begin { DataFromClipboard }
    Assert( Assigned( S ));
    hMem := GetClipboardData( fmt );
    If hMem <> 0 Then Begin
      datasize := GlobalSize( hMem );
      If datasize > 0 Then Begin
        pMem := GlobalLock( hMem );
        If pMem = Nil Then
          raise EclipboardError.Create( eLockFailed );
        try
          S.WriteBuffer( pMem^, datasize );
        finally
          GlobalUnlock( hMem );
        end;
      End;
    End;
  End; { DatafromClipboard }

{-- CopyDataToClipboard -----------------------------------------------}
{: Copies a block of memory to the clipboard in a given format
@Param fmt is the clipboard format to use
@Param data is an untyped const parameter that addresses the data to copy
@Param datasize is the size of the data, in bytes
@Param emptyClipboardFirst determines if the clipboard should be emptied,
  true by default
@Precondition The clipboard must not be open already
@Postcondition If emptyClipboardFirst is true all prior data will be
  cleared from the clipboard, even if datasize is <= 0. The clipboard
  is closed again.
@desc Tries to open the clipboard, empties it if required and then tries to
  copy the passed data to the clipboard. This operation is a NOP if
  datasize <= 0. If the clipboard cannot be opened a <see
class=EClipboardError>
  is raised.
Created 5.7.2000 by P. Below
@Raises EClipboardError
}{---------------------------------------------------------------------}
Procedure CopyDataToClipboard( fmt: DWORD; Const data; datasize: Integer;
                               emptyClipboardFirst: Boolean = true );
  Begin { CopyDataToClipboard }
    If OpenClipboard( 0 ) Then
      try
        If emptyClipboardFirst Then
          EmptyClipboard;
        DataToClipboard( fmt, data, datasize );
      finally
        CloseClipboard;
      end
    Else
      raise EclipboardError.Create( eCannotOpenClipboard );
  End; { CopyDataToClipboard }

{-- StringToClipboard -------------------------------------------------}
{: Copies a string to clipboard in CF_TEXT clipboard format
@Param S is the string to copy, it may be empty.
@Precondition The clipboard must not be open already.
@Postcondition Any prior clipboard content will be cleared, but only
  if S was not empty. The clipboard is closed again.
@desc Hands the brunt of the work off to <See routine=CopyDataToClipboard>,
  but only if S was not empty. Otherwise nothing is done at all.<BR>
Created 5.7.2000 by P. Below
@Raises EClipboardError
}{---------------------------------------------------------------------}
Procedure StringToClipboard( Const S: String );
  Begin
    If Length(S) > 0 Then
      CopyDataToClipboard( CF_TEXT, S[1], Length(S)+1);
  End; { StringToClipboard }

{-- CopyDataFromClipboard ---------------------------------------------}
{: Copies data from the clipboard into a stream
@Param fmt is the clipboard format to look for
@Param S is the stream to copy to
@Precondition S <> nil<P>
  The clipboard must not be open already.
@Postcondition If data was copied the streams position will have moved.
  The clipboard is closed again.
@desc Tries to open the clipboard, and then tries to
  copy the data to the passed stream. This operation is a NOP if
  the clipboard does not contain data in the requested format.
  If the clipboard cannot be opened a <see class=EClipboardError>
  is raised.
Created 5.7.2000 by P. Below
@Raises EClipboardError
}{---------------------------------------------------------------------}
Procedure CopyDataFromClipboard( fmt: DWORD; S: TStream );
  Begin { CopyDataFromClipboard }
    Assert( Assigned( S ));
    If OpenClipboard( 0 ) Then
      try
        DataFromClipboard( fmt , S );
      finally
        CloseClipboard;
      end
    Else
      raise EclipboardError.Create( eCannotOpenClipboard );
  End; { CopyDataFromClipboard }

{-- ClipboardAsString -------------------------------------------------}
{: Returns any text contained on the clipboard
@Returns the clipboards content if it contained something in CF_TEXT
  format, or an empty string.
@Precondition The clipboard must not be already open
@Postcondition The clipboard is closed.
@desc If the clipboard contains data in CF_TEXT format it is copied to a
  temp memory stream, zero-terminated for good measure and copied into
  the result string.
Created 5.7.2000 by P. Below
@Raises EClipboardError
}{---------------------------------------------------------------------}
Function ClipboardAsString: String;
  Const
    nullchar: Char = #0;
  Var
    ms: TMemoryStream;
  Begin { ClipboardAsString }
    If not IsClipboardFormatAvailable( CF_TEXT ) Then
      Result := EmptyStr
    Else Begin
      ms:= TMemoryStream.Create;
      try
        CopyDataFromClipboard( CF_TEXT , ms );
        ms.Seek( 0, soFromEnd );
        ms.WriteBuffer( nullChar, Sizeof( nullchar ));
        Result := Pchar( ms.Memory );
      finally
        ms.Free;
      end;
    End;
  End; { ClipboardAsString }

{-- ClipboardHasFormat ------------------------------------------------}
{: Checks if the clipboard contains data in the specified format
@Param fmt is the format to check for
@Returns true if the clipboard contains data in this format, false
  otherwise
@Precondition none
@Postcondition none
@desc This is a simple wrapper around an API function.
Created 5.7.2000 by P. Below
}{---------------------------------------------------------------------}
Function ClipboardHasFormat( fmt: DWORD ): Boolean;
  Begin { ClipboardHasFormat }
    Result := IsClipboardFormatAvailable( fmt );
  End; { ClipboardHasFormat }

end.



Relevant Pages

  • Re: Tk::Clipboard and other kinds of data
    ... data interpreted instead of literally inserted as a raw string into the ... The manual for X clipboard is here: ... when copying RTF from within Word by using Win32::Clipboard. ... the format 49370 had the expected RTF ...
    (comp.lang.perl.tk)
  • Re: problems pasting Adobe Illustrator graphics-->Inserting them, DISCOVERY
    ... the "Clipboard" is not involved in Insert>File... ... it seems to be no longer a vector format. ... it checks the timestamp on the picture file it finds ... But if the document content and sketches are co-evolving a lot --a very ...
    (microsoft.public.mac.office.word)
  • Re: OpenClipboard
    ... YOU ARE DECLARING LOCAL VARIABLES AND NAMING THEM AS IF THEY ... OpenClipboar, an assertion failure window is pop out, and the program ... buffer to the clipboard, but it doesn't mention what format it is in; ... why you are assuming that it is in CF_BITMAP format. ...
    (microsoft.public.vc.mfc)
  • Re: Cant paste images from Snapz Pro into Word 2008
    ... But I am trying to find out what is ON THE CLIPBOARD? ... The native format an application places on the clipboard when you copy will ... with the screen capture application Snapz Pro, ...
    (microsoft.public.mac.office.word)
  • Re: Disabled CommandBarButton image in Office 2000 is always empty
    ... When I create the DIBs I face the problem that Office 2000 apps show empty command bar buttons. ... // S_OFF2000_CLIP_IMAGE was filled earlier with the localized name of the clipboard format "Toolbar Button Face" ... // I tried adding only the Toolbar format or both - neither way the disabled button image was displayed ...
    (microsoft.public.office.developer.com.add_ins)