FileExtract - Can anyone spot the deliberate mistake please?

Basically, the program includes my add-in along with SAPbouiCOM.dll both embedded.
The code below now extracts SAPbouiCOM.dll perfectly, but my program is condensed to 1Kb!!!
I bet there's something obvious here, but I just can't spot it!
Private Sub ExtractFile(ByVal path As String)
        Try
            Dim AddonExeFile As IO.FileStream
            Dim thisExe As System.Reflection.Assembly
            thisExe = System.Reflection.Assembly.GetExecutingAssembly()
            Dim sTargetPath As String
            Dim sSourcePath As String
            Dim sTargetPathdll As String
            Dim sFile As System.IO.Stream
            sTargetPath = path & "\" & sAddonName & ".exe"
            sSourcePath = path & "\" & sAddonName & ".tmp"
            sTargetPathdll = path & "\" & "Interop.SAPbouiCOM.dll"
            For Each resourceName As String In thisExe.GetManifestResourceNames()
                sFile = thisExe.GetManifestResourceStream(resourceName)
                If LCase(resourceName) <> LCase("Addoninstaller.Interop.SAPbouiCOM.dll") Then
                    ' Create a tmp file first, after file is extracted change to exe
                    If IO.File.Exists(sSourcePath) Then
                        IO.File.Delete(sSourcePath)
                    End If
                    AddonExeFile = IO.File.Create(sSourcePath)
                    Dim buffer() As Byte
                    ReDim buffer(sFile.Length)
                    sFile.Read(buffer, 0, sFile.Length)
                    AddonExeFile.Write(buffer, 0, sFile.Length)
                    AddonExeFile.Close()
                    If IO.File.Exists(sTargetPath) Then
                        IO.File.Delete(sTargetPath)
                    End If
                    ' Change file extension to exe
                    IO.File.Move(sSourcePath, sTargetPath)
                Else
                    ' Create a tmp file first, after file is extracted change to exe
                    AddonExeFile = IO.File.Create(sTargetPathdll)
                    Dim buffer2() As Byte
                    ReDim buffer2(sFile.Length)
                    sFile.Read(buffer2, 0, sFile.Length)
                    AddonExeFile.Write(buffer2, 0, sFile.Length)
                    AddonExeFile.Close()
                End If
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

Hi Daniel,
I'm a bit lazy - so I'm not going to go through your code -> I'll give you a code snippet I use (it is basically the same as in the SAP example)
"in someSub"
' Extract exe to installation folder
            ExtractFile(strDest, "YourAddonName", "exe")
            ' Extract dlls to installation folder
            ExtractFile(strDest, "Interop.SAPbobsCOM", "dll")
"end someSub"
' This function extracts the given add-on into the path specified
    Private Sub ExtractFile(ByVal path As String, ByVal FName As String, ByVal ext As String)
        Dim AddonExTFile As IO.FileStream
        Dim thisExT As System.Reflection.Assembly
        Dim file As System.IO.Stream
        Dim sTargetPath = path & "\" & FName & "." & ext
        Dim sSourcePath = path & "\" & FName & ".tmp"
        Try
            Try
                thisExT = System.Reflection.Assembly.GetExecutingAssembly()
                file = thisExT.GetManifestResourceStream(sInstallName & "." & FName & "." & ext)
                ' Create a tmp file first, after file is extracted change to ext
                If IO.File.Exists(sSourcePath) Then
                    IO.File.Delete(sSourcePath)
                End If
                AddonExTFile = IO.File.Create(sSourcePath)
                Dim buffer() As Byte
                ReDim buffer(file.Length)
                file.Read(buffer, 0, file.Length)
                AddonExTFile.Write(buffer, 0, file.Length)
                AddonExTFile.Close()
                If IO.File.Exists(sTargetPath) Then
                    IO.File.Delete(sTargetPath)
                End If
                ' Change file extension to exe
                IO.File.Move(sSourcePath, sTargetPath)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        Finally
            AddonExTFile = Nothing
            thisExT = Nothing
            file = Nothing
            sTargetPath = ""
            sSourcePath = ""
            GC.Collect()
        End Try
    End Sub
AND remenber to include your exe and dll as embedded resources in your Add-On installer

Similar Messages

  • Can ANYONE spot the memory leak??

    Hi, I have some code here, and there is a SERIOUS memory leak. Basically, I realized the leak was there when a report tried to execute this 100,000+ times and it bogged the system down to a crawl. Can anyone spot the leak? I will explain the variables below the code:
    char* getDescription(char* chFlag, char* chDEID, char* chKey, int keysize)
    //first, we need to allocate new Byte arrays....
    jbyteArray JchFlag = (*env1)->NewByteArray(env1,1);
    jbyteArray JchDEID = (*env1)->NewByteArray(env1,2);
    jbyteArray JchKey = (*env1)->NewByteArray(env1,40);
    //next, we need to put the correct info in those byte arrays....
    (*env1)->SetByteArrayRegion(env1,JchFlag,0,1,(jbyte*)chFlag); (*env1)->SetByteArrayRegion(env1,JchDEID,0,2,(jbyte*)chDEID); (*env1)->SetByteArrayRegion(env1,JchKey,0,40,(jbyte*)chKey);
    getDescriptionID =(*env1)->GetMethodID(env1,myjclass,"getDescription","([B[B[BI)Ljava/lang/String;");
    result              =(jstring)((*env1)->CallObjectMethod(env1,myjobject,getDescriptionID,JchFlag,JchDEID,JchKey,keysize))  ;   
        returnvalue = NULL;
        if(result == NULL)
           strcpy(holder1, "**********Error Finding Description**********");
        else { //now, we convert the jstring to a char *, so we can return the proper type...                       
                returnvalue=(char*)((*env1)->GetStringUTFChars(env1,result,&isCopy)) ;
                strcpy(holder1,returnvalue);           
                if(isCopy == JNI_TRUE)                    
                    (*env1)->ReleaseStringUTFChars(env1,result,returnvalue);                         
    (*env1)->DeleteLocalRef(env1,result);
    return holder1;
    //return description;
    }//end getDescription function
    -myjclass is global, it gets its value in the initialization.
    -any variables that are not declared in this function are, of course, globally defined.

    Hello Friends,
    I had also tried to use the ReleaseStringUTFChars after making the check of whether it does a copy or not.
    For me in Windows, it works fine most of the time. But when I go on increasing the no. of strings in a Vector of objects to more than 500 or something , then it occasionally fails.
    Just before ReleaseStringUTF, I do have the copied string in char* .
    Soon after Releasing, I do get a junk in the character array.
    I dont know why it happens like this.
    Please advice.
    Everyone suggest ReleaseStringUTF.
    But why it fails in Windows.
    And any one know about how it will behave in Alpha.
    It totally fails in Alpha.
    I could not get the string at all.
    Please help
    LathaDhamo

  • Can anyone spot the problem with this coding??

    can anyone spot this problem with my program. it keeps saying
    "missing return statement } " with a little arrow beneath the bracket.
    many thanks
    public class Game extends GameInterface
         GameInterface gameInt = new GameInterface();
         String boardString;
         // final static char NOUGHT='O', CROSS='X';
         private int square = 0;
         Player player1 = new Player();
         Player player2 = new Player();
         String firstPlayer, secondPlayer;
         public Game() // Constructor
              boardString = "0123456789";
    public boolean initialise(boolean first)
                   gameInt.setPlayerNames(player1,player2);
              MyPrint.myPrintln("Player one name is " + player1.getName());
              MyPrint.myPrintln("Player two name is " + player2.getName());
              String P1 = player1.getName();
              String P2 = player2.getName();
    }

    It means you declare your method to return something, but you don't actually return anything.

  • Can anyone spot the syntax error of db delete?

    Hi
    I'm trying to get a database delete statement to work for a relations table - it just has studentId and courseId as foreign keys which make up a joint primary key.
    The line is
    db.update("delete from enrollments2 where (studentsid = '" + getStudentId() + "," + " coursesid = " +  getCourseId() + "')");The error is
    ERROR: invalid input syntax for integer: "78, coursesid = 75"Somehow I am putting non integer into an integer... I can't seem to spot the mistake though. Any help would be appreciated.

    The correct syntax I should mention was
    db.update("delete from enrollments2 where (studentsid = '" + getStudentId() + "'and coursesid = '" +  getCourseId() + "')");I'll leave that in for the time being and try to come back to it tonight... its on my todo list.
    Thanks for the snippet by the way, it always saves a lot of time when someone provides a useful snippet towards a solution. I hadn't heard of prepared statements until now too, interesting.
    Message was edited by:
    occams_razor
    -->> missed a 2 out there as enrollments2 is my test case

  • Can anyone spot the problem?

    Hey i've been workin on an applet which accepts two boolean equations with 3 variables and returns an answer telling if they are logically equal. When it comes to the PLUS and MINUS cases the program works fine. However in the TIMES and DIVIDE cases it returns at least one wrong answer, despite the fact i'm using the logical AND gate. For example if i enter x*y the program returns
    answer 1 = O, when (x,y)=(0,0)
    answer 2 = 1, when (x,y)=(1,0)
    answer 3 = O, when (x,y)=(0,1)
    answer 4 = 1, when (x,y)=(1,1)
    were answer 2 is wrong using an AND gate.
    Here is the for loop which passes the values
                 for (int y = 0; y < 2; y++)
                   for (int x = 0; x < 2; x++)
                       int d = MyParser.answer(x, y);
                       int doub = MyParser2.answer(x, y);
                       String eq = "";
                       if (d == doub) {
                         equal++;
                         count++;
                         eq = "equal\t";
                       else {
                         count++;
                         eq = "not equal";
                       tb1.append("\nAnswer was " + d + "\t " + eq + " " +
                                  "\t answer 2 was " + doub);
                   }and here is the code for the parser
    package Applet1;
    public final class Parse
      public Parse (String equation)
        parse (equation);
       public int answer(int x,int y, int z)
         return this.value(x,y,z);
       public int answer(int x,int y)
         return this.value(x, y);
       public int answer(int x)
         return this.value(x);
       public int value(int x)
         return val(x, 0, 0);
       public int value(int x, int y)
         return val(x, y, 0);
       public int value(int x, int y, int z)
         return val(x, y, z);
       public String getEquation()
        return equation;
      private String equation;
      private byte[] code;
      private int[] stack;
      private int[] constant;
      private int pos = 0, constantCt = 0, codeSize = 0;
      private static final byte
      PLUS = -1,   MINUS = -2,   TIMES = -3,   DIVIDE = -4,
      UNARYMINUS = -5, VARIABLEX = -6, VARIABLEY = -7, VARIABLEZ = -8;
      private char next()
        if (pos >= equation.length())
        return 0;
        else
        return equation.charAt(pos);
      private void skip()
        while (Character.isWhitespace(next()))
        pos++;
      private int val(int variableX, int variableY, int variableZ)
       try
         int top = 0;
         for (int i=0; i < codeSize; i++)
           if (code[i] >= 0)
             stack [top++] = constant [code ];
    else if (code [i] >= UNARYMINUS)
    int y = stack[--top];
    int x = stack[--top];
    int w;
    int ans = (int) Double.NaN;
    switch (code[i])
    case PLUS: ans = x | y;
    break;
    case MINUS: ans = (x) & (~y);
    break;
    case TIMES: ans = x & y;
    break;
    case DIVIDE: ans = x & ~y;
    break;
    if (Double.isNaN(ans))
    return ans;
    stack [top++] = ans;
    else if (code[i] == VARIABLEX)
    stack [top++] = variableX;
    else if (code[i] == VARIABLEY)
    stack [top++] = variableY;
    else if (code[i] == VARIABLEZ)
    stack [top++] = variableZ;
    catch (Exception e)
    double b = Double.NaN;
    int i = (int) b;
    return i;
    double d2;
    if (Double.isInfinite(stack[0]))
    d2 = Double.NaN;
    int i2 = (int) d2;
    return i2;
    }else
    return stack[0];
    private void error (String message)
    throw new IllegalArgumentException
    ("Parse error: " + message + "\n");
    private int stackUse()
    int s = 0;
    int max = 0;
    for (int i = 0; i < codeSize; i++)
    if (code[i] >= 0 || code [i] == VARIABLEX || code[i] == VARIABLEY || code[i] == VARIABLEZ)
    s++;
    if (s > max)
    max = s;
    } else if (code[i] >= UNARYMINUS)
    s--;
    return max;
    private void parse (String equation)
    if (equation == null || equation.trim().equals(""))
    error ("No Data to be parsed");
    this.equation = equation;
    code = new byte[equation.length()];
    constant = new int [equation.length()];
    parseExpress();
    skip();
    int stackSize = stackUse();
    stack = new int[stackSize];
    byte[] c = new byte[codeSize];
    System.arraycopy(code,0,c,0,codeSize);
    code = c;
    int[] A = new int[constantCt];
    System.arraycopy(constant,0,A,0,constantCt);
    constant = A;
    private void parseExpress()
    boolean neg = false;
    skip();
    parseVaries();
    if (neg)
    code[codeSize++] = UNARYMINUS;
    skip();
    while (next() == '+' || next() == '-')
    char op = next();
    pos++;
    parseTerm();
    if (op =='+')
    code[codeSize++] = PLUS;
    else
    code[codeSize++] = MINUS;
    skip();
    private void parseTerm()
    parseFactor();
    skip();
    while (next() == '*' || next() == '/')
    char op = next();
    pos++;
    parseFactor();
    code[codeSize++] = (op == '*')? PLUS:MINUS;
    skip();
    private void parseFactor()
    parseVaries();
    skip();
    while (next() == '^')
    pos++;
    parseVaries();
    code[codeSize++] = UNARYMINUS;
    skip();
    private void parseVaries()
    skip();
    char ch = next();
    if (ch == 'x' || ch =='X')
    pos++;
    code[codeSize++] = VARIABLEX;
    else if (ch == 'y' || ch == 'Y')
    pos++;
    code[codeSize++] = VARIABLEY;
    else if (ch == 'z' || ch == 'Z')
    pos++;
    code[codeSize++] = VARIABLEZ;
    else if (ch == '(')
    pos++;
    parseExpress();
    skip();
    if (next () !=')')
    error("Right parenthesis needed");
    pos++;
    else if (ch == ')')
    error ("Need a left parenthesis");
    else if (ch == '+' || ch == '-' || ch == '*' || ch =='/' || ch =='^')
    error ("Operator" + ch + "\n found in unexpected position");
    else if (ch == 0)
    error ("Incorrect entry");
    else
    error ("Illegal character " + ch);
    Its not pretty i know and its missing a part to parse Digits and i'm using type casting for strange reasons, but it does work. Except for in these two cases, can anyone see why
    Thanks
    podger

    I'm not even entirely certain what you are trying to accomplish here.
    It looks wrong in any case.
    I can't see anything in the way of debugging, so heres my help for today:
    public void printCode(){
          System.out.println(equation + ":");
          for(int i=0; i<code.length; i++){
            switch(code){
    case PLUS: System.out.print("Plus "); break;
    case MINUS: System.out.print("Minus "); break;
    case TIMES: System.out.print("TIMES "); break;
    case DIVIDE: System.out.print("DIVIDE "); break;
    case UNARYMINUS: System.out.print("-"); break;
    case VARIABLEX: System.out.print("x "); break;
    case VARIABLEY: System.out.print("y ");break;
    case VARIABLEZ:System.out.print("z ");break;
    System.out.println();
    I suggest you parse a couple of expressions, and print out the code generated using this handy little method.
    Parse parse = new Parse("x+y");
    parse.printCode();       
    parse = new Parse("x*y");
    parse.printCode();(x+y) : x y Plus
    (x*y) : x
    I think you will find the problem in your parseExpress method (well one of your problems anyway)
    Also take a look at your ParseTerm function - I'm pretty sure that a * is meant to represent "TIMES" and not "PLUS"
    Did you ever thing about using switch statements rather than ifs?
    Good luck,
    evnafets

  • Can anyone spot the syntax error?

    I've been looking at this for about a day now and can't see the error, which is:
    Insert Failed: java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.
      public String addSaleList(SaleList sL) {
        try {
          //Gets the connection to customer database.
          Class.forName(Driver);
          Connection myCon = DriverManager.getConnection(Url);
          System.out.println(sL.saleListID + " " + sL.saleID + " " + sL.product
                             + " " + sL.number);
          String sqlQry = "INSERT INTO salelist(saleID, product, number)" +
              "VALUES(?,?,?)";
          PreparedStatement myStmt = myCon.prepareStatement(sqlQry);
          myStmt.setInt(1, sL.saleID);
          myStmt.setString(2, sL.product);
          myStmt.setInt(3, sL.number);
          myStmt.executeUpdate();
          return "Sale confirmed";
        catch (Exception e) {
          System.out.println("Insert Failed: " + e);
          return ("Insert Failed: " + e);
      public class SaleList {
        public int saleListID;
        public int saleID;
        public String  product;
        public int  number;
        public SaleList(int saleListID, int saleID, String product, int number) {
          this.saleListID = saleListID;
          this.saleID = saleID;
          this.product = product;
          this.number = number;
      SaleList saleL = new SaleList(0,10,"b",2);
      lblStatus.setText(sM.addSaleList(saleL));

    Hey this is the stack trace:
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.
         at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6958)
         at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7115)
         at sun.jdbc.odbc.JdbcOdbc.SQLExecute(JdbcOdbc.java:3150)
         at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execut(JdbcOdbcPreparedStatement.java:214)
    at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeUpdateJdbcOdbcPreparedStatement.java:136)
         at myproject.SaleModel.addSaleList0 120 a 1
    (SaleModel.java:69)
         at myproject.SalesGUI.actionPerformed(SalesGUI.java:395)
         at java.awt.Button.processActionEvent(Button.java:382)
         at java.awt.Button.processEvent(Button.java:350)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

  • Can anyone spot the error in this script for iTunes?

    This AppleScript is designed to copy the Name and Artist of an iTunes track, then populate the Album Artist field with both, separated with an oblique. But when I run the script in iTunes, it only pastes the Artist name in to the Album Artist field and not the whole string.
    tell application "iTunes"
    if selection is not {} then -- if tracks are selected...
    set sel to selection
    set numTracks to (length of sel)
    set s to "s"
    if numTracks is 1 then set s to ""
    display dialog "Adds the name of the track and the name of the artist to the Album Artist field." & return & return & (numTracks & " track" & s & " selected.") buttons {"Cancel", "Continue"} default button 2 with title "Create Album Artist" giving up after 30
    if gave up of result is true then return
    repeat with t from 1 to numTracks
    tell contents of item t of sel
    set {album artist} to ({get artist} & " / " & {get name})
    end tell
    end repeat
    else
    display dialog "No tracks have been selected." buttons {"Cancel"} default button 1 with icon 0 giving up after 30
    end if -- no selection
    end tell

    Hello
    Try -
    tell item t of sel
    set album artist to (get artist) & " / " & (get name)
    end tell
    instead of -
    tell contents of item t of sel
    set {album artist} to ({get artist} & " / " & {get name})
    end tell
    In your original code, the left and right value of assignment are both list, i.e. -
    left value = {album artist}
    right value = {get artist, "/", get name}
    Consequently 'album artist' is assigned to the 1st item of the list at right, which is the result of 'get artist'.
    In order to avoid this, don't use list assingment, which is not necessary at all here.
    Also, I think you may just tell item t of sel, not contents of item t of sel.
    Hope this may help,
    H

  • Spot the deliberate mistake ! Grand prize for the first correct answer .....

    Hi all,
    I have been trying to get this piddly bit of code to work for a day now and I am out of cigarettes so.....
    JAVA STORED PROCEDURE USING JDEVELOPER
    ======================================
    The thing deploys ok. It is even executing from SQL*PLUS and I get a PL/SQL procedure successfully completed message. The problem is that it does not insert anything into the table. I have tried a commit after the exec in SQL*PLUS to no avail. Any suggestions ? It is the same for a DELETE statement.
    I know I don't need the three variables but I am at the stage of hard-coding some values into it to get it to work.
    Oh, and the prize is my UMIST cigarette lighter, a collectors item in a few hundred years, worth 10 pence at the moment.
    Cheers.
    package mypackage;
    import java.sql.*;
    import java.io.*;
    public class testSelect {
    public static void testSelect (int first, int second, int third)
    throws Exception {
    try{
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con=DriverManager.getConnection("jdbc:oracle:thin:@prams_nt_03:1521:gems", "rb199", "rb199");
    String sql = "INSERT INTO test VALUES (1, 2, 3)";
    PreparedStatement pstmt = con.prepareStatement(sql);
    pstmt.executeUpdate();
    pstmt.close();
    catch(Exception m)
    { m.printStackTrace();}

    Here's my guess.
    The commit from sqlplus would commit changes make by the current Oracle session. However, when you use the server thin driver, you are creating another Oracle session to the prams_nt_03 db. In order to commit this correctly. I think you need to call con.commit(); after the pstmt.executeUpdate(); This will commit the change you just make in the thin created Oracle session.
    In addition, it's odd that the thin connection doesn't do 'setAutoCommit to true' by default.
    package mypackage;
    import java.sql.*;
    import java.io.*;
    public class testSelect {
    public static void testSelect (int first, int second, int third)
    throws Exception {
    try{
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con=DriverManager.getConnection("jdbc:oracle:thin:@prams_nt_03:1521:gems", "rb199", "rb199");
    String sql = "INSERT INTO test VALUES (1, 2, 3)";
    PreparedStatement pstmt = con.prepareStatement(sql);
    pstmt.executeUpdate();
    pstmt.close();
    catch(Exception m)
    { m.printStackTrace();}

  • The cellular data services have disappeared from my settings. Can anyone help me restore it please?

    The cellular data services have disappeared from my settings. Can anyone help me restore it please?

    Try this  - Reset the iPad by holding down on the Sleep and Home buttons at the same time for about 10-15 seconds until the Apple Logo appears - ignore the red slider - let go of the buttons. (This is equivalent to rebooting your computer.) No data/files will be erased. http://support.apple.com/kb/ht1430
     Cheers, Tom

  • I have just dowloaded an audiobook from amazon to itunes.  I have synched my iphone 4s but cannot find the audio book on my phone.  Can anyone help me locate it please?

    I have just downloaded an audio book from amazon to itunes.  I have synchronised my iphone 4s, but cannot locate the book!  Amazon says to tap the ipod icon but i do not have one!! Can anyone help me locate it please?

    kikuyujen wrote:
    Could anyone help me find an article called Switch 101 that helps people converting from Windows to Mac.
    Just Googled "Switch 101."
    http://www.apple.com/support/switch101/

  • Hello I have problome with YouTube on my apple tv. When I add playlist on my Mac I can see the movies and play them but I can't see the movies on my appletv only the name of the playlist and I am can't watch the movies. Anyone know the problome? Please..

    Hello I have problome with YouTube on my apple tv. When I add playlist on my Mac I can see the movies and play them but I can't see the movies on my appletv only the name of the playlist and I am can't watch the movies. Anyone know the problome? Please..

    Geesh - all this information and no  one has any clue to this? Not even someone from Apple?
    Can someone at least point me in the right direction?

  • Problems with Overlay Layout - can anyone spot something wrong/missing?

    Hi folks, I'm developing a tool that allows you to draw rectangles around objects on an image. The rectangles are then saved, and you can move between images. For some reason, though my rectangles are not drawing on the panel. I am using the Overlay Layout. Can anyone spot what I'm doing wrong? (The TopPanel canvas appears to be there, as it's taking input from the mouse - the problem is simply that the red rectangles are not drawing on the panel). Please help!!
    So you know, there is a JFrame in another class which adds an instance of the ObjectMarker panel to it. It also provides buttons for using the next and previous Image methods.
    Any other general advice is appreciated too.
    * Object_Marker.java
    * Created on 07 April 2008, 15:38
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.event.MouseEvent;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import javax.imageio.ImageIO;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.OverlayLayout;
    import javax.swing.event.MouseInputAdapter;
    * @author Eric
    public class ObjectMarker extends javax.swing.JPanel {
         private static final long serialVersionUID = 6574271353772129556L;
         File directory;
         String directory_path;
         Font big = new Font("SansSerif", Font.BOLD, 18);
         List<File> file_list = Collections.synchronizedList(new LinkedList<File>());
         String[] filetypes = { "jpeg", "jpg", "gif", "bmp", "tif", "tiff", "png" };
         // This Hashmap contains List of Rectangles, allowing me to link images to collections of rectangles through the value 'index'.
         public static HashMap<Integer, List<Rectangle>> collection = new HashMap<Integer, List<Rectangle>>();
         BufferedImage currentImage;
         Thread thread;
         Integer index = 0;
         OverlayLayout overlay;
         private TopPanel top;
         private JPanel pictureFrame;
         String newline = System.getProperty("line.separator");
          * Creates new form Object_Marker
          * @throws IOException
         public ObjectMarker(File directory) {
              System.out.println("Got in...");
              this.directory = directory;
              File[] temp = directory.listFiles();
              directory_path = directory.getPath();
              // Add all the image files in the directory to the linked list for easy
              // iteration.
              for (File file : temp) {
                   if (isImage(file)) {
                        file_list.add(file);
              initComponents();
              try {
                   currentImage = ImageIO.read(file_list.get(index));
              } catch (IOException e) {
                   System.out.println("There was a problem loading the image.");
              // 55 pixels offsets the height of the JMenuBar and the title bar
              // which are included in the size of the JFrame.
              this.setSize(currentImage.getWidth(), currentImage.getHeight() + 55);
         public String getImageList() {
              // Allows me to build the string gradually.
              StringBuffer list = new StringBuffer();
              list.append("Image files found in directory: \n\n");
              for (int i = 0; i < file_list.size(); i++) {
                   list.append((((File) file_list.get(i))).getName() + "\n");
              return list.toString();
         private void initComponents() {
              top = new TopPanel();
              pictureFrame = new javax.swing.JPanel();
              OverlayLayout ol = new OverlayLayout(this);
              this.setLayout(ol);
              this.add(top);
              this.add(pictureFrame);
          * private void initComponents() {
          * javax.swing.GroupLayout pictureFrameLayout = new
          * javax.swing.GroupLayout(pictureFrame);
          * pictureFrame.setLayout(pictureFrameLayout);
          * pictureFrameLayout.setHorizontalGroup(
          * pictureFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          * .addGap(0, 497, Short.MAX_VALUE) ); pictureFrameLayout.setVerticalGroup(
          * pictureFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          * .addGap(0, 394, Short.MAX_VALUE) );
          * javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
          * this.setLayout(layout); layout.setHorizontalGroup(
          * layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          * .addComponent(pictureFrame, javax.swing.GroupLayout.DEFAULT_SIZE,
          * javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) );
          * layout.setVerticalGroup(
          * layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          * .addComponent(pictureFrame, javax.swing.GroupLayout.DEFAULT_SIZE,
          * javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); }
          * This function returns the extension of a given file, for example "jpg" or
          * "gif"
          * @param f
          *            The file to examine
          * @return String containing extension
         public static String getExtension(File f) {
              String ext = null;
              String s = f.getName();
              int i = s.lastIndexOf('.');
              if (i > 0 && i < s.length() - 1) {
                   ext = s.substring(i + 1).toLowerCase();
              } else {
                   ext = "";
              return ext;
         public String getDetails() {
              saveRectangles();
              StringBuffer sb = new StringBuffer();
              for (int i = 0; i < file_list.size(); i++) {
                   try{
                   int count = collection.get(i).size();
                   if (count > 0) {
                        sb.append(file_list.get(i).getPath() + " "); // Add the
                        // filename of
                        // the file
                        sb.append(count + " "); // Add the number of rectangles
                        for (int j = 0; j < collection.get(i).size(); j++) {
                             Rectangle current = collection.get(i).get(j);
                             String coordinates = (int) current.getMinX() + " "
                                       + (int) current.getMinY() + " ";
                             String size = ((int) current.getMaxX() - (int) current
                                       .getMinX())
                                       + " "
                                       + ((int) current.getMaxY() - (int) current
                                                 .getMinY()) + " ";
                             String result = coordinates + size;
                             sb.append(result);
                        sb.append(newline);
                   } catch (NullPointerException e){
                        // Do nothing.  "int count = collection.get(i).size();"
                        // will try to over count.
              return sb.toString();
         private boolean isImage(File f) {
              List<String> list = Arrays.asList(filetypes);
              String extension = getExtension(f);
              if (list.contains(extension)) {
                   return true;
              return false;
         /** Draw the image on the panel. * */
         public void paint(Graphics g) {
              if (currentImage == null) {
                   g.drawString("No image to display!", 300, 240);
              } else {
                   // Draw the image
                   g.drawImage(currentImage, 0, 0, this);
                   // Write the index
                   g.setFont(big);
                   g.drawString(index + 1 + "/" + file_list.size(), 10, 25);
         public void nextImage() throws IOException {
              if (index < file_list.size() - 1) {
                   printOutContents();
                   System.out.println("Index: " + index);
                   saveRectangles();
                   index++;
                   currentImage = ImageIO.read(file_list.get(index));
                   this
                             .setSize(currentImage.getWidth(),
                                       currentImage.getHeight() + 55);
                   top.setSize(this.getSize());
                   top.rectangle_list.clear();
                   if (collection.size() > index) {
                        loadRectangles();
                   repaint();
         private void saveRectangles() {
              // If the current image's rectangles have not been changed, don't do
              // anything.
              if (collection.containsKey(index)) {
                   System.out.println("Removing Index: " + index);
                   collection.remove(index);
              collection.put(index, top.getRectangleList());
              System.out.println("We just saved " + collection.get(index).size()
                        + " rectangles");
              System.out.println("They were saved in HashMap Location " + index);
              System.out.println("Proof: ");
              List<Rectangle> temp = collection.get(index);
              for (int i = 0; i < temp.size(); i++) {
                   System.out.println("Rectangle " + (i + 1) + ": " + temp.get(i));
              // If the rectangle list has changed, set the list the current index
              // as the new list.
         private void loadRectangles() {
              System.out.println("We just loaded index " + index
                        + " into temporary memory.");
              System.out.println("Proof: ");
              List<Rectangle> temp = collection.get(index);
              top.rectangle_list = collection.get(index);
              for (int i = 0; i < temp.size(); i++) {
                   System.out.println("Rectangle " + (i + 1) + ": " + temp.get(i));
         private void printOutContents() {
              System.out.println();
              System.out.println("Contents printout...");
              for (int i = 0; i < collection.size(); i++) {
                   for (Rectangle r : collection.get(i)) {
                        System.out.println("In collection index: " + i + " Rectangle "
                                  + r.toString());
              System.out.println();
         public void previousImage() throws IOException {
              if (index >= 1) {
                   printOutContents();
                   System.out.println("Index: " + index);
                   saveRectangles();
                   index--;
                   currentImage = ImageIO.read(file_list.get(index));
                   this
                             .setSize(currentImage.getWidth(),
                                       currentImage.getHeight() + 55);
                   top.setSize(this.getSize());
                   top.rectangle_list.clear();
                   if (index >= 0) {
                        loadRectangles();
                   repaint();
         public void removeLastRectangle() {
              // This method removes the most recent rectangle added.
              try {
                   int length = collection.get(index).size();
                   collection.get(index).remove(length - 1);
              } catch (NullPointerException e) {
                   try {
                        top.rectangle_list.remove(top.rectangle_list.size() - 1);
                   } catch (IndexOutOfBoundsException ioobe) {
                        JOptionPane.showMessageDialog(this, "Cannot undo any more!");
    * Class developed from SSCCE found on Java forum:
    * http://forum.java.sun.com/thread.jspa?threadID=647074&messageID=3817479
    * @author 74philip
    class TopPanel extends JPanel {
         List<Rectangle> rectangle_list;
         private static final long serialVersionUID = 6208367976334130998L;
         Point loc;
         int width, height, arcRadius;
         Rectangle temp; // for mouse ops in TopRanger
         public TopPanel() {
              setOpaque(false);
              rectangle_list = Collections
                        .synchronizedList(new LinkedList<Rectangle>());
              TopRanger ranger = new TopRanger(this);
              addMouseListener(ranger);
              addMouseMotionListener(ranger);
         public List<Rectangle> getRectangleList() {
              List<Rectangle> temporary = Collections
                        .synchronizedList(new LinkedList<Rectangle>());
              temporary.addAll(rectangle_list);
              return temporary;
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D) g;
              g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
              g2.setPaint(Color.red);
              // Draw all the rectangles in the rectangle list.
              for (int i = 0; i < rectangle_list.size(); i++) {
                   g2.drawRect(rectangle_list.get(i).x, rectangle_list.get(i).y,
                             rectangle_list.get(i).width, rectangle_list.get(i).height);
              if (temp != null) {
                   g2.draw(temp);
         public void loadRectangleList(List<Rectangle> list) {
              rectangle_list.addAll(list);
         public void addRectangle(Rectangle r) {
              rectangle_list.add(r);
    class TopRanger extends MouseInputAdapter {
         TopPanel top;
         Point offset;
         boolean dragging;
         public TopRanger(TopPanel top) {
              this.top = top;
              dragging = false;
         public void mousePressed(MouseEvent e) {
              Point p = e.getPoint();
              top.temp = new Rectangle(p, new Dimension(0, 0));
              offset = new Point();
              dragging = true;
              top.repaint();
         public void mouseReleased(MouseEvent e) {
              dragging = false;
              // update top.r
              System.out.println(top.getRectangleList().size() + ": Object added: "
                        + top.temp.toString());
              top.addRectangle(top.temp);
              top.repaint();
         public void mouseDragged(MouseEvent e) {
              if (dragging) {
                   top.temp.setBounds(top.temp.x, top.temp.y, e.getX() - top.temp.x, e
                             .getY()
                             - top.temp.y);
                   top.repaint();
    }Regards,
    Eric

    Alright so I fixed it! I created a new class called BottomPanel extends JPanel, which I then gave the responsibility of drawing the image. I gave it an update method which took the details of the currentImage and displayed it on the screen.
    If anybody's interested I also discovered/solved a problem with my mouseListener - I couldn't drag backwards. I fixed this by adding tests looking for negative widths and heights. I compensated accordingly by reseting the rectangle origin to e.getX(), e.getY() and by setting the to original_origin.x - e.getX() and original_origin.y - e.getY().
    No problem!

  • ADM dialog hangs but on debugging it works fine. Can't spot the problem

    Hello,
    I have developed an automate plugin which submits a design on a server using libcurl library. There is a dialog(made using ADM) to submit a design which consists of a submit button and a progress bar. On clicking the submit button, the progress bar starts getting updated. When the progress bar is completely updated the dialog seems to hang. The dialog is supposed to close after submit. The obvious way to search for the problem was to debug the source code, but it appears that whenever the source code is debugged then it runs smoothly. But without any debug points the problem reverts. How can we spot the problem without debugging?
    Please guide.

    In developing plug-ins over the past years I have encountered a few cases where the presence of the debugger seemed to work around a problem.  The debugger necessarily changes the timing and resource allocations some.
    In every case the problem turned out to be a legitmate bug - a mistake we had made in our code, and in some cases finding that bug required other measures beyond using the debugger to help us track it down.  We ended up implementing a very sophisticated logging facility that we use in all our products now.  It appends lines of text containing pertinent info into a log file that's created for each run.  The detailed logging commands compile-out in a Release build, so we just leave them in the source code all the time and they add no overhead.
    Unfortunately, there's no easy answer for your dilemma, other than to advise you to implement your own logging facility - or at least the ability to add printf statements (or similar) into your code so you can trace the progress in sticky situations.
    Though I saw your message and am a plug-in developer myself, you might find you can get more direct help in the SDK forum...
    http://forums.adobe.com/community/photoshop/photoshop_sdk
    Good luck!
    -Noel

  • We used to get a 'whooshing' noise when we sent an eMail using mac Mail. This no longer happens. We recently updated to Mountain Lion 10.8.1  Can anyone throw light  on this please?    David

    We used to get a 'whooshing' noise when we sent an eMail using mac Mail. This no longer happens. We recently updated to Mountain Lion 10.8.1  Can anyone throw light  on this please?    David

    Hi
    I am sorry to see you are having problems with your BT Service
    I suggest you contact the forum mods they should be able to get this problem sorted for you this is a link to them http://bt.custhelp.com/app/contact_email/c/4951
    They normally reply by email or phone directly to you within 3 working days they will take personal ownership of your problem until resolved and will keep you informed of progress
    They are a UK based BT specialist team who have a good record at getting problems solved
    This is a customer to customer self help forum the only BT presence here are the forum moderators
    If you want to say thanks for a helpful answer,please click on the Ratings star on the left-hand side If the reply answers your question then please mark as ’Mark as Accepted Solution’

  • Can anyone explain this to me, please. It's a static section question.

    Can anyone explain this to me, please. It's a static section question.
    I came across the following style of programming recently and I would like to know what the Static section is actually doing in the class. Thx.
    Here is the code.
    public class ClassA {
         private static Hashtable ClassAList = new Hashtable();
         private ClassB cB;
         private Vector goodLink;
         private Hashtable classCList;
         static
              ClassA cA = new ClassA();
              ClassAList.put("whatever", cA);
         public static ClassA getClassA()
              return (ClassA) ClassAList.get("whatever");

    hi,
    The static section shall be loaded before it's constructor is called. (i.e at the time of loading the class). Therefore making it available for any other objects to call.
    hope this clarifies ur question
    prasanna

Maybe you are looking for