How to restructure this code into separate classes?

I have C# code that initializes a force feedback joystick and plays an effect file(vibrates the joystick). I have turn the console application into library
code to make a dll so that I can use it in LabVIEW. 
Right now all the code is written under one class, so went I put the dll in LabVIEW I can only select that one class. labVIEW guy told me that I need to
restructure my C# code into separate classes. Each class that I want to access from LabVIEW needs to marked as public. Then I can instantiate that class in LabVIEW using a constructor, and call methods and set properties of that class using invoke nodes and
property nodes.
How can I do this correctly? I tried changing some of them into classes but doesn't work. Can you guys take a look at the code to see if it is even possible
to break the code into separate classes? Also, if it is possible can you guide me, suggest some reading/video, etc.
Thank you
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using Microsoft.DirectX.DirectInput;
namespace JoystickProject
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
private System.Windows.Forms.Label label1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private Device device = null;
private bool running = true;
private ArrayList effectList = new ArrayList();
private string joyState = "";
public bool InitializeInput()
// Create our joystick device
foreach(DeviceInstance di in Manager.GetDevices(DeviceClass.GameControl,
EnumDevicesFlags.AttachedOnly | EnumDevicesFlags.ForceFeeback))
// Pick the first attached joystick we see
device = new Device(di.InstanceGuid);
break;
if (device == null) // We couldn't find a joystick
return false;
device.SetDataFormat(DeviceDataFormat.Joystick);
device.SetCooperativeLevel(this, CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Background);
device.Properties.AxisModeAbsolute = true;
device.Properties.AutoCenter = false;
device.Acquire();
// Enumerate any axes
foreach(DeviceObjectInstance doi in device.Objects)
if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
// We found an axis, set the range to a max of 10,000
device.Properties.SetRange(ParameterHow.ById,
doi.ObjectId, new InputRange(-5000, 5000));
// Load our feedback file
EffectList effects = null;
effects = device.GetEffects(@"C:\MyEffectFile.ffe",
FileEffectsFlags.ModifyIfNeeded);
foreach(FileEffect fe in effects)
EffectObject myEffect = new EffectObject(fe.EffectGuid, fe.EffectStruct,
device);
myEffect.Download();
effectList.Add(myEffect);
while(running)
UpdateInputState();
Application.DoEvents();
return true;
public void PlayEffects()
// See if our effects are playing.
foreach(EffectObject myEffect in effectList)
//if (button0pressed == true)
//MessageBox.Show("Button Pressed.");
// myEffect.Start(1, EffectStartFlags.NoDownload);
if (!myEffect.EffectStatus.Playing)
// If not, play them
myEffect.Start(1, EffectStartFlags.NoDownload);
//button0pressed = true;
protected override void OnClosed(EventArgs e)
running = false;
private void UpdateInputState()
PlayEffects();
// Check the joystick state
JoystickState state = device.CurrentJoystickState;
device.Poll();
joyState = "Using JoystickState: \r\n";
joyState += device.Properties.ProductName;
joyState += "\n";
joyState += device.ForceFeedbackState;
joyState += "\n";
joyState += state.ToString();
byte[] buttons = state.GetButtons();
for(int i = 0; i < buttons.Length; i++)
joyState += string.Format("Button {0} {1}\r\n", i, buttons[i] != 0 ? "Pressed" : "Not Pressed");
label1.Text = joyState;
//if(buttons[0] != 0)
//button0pressed = true;
public Form1()
// Required for Windows Form Designer support
InitializeComponent();
// TODO: Add any constructor code after InitializeComponent call
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
if( disposing )
if (components != null)
components.Dispose();
base.Dispose( disposing );
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
public void InitializeComponent()
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
// label1
this.label1.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(272, 488);
this.label1.TabIndex = 0;
// Form1
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.SystemColors.ControlText;
this.ClientSize = new System.Drawing.Size(288, 502);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.label1});
this.Name = "Form1";
this.Text = "Joystick Stuff";
this.ResumeLayout(false);
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
using (Form1 frm = new Form1())
frm.Show();
if (!frm.InitializeInput())
MessageBox.Show("Couldn't find a joystick.");

Imho he means the following.
Your class has performs two tasks:
Controlling the joystick.
Managing the joystick with a form.
So I would recommend, that you separate the WinForm from the joystick code. E.g.
namespace JoystickCtlLib
public class JoystickControl
private Device device = null;
private bool running = true;
private ArrayList effectList = new ArrayList();
private string joyState = "";
public string State { get { return this.joyState; } }
public bool InitializeInput() { return true; }
public void PlayEffects() { }
private void UpdateInputState() { }
So that your joystick class does not reference or uses any winform or button.
btw, there is a thing which is more important than that: Your polling the device in the main thread of your application. This will block your main application. Imho this should be a job for a thread like background worker.

Similar Messages

  • (AS3) How to divide my code into classes/package

    Anyone familiar with this? I have already tried dividing
    among classes and it is not working.
    I have created the following code that pulls data from an
    external xml file into a datagrid. I have been trying to figure out
    how to get it to function using classes and/or packages. I'd like
    to separate the functionality into separate classes for each of the
    following:
    1) A class for loading the XML file(s) (there will likely be
    more datagrids and more xml files)
    2) A class for "drawing" the datagrid based on the xml
    .... others you can think of??
    I have attached the code in question.
    Thanks,
    Mark

    Classes in AS3 need to be in packages now, e.g.:
    // package needs to be included in same directory with FLA or
    in class look up targets
    package {
    // import statements go here
    // needs to be public for access outside of package
    directory
    public class NewXMLClass {
    // again public makes it accessible to other classes
    public function NewXMLClass() {}
    // inlcude your methods here
    use an import statement to use it in other classes e.g.
    import NewXMLClass;
    Hope that helps...

  • How do I get this code into iBook Author?

    I would like to add an accordion menu to my iBook that will reveal a list of web links when clicked. Here is a link to an example with example code. I'm just not sure how to get this code and it's required external javascript file into iBook author.
    http://www.dynamicdrive.com/dynamici...m?expandable=3
    Any help would be appreciated

    Oops. Thanks. Here is a new link:
    http://www.dynamicdrive.com/dynamicindex17/ddaccordionmenu-bullet.htm

  • How can i rewrite this code into java?

    How can i rewrite this code into a java that has a return value?
    this code is written in vb6
    Private Function IsOdd(pintNumberIn) As Boolean
        If (pintNumberIn Mod 2) = 0 Then
            IsOdd = False
        Else
            IsOdd = True
        End If
    End Function   
    Private Sub cmdTryIt_Click()
              Dim intNumIn  As Integer
              Dim blnNumIsOdd     As Boolean
              intNumIn = Val(InputBox("Enter a number:", "IsOdd Test"))
              blnNumIsOdd = IsOdd(intNumIn)
              If blnNumIsOdd Then
           Print "The number that you entered is odd."
        Else
           Print "The number that you entered is not odd."
        End If
    End Sub

    873221 wrote:
    I'm sorry I'am New to Java.Are you new to communication? You don't have to know anything at all about Java to know that "I have an error," doesn't say anything useful.
    I'm just trying to get you to think about what your post actually says, and what others will take from it.
    what does this error mean? what code should i replace and add? thanks for all response
    C:\EvenOdd.java:31: isOdd(int) in EvenOdd cannot be applied to ()
    isOdd()=true;
    ^
    C:\EvenOdd.java:35: isOdd(int) in EvenOdd cannot be applied to ()
    isOdd()=false;
    ^
    2 errors
    Telling you "what code to change it to" will not help you at all. You need to learn Java, read the error message, and think about what it says.
    It's telling you exactly what is wrong. At line 31 of EvenOdd.java, you're calling isOdd(), with no arguments, but the isOdd() method requires an int argument. If you stop ant think about it, that should make perfect sense. How can you ask "is it odd?" without specifying what "it" is?
    So what is this all about? Is this homework? You googled for even odd, found a solution in some other language, and now you're just trying to translate it to Java rather than actually learning Java well enough to simply write this trivial code yourself?

  • Anyone knows how to make this code to netbeans??

    anyone knows how to make this code to netbeans?? i just want to convert it into netbeans... im not really advance with this software... anyway..just reply if you have any idea...or steps how to build it... etc.... thanks guys...
       import javax.swing.*;
       import javax.swing.table.*;
       import java.awt.*;
       import java.awt.event.*;
       import java.util.regex.*;
       public class FilterTable {
         public static void main(String args[]) {
           Runnable runner = new Runnable() {
             public void run() {
               JFrame frame = new JFrame("Sorting JTable");
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               Object rows[][] = {
                 {"AMZN", "Amazon", 41.28},
                 {"EBAY", "eBay", 41.57},
                 {"GOOG", "Google", 388.33},
                 {"MSFT", "Microsoft", 26.56},
                 {"NOK", "Nokia Corp", 17.13},
                 {"ORCL", "Oracle Corp.", 12.52},
                 {"SUNW", "Sun Microsystems", 3.86},
                 {"TWX",  "Time Warner", 17.66},
                 {"VOD",  "Vodafone Group", 26.02},
                 {"YHOO", "Yahoo!", 37.69}
               Object columns[] = {"Symbol", "Name", "Price"};
               TableModel model =
                  new DefaultTableModel(rows, columns) {
                 public Class getColumnClass(int column) {
                   Class returnValue;
                   if ((column >= 0) && (column < getColumnCount())) {
                     returnValue = getValueAt(0, column).getClass();
                   } else {
                     returnValue = Object.class;
                   return returnValue;
               JTable table = new JTable(model);
               final TableRowSorter<TableModel> sorter =
                       new TableRowSorter<TableModel>(model);
               table.setRowSorter(sorter);
               JScrollPane pane = new JScrollPane(table);
               frame.add(pane, BorderLayout.CENTER);
               JPanel panel = new JPanel(new BorderLayout());
               JLabel label = new JLabel("Filter");
               panel.add(label, BorderLayout.WEST);
               final JTextField filterText =
                   new JTextField("SUN");
               panel.add(filterText, BorderLayout.CENTER);
               frame.add(panel, BorderLayout.NORTH);
               JButton button = new JButton("Filter");
               button.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                   String text = filterText.getText();
                   if (text.length() == 0) {
                     sorter.setRowFilter(null);
                   } else {
                     try {
                       sorter.setRowFilter(
                           RowFilter.regexFilter(text));
                     } catch (PatternSyntaxException pse) {
                       System.err.println("Bad regex pattern");
               frame.add(button, BorderLayout.SOUTH);
               frame.setSize(300, 250);
               frame.setVisible(true);
           EventQueue.invokeLater(runner);
       }

    its okay onmosh.....what we need to
    this...forum....is to have a good......relationship
    of programmers......and to start with .....we need to
    have a good attitude........right.....???.....no
    matter how good you are in programming but if you did
    not posses the right kind of attitude....everything
    is useless.....in the first place....all we
    want....is just to ask...some....help....but
    conflicts......but unluckily......we did not expect
    that there are members in here which......not
    good...to follow.....just as suggestion for those
    people not having the right kind of attidude...why
    can't you do in a very nice message sharing in a very
    nice....way....why we need to put some
    stupid....stuff...words.....can't you live with out
    ******* ****....its not.....lastly especially you
    have your children right now and people around...that
    somehow......idiolize...you even me....is one of
    them......but showing but attitude....is not
    good......tnx....hope you'll take it this....in the
    positive side.....be optimistic...guys....the
    world..is not yours....all of us will just past
    away....always..remember that one.....treasure..our
    stay in this....temporary home.....which...is
    world....Whoa. That post seems to be killing my brain.
    URK
    Join........us..........do not be..........afraid.......

  • How to transport this code to an applet

    Hi friends..
    the following page has a program to capture images from a web-cam.. can u help me how to transport that code into an applet. So that i can import that applet into an html page, where the live video can be streamed.
    the link is :- http://forum.java.sun.com/thread.jspa?threadID=247253&start=0&tstart=0
    i tried this code. but on html page the code is not being initialized, though the program is getting compiled correctly.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.format.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import javax.media.protocol.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.applet.*;
    import com.sun.image.codec.jpeg.*;
    public class applet extends JApplet{
       static final int    WIDTH  = 320;
        static final int    HEIGHT = 320;
        //public intoApplet d = null;
        public static void main(String args[]){
             JFrame frame = new JFrame("Code Converter");
             applet a = new applet();
             a.init();
             frame.getContentPane().add(a);
             frame.setSize(WIDTH, HEIGHT);
             frame.setVisible(true);
        public void init() {
          System.out.println("Applet initializing");
          intoApplet d = new intoApplet();
          getContentPane().add(d);
        public void start() {
            System.out.println("Applet starting");
        public void stop() {
            System.out.println("Applet stopping");
        public void destroy() {
            System.out.println("Applet destroyed");
    public class intoApplet extends JPanel //implements ActionListener
      public Player player = null;
      public CaptureDeviceInfo di = null;
      public MediaLocator ml = null;
      public JButton capture = null;
      public Buffer buf = null;
      public Image img = null;
      public VideoFormat vf = null;
      public BufferToImage btoi = null;
      //public ImagePanel imgpanel = null;
      public intoApplet()
           System.out.print("into swing...");
        setLayout(new BorderLayout());
        setSize(320,320);
        String str1 = "vfw:Logitech USB Video Camera:0";
        String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
        di = CaptureDeviceManager.getDevice(str2);
        //ml = di.getLocator();
        ml = new MediaLocator("vfw://0");
        try
          player = Manager.createRealizedPlayer(ml);
          player.start();
          Component comp;
          if ((comp = player.getVisualComponent()) != null)
            add(comp,BorderLayout.NORTH);
          //add(capture,BorderLayout.CENTER);
          //add(imgpanel,BorderLayout.SOUTH);
        catch (Exception e)
          e.printStackTrace();
    public void playerclose()
        player.close();
        player.deallocate();
    }Message was edited by:
    rahulsah

    Maybe this topic helps (JUnit into Applet):
    http://forum.java.sun.com/thread.jspa?threadID=5130219&messageID=9469005#9469005

  • Can any one change this Applet into a class that extends Jpanel.....

    Hi,
    I need this applet as a class that extends JPanel, I will be very very thankful to you if any one kindly change this Applet code into a class that extends JApplet.
    I will be very thankful to you if some one can reserve few minutes & do this favor early.
    Thanks a lot for any help.
         My Pong Code
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    public class Class1 extends Applet implements Runnable
    {     private final int APPLET_WIDTH = 900;
         private final int APPLET_HEIGHT = 600;
         private int px = 15;
         private final int py = 560;
         private final int ph = 10;
         private final int pw = 75;
         private int old_px = px;
         private int bx = 450;
         private int by = 15;
         private final int bh = 20;
         private final int bw = 20;
         private int move_x = 2;
         private int move_y = 2;
         private boolean done = false;
         Thread t;
         private final int delay = 25;
         public void init()
         {     setBackground(Color.black);
              setSize(APPLET_WIDTH, APPLET_HEIGHT);
              requestFocus();
              addKeyListener(new DirectionKeyListener());
             (t = new Thread(this)).start();
         public void run()      {
        try      {     while((t == Thread.currentThread()) && (done == false))           {     
                   if ((bx < 15) || (bx > APPLET_WIDTH-30))                     move_x = -move_x;                                if ((by < 15) ||                    ((by > APPLET_HEIGHT-60)&&                     ((px<=bx)&&(bx<=px+pw))))
                        move_y = -move_y;
                   if (by > APPLET_HEIGHT)
                        done = true;
                                   bx = bx + move_x;
                   by = by + move_y;                                                repaint();
                   t.sleep(delay);
         catch(Exception e)      {}
         }//end run
         /*public void move_paddle(int amount)
              old_px = px;
              //if (amount > 0)
                //if (px <= APPLET_WIDTH-15)
                   px = px + amount;
              //else if (amount < 0)
               // if (px >= 15)
                   px = px + amount;
         public void paint(Graphics page)
              //     page.setColor(Color.black);
              //     page.drawRect(old_px, py, pw, ph);
                   page.setColor(Color.blue);
                   page.drawRect(px, py, pw, ph);
                   page.setColor(Color.white);
                   page.drawOval(bx, by, bw, bh);
                   if ((done == true) && (by > APPLET_HEIGHT))
                        page.drawString("LOSER!!!", APPLET_WIDTH/2, APPLET_HEIGHT/2);
                   else if (done == true)
                        page.drawString("Game Over, Man!", APPLET_WIDTH/2-10, APPLET_HEIGHT/2);
         private class DirectionKeyListener implements KeyListener               
              public void keyPressed (KeyEvent event)
                   switch (event.getKeyCode())
                   case KeyEvent.VK_LEFT:
                        old_px = px;
                        if (px >=15)
                             px -=10;
                        break;
                   case KeyEvent.VK_RIGHT:
                        old_px = px;
                        if (px+pw <= APPLET_WIDTH-15)
                             px += 10;
                        break;
                   case KeyEvent.VK_Q:
                        done = true;
                   default:
                   }  //end switch
                   repaint();
              }//end keyPressed
              public void keyTyped (KeyEvent event)
              public void keyReleased (KeyEvent event)
         }  //end class 
    }

    thank you sir for your advice.
    Its not like that I without any attempt, just past code here & asked for its conversion. I spent about 5 hours on it, can say spoil whole day but to no avail. You then just guide me, give some hint so that I do it. I will most probably wanted to do it by myself but asked for help when was just disappointed.
    I try to put all init() in default constructor of identical copy of this applet that extends JPanel. Problem.....ball tend to fell but pad not moving. Also out out was not getting ant color input. That was like my best effort.....other tried that I found by search like just do nothing only extend panel OR frame in spite of applet, start applet from within main of another class.... these are few I remember what I tried.
    I will be very very thankful to you if you can help/guide me how can I do it. Behavior of the Applet is like a normal PONG game with on pad controlled by arrow keys, & one ball colliding with walls of boundary & falling down.
    Thanks a lot again for your attention & time.

  • How to scan multiple photos into separate

    I have a hp envy 5660.  I often have to scan multiple photos and on my old printer it would show them as individual files on the scan page.  I can't figure out how to do that with this printer.  I want to scan multiple photos, have them save as individual phhotos so I can print them out on 4 x 6 photo paper.  Any ideas? Thanks!

    Hi @bird22557,
    Welcome to the HP Forums!
    I noticed that you are wondering how to scan multiple photos into separate files with your HP Envy 5660 printer on Windows 7. I am happy to look into this scanning issue for you!  
    I would recommend to go through this how to scan guide, Scan from Windows 7 With the Full Feature HP Software for HP Multifunction Printers, you can try with HP software or without HP software. As there are multiple ways of scanning.
    For future reference, here is your printer's user guide as well, HP ENVY 5660 e-All-in-One Printer User guides.
    Hope this helps, and thank you for posting!
    RnRMusicMan
    I work on behalf of HP
    Please click “Accept as Solution ” if you feel my post solved your issue, it will help others find the solution.
    Click the “Kudos Thumbs Up" to say “Thanks” for helping!

  • I just purchased Wittenberger Fraktur how do install this font into my photoshop cs6 for mac ?

    I just purchased Wittenberger Fraktur how do install this font into my photoshop cs6 for mac ?

    You just install it in the OS.
    Photoshop gets the fonts from the OS.

  • Can someone please tell me on how to modify this code so that I dont have to enter the file name at all?

    Hello
    can someone please tell me how to modify this code so that I dont have to enter the file path at all? When i give the same file path constants to both the read and write VIs I'm getting an error message.
    Attachments:
    read and write.vi ‏11 KB

    Yup use the low level File I/O opening the reference once, and closing it once.  
    As for the path selection you have an unwired input which is the path to use.  Programatically set that and you won't be prompted to select a path.  Usually this is done with a path constant to a folder, then using the Build Path, to set the file name in that folder.
    Unofficial Forum Rules and Guidelines - Hooovahh - LabVIEW Overlord
    If 10 out of 10 experts in any field say something is bad, you should probably take their opinion seriously.

  • How to turn this Java into something I can use in CF?

    Hi - Following on from a recent post about how to strip our special characters from a string before insertion to the db I have found this Java code - my question is, how can I turn this into something I can use with CF? I think I need to use the cfscipt tag but that's right on the boundaries of my knowledge base.. If anyone could please help I'd be ever so grateful - thank you!
    package net.htmlescape;
    * HtmlEscape in Java, which is compatible with utf-8
    * @author Ulrich Jensen, http://www.htmlescape.net
    * Feel free to get inspired, use or steal this code and use it in your
    * own projects.
    * License:
    * You have the right to use this code in your own project or publish it
    * on your own website.
    * If you are going to use this code, please include the author lines.
    * Use this code at your own risk. The author does not warrent or assume any
    * legal liability or responsibility for the accuracy, completeness or usefullness of
    * this program code.
    public class HtmlEscape {
      private static char[] hex={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
       * Method for html escaping a String, for use in a textarea
       * @param original The String to escape
       * @return The escaped String
      public static String escapeTextArea(String original)
        return escapeSpecial(escapeTags(original));    
       * Normal escape function, for Html escaping Strings
       * @param original The original String
       * @return The escape String
      public static String escape(String original)
        return escapeSpecial(escapeBr(escapeTags(original)));
      public static String escapeTags(String original)
        if(original==null) return "";
        StringBuffer out=new StringBuffer("");
        char[] chars=original.toCharArray();
        for(int i=0;i<chars.length;i++)
          boolean found=true;
          switch(chars[i])
            case 60:out.append("&lt;"); break; //<
            case 62:out.append("&gt;"); break; //>
            case 34:out.append("&quot;"); break; //"
            default:found=false;break;
          if(!found) out.append(chars[i]);
        return out.toString();
      public static String escapeBr(String original)
        if(original==null) return "";
        StringBuffer out=new StringBuffer("");
        char[] chars=original.toCharArray();
        for(int i=0;i<chars.length;i++)
          boolean found=true;
          switch(chars[i])
            case '\n': out.append("<br/>"); break; //newline
            case '\r': break;
            default:found=false;break;
          if(!found) out.append(chars[i]);
        return out.toString();
      public static String escapeSpecial(String original)
        if(original==null) return "";
        StringBuffer out=new StringBuffer("");
        char[] chars=original.toCharArray();
        for(int i=0;i<chars.length;i++)
            boolean found=true;
          switch(chars[i]) {
            case 38:out.append("&amp;"); break; //&
            case 198:out.append("&AElig;"); break; //Æ
            case 193:out.append("&Aacute;"); break; //Á
            case 194:out.append("&Acirc;"); break; //Â
            case 192:out.append("&Agrave;"); break; //À
            case 197:out.append("&Aring;"); break; //Å
            case 195:out.append("&Atilde;"); break; //Ã
            case 196:out.append("&Auml;"); break; //Ä
            case 199:out.append("&Ccedil;"); break; //Ç
            case 208:out.append("&ETH;"); break; //Ð
            case 201:out.append("&Eacute;"); break; //É
            case 202:out.append("&Ecirc;"); break; //Ê
            case 200:out.append("&Egrave;"); break; //È
            case 203:out.append("&Euml;"); break; //Ë
            case 205:out.append("&Iacute;"); break; //Í
            case 206:out.append("&Icirc;"); break; //Î
            case 204:out.append("&Igrave;"); break; //Ì
            case 207:out.append("&Iuml;"); break; //Ï
            case 209:out.append("&Ntilde;"); break; //Ñ
            case 211:out.append("&Oacute;"); break; //Ó
            case 212:out.append("&Ocirc;"); break; //Ô
            case 210:out.append("&Ograve;"); break; //Ò
            case 216:out.append("&Oslash;"); break; //Ø
            case 213:out.append("&Otilde;"); break; //Õ
            case 214:out.append("&Ouml;"); break; //Ö
            case 222:out.append("&THORN;"); break; //Þ
            case 218:out.append("&Uacute;"); break; //Ú
            case 219:out.append("&Ucirc;"); break; //Û
            case 217:out.append("&Ugrave;"); break; //Ù
            case 220:out.append("&Uuml;"); break; //Ü
            case 221:out.append("&Yacute;"); break; //Ý
            case 225:out.append("&aacute;"); break; //á
            case 226:out.append("&acirc;"); break; //â
            case 230:out.append("&aelig;"); break; //æ
            case 224:out.append("&agrave;"); break; //à
            case 229:out.append("&aring;"); break; //å
            case 227:out.append("&atilde;"); break; //ã
            case 228:out.append("&auml;"); break; //ä
            case 231:out.append("&ccedil;"); break; //ç
            case 233:out.append("&eacute;"); break; //é
            case 234:out.append("&ecirc;"); break; //ê
            case 232:out.append("&egrave;"); break; //è
            case 240:out.append("&eth;"); break; //ð
            case 235:out.append("&euml;"); break; //ë
            case 237:out.append("&iacute;"); break; //í
            case 238:out.append("&icirc;"); break; //î
            case 236:out.append("&igrave;"); break; //ì
            case 239:out.append("&iuml;"); break; //ï
            case 241:out.append("&ntilde;"); break; //ñ
            case 243:out.append("&oacute;"); break; //ó
            case 244:out.append("&ocirc;"); break; //ô
            case 242:out.append("&ograve;"); break; //ò
            case 248:out.append("&oslash;"); break; //ø
            case 245:out.append("&otilde;"); break; //õ
            case 246:out.append("&ouml;"); break; //ö
            case 223:out.append("&szlig;"); break; //ß
            case 254:out.append("&thorn;"); break; //þ
            case 250:out.append("&uacute;"); break; //ú
            case 251:out.append("&ucirc;"); break; //û
            case 249:out.append("&ugrave;"); break; //ù
            case 252:out.append("&uuml;"); break; //ü
            case 253:out.append("&yacute;"); break; //ý
            case 255:out.append("&yuml;"); break; //ÿ
            case 162:out.append("&cent;"); break; //¢
            default:
              found=false;
              break;
          if(!found)
            if(chars[i]>127) {
              char c=chars[i];
              int a4=c%16;
              c=(char) (c/16);
              int a3=c%16;
              c=(char) (c/16);
              int a2=c%16;
              c=(char) (c/16);
              int a1=c%16;
              out.append("&#x"+hex[a1]+hex[a2]+hex[a3]+hex[a4]+";");    
            else
              out.append(chars[i]);
        return out.toString();

    hi Dan, thanks for asking
    I did this in the end..
    <cfscript>
      // function cleantext(string) {
      //   string = "<p>" & string;
      //   string = Replace(string, chr(13) & chr(10) & chr(13) & chr(10), "</p><p>", "all");
      //   string = Replace(string, chr(13) & chr(10), "<br />", "all");
      //   string = string & "</p>";
      //   return string;
    * HtmlEscape in Java, which is compatible with utf-8
    * @author Ulrich Jensen, http://www.htmlescape.net
    * Feel free to get inspired, use or steal this code and use it in your
    * own projects.
    * License:
    * You have the right to use this code in your own project or publish it
    * on your own website.
    * If you are going to use this code, please include the author lines.
    * Use this code at your own risk. The author does not warrent or assume any
    * legal liability or responsibility for the accuracy, completeness or usefullness of
    * this program code.
    function cleantext(string)  {
      private static char[] hex={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
       * Method for html escaping a String, for use in a textarea
       * @param original The String to escape
       * @return The escaped String
      public static String escapeTextArea(String original)
        return escapeSpecial(escapeTags(original));   
       * Normal escape function, for Html escaping Strings
       * @param original The original String
       * @return The escape String
      public static String escape(String original)
        return escapeSpecial(escapeBr(escapeTags(original)));
      public static String escapeTags(String original)
        if(original==null) return "";
        StringBuffer out=new StringBuffer("");
        char[] chars=original.toCharArray();
        for(int i=0;i<chars.length;i++)
          boolean found=true;
          switch(chars[i])
            case 60:out.append("&lt;"); break; //<
            case 62:out.append("&gt;"); break; //>
            case 34:out.append("&quot;"); break; //"
            default:found=false;break;
          if(!found) out.append(chars[i]);
        return out.toString();
      public static String escapeBr(String original)
        if(original==null) return "";
        StringBuffer out=new StringBuffer("");
        char[] chars=original.toCharArray();
        for(int i=0;i<chars.length;i++)
          boolean found=true;
          switch(chars[i])
            case '\n': out.append("<br/>"); break; //newline
            case '\r': break;
            default:found=false;break;
          if(!found) out.append(chars[i]);
        return out.toString();
      public static String escapeSpecial(String original)
        if(original==null) return "";
        StringBuffer out=new StringBuffer("");
        char[] chars=original.toCharArray();
        for(int i=0;i<chars.length;i++)
            boolean found=true;
          switch(chars[i]) {
            case 38:out.append("&amp;"); break; //&
            case 198:out.append("&AElig;"); break; //Æ
            case 193:out.append("&Aacute;"); break; //Á
            case 194:out.append("&Acirc;"); break; //Â
            case 192:out.append("&Agrave;"); break; //À
            case 197:out.append("&Aring;"); break; //Å
            case 195:out.append("&Atilde;"); break; //Ã
            case 196:out.append("&Auml;"); break; //Ä
            case 199:out.append("&Ccedil;"); break; //Ç
            case 208:out.append("&ETH;"); break; //Ð
            case 201:out.append("&Eacute;"); break; //É
            case 202:out.append("&Ecirc;"); break; //Ê
            case 200:out.append("&Egrave;"); break; //È
            case 203:out.append("&Euml;"); break; //Ë
            case 205:out.append("&Iacute;"); break; //Í
            case 206:out.append("&Icirc;"); break; //Î
            case 204:out.append("&Igrave;"); break; //Ì
            case 207:out.append("&Iuml;"); break; //Ï
            case 209:out.append("&Ntilde;"); break; //Ñ
            case 211:out.append("&Oacute;"); break; //Ó
            case 212:out.append("&Ocirc;"); break; //Ô
            case 210:out.append("&Ograve;"); break; //Ò
            case 216:out.append("&Oslash;"); break; //Ø
            case 213:out.append("&Otilde;"); break; //Õ
            case 214:out.append("&Ouml;"); break; //Ö
            case 222:out.append("&THORN;"); break; //Þ
            case 218:out.append("&Uacute;"); break; //Ú
            case 219:out.append("&Ucirc;"); break; //Û
            case 217:out.append("&Ugrave;"); break; //Ù
            case 220:out.append("&Uuml;"); break; //Ü
            case 221:out.append("&Yacute;"); break; //Ý
            case 225:out.append("&aacute;"); break; //á
            case 226:out.append("&acirc;"); break; //â
            case 230:out.append("&aelig;"); break; //æ
            case 224:out.append("&agrave;"); break; //à
            case 229:out.append("&aring;"); break; //å
            case 227:out.append("&atilde;"); break; //ã
            case 228:out.append("&auml;"); break; //ä
            case 231:out.append("&ccedil;"); break; //ç
            case 233:out.append("&eacute;"); break; //é
            case 234:out.append("&ecirc;"); break; //ê
            case 232:out.append("&egrave;"); break; //è
            case 240:out.append("&eth;"); break; //ð
            case 235:out.append("&euml;"); break; //ë
            case 237:out.append("&iacute;"); break; //í
            case 238:out.append("&icirc;"); break; //î
            case 236:out.append("&igrave;"); break; //ì
            case 239:out.append("&iuml;"); break; //ï
            case 241:out.append("&ntilde;"); break; //ñ
            case 243:out.append("&oacute;"); break; //ó
            case 244:out.append("&ocirc;"); break; //ô
            case 242:out.append("&ograve;"); break; //ò
            case 248:out.append("&oslash;"); break; //ø
            case 245:out.append("&otilde;"); break; //õ
            case 246:out.append("&ouml;"); break; //ö
            case 223:out.append("&szlig;"); break; //ß
            case 254:out.append("&thorn;"); break; //þ
            case 250:out.append("&uacute;"); break; //ú
            case 251:out.append("&ucirc;"); break; //û
            case 249:out.append("&ugrave;"); break; //ù
            case 252:out.append("&uuml;"); break; //ü
            case 253:out.append("&yacute;"); break; //ý
            case 255:out.append("&yuml;"); break; //ÿ
            case 162:out.append("&cent;"); break; //¢
            default:
              found=false;
              break;
          if(!found)
            if(chars[i]>127) {
              char c=chars[i];
              int a4=c%16;
              c=(char) (c/16);
              int a3=c%16;
              c=(char) (c/16);
              int a2=c%16;
              c=(char) (c/16);
              int a1=c%16;
              out.append("&#x"+hex[a1]+hex[a2]+hex[a3]+hex[a4]+";");   
            else
              out.append(chars[i]);
        return out.toString();
    </cfscript>  
    <cfset cleanedtext = cleantext(dirtytext)>
    Although actually I also ended up changing my charset of my tables to utf8 (it was latin_swedish) and that seems to have solved the head issue (with special characters (bullet points i think it was) throwing an error when inserting them in the db)

  • How to convert this Servlet into JSP

    I am trying to convert this Servlet into JSP page.
    How do I go about doing this?
    Thanks.
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.text.*;
    /** Shows all items currently in ShoppingCart. Clients
    * have their own session that keeps track of which
    * ShoppingCart is theirs. If this is their first visit
    * to the order page, a new shopping cart is created.
    * Usually, people come to this page by way of a page
    * showing catalog entries, so this page adds an additional
    * item to the shopping cart. But users can also
    * bookmark this page, access it from their history list,
    * or be sent back to it by clicking on the "Update Order"
    * button after changing the number of items ordered.
    * <P>
    * Taken from Core Servlets and JavaServer Pages 2nd Edition
    * from Prentice Hall and Sun Microsystems Press,
    * http://www.coreservlets.com/.
    * &copy; 2003 Marty Hall; may be freely used or adapted.
    public class OrderPage extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    HttpSession session = request.getSession();
    ShoppingCart cart;
    synchronized(session) {
    cart = (ShoppingCart)session.getAttribute("shoppingCart");
    // New visitors get a fresh shopping cart.
    // Previous visitors keep using their existing cart.
    if (cart == null) {
    cart = new ShoppingCart();
    session.setAttribute("shoppingCart", cart);
    String itemID = request.getParameter("itemID");
    if (itemID != null) {
    String numItemsString =
    request.getParameter("numItems");
    if (numItemsString == null) {
    // If request specified an ID but no number,
    // then customers came here via an "Add Item to Cart"
    // button on a catalog page.
    cart.addItem(itemID);
    } else {
    // If request specified an ID and number, then
    // customers came here via an "Update Order" button
    // after changing the number of items in order.
    // Note that specifying a number of 0 results
    // in item being deleted from cart.
    int numItems;
    try {
    numItems = Integer.parseInt(numItemsString);
    } catch(NumberFormatException nfe) {
    numItems = 1;
    cart.setNumOrdered(itemID, numItems);
    // Whether or not the customer changed the order, show
    // order status.
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Status of Your Order";
    String docType =
    "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
    "Transitional//EN\">\n";
    out.println(docType +
    "<HTML>\n" +
    "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
    "<BODY BGCOLOR=\"#FDF5E6\">\n" +
    "<H1 ALIGN=\"CENTER\">" + title + "</H1>");
    synchronized(session) {
    List itemsOrdered = cart.getItemsOrdered();
    if (itemsOrdered.size() == 0) {
    out.println("<H2><I>No items in your cart...</I></H2>");
    } else {
    // If there is at least one item in cart, show table
    // of items ordered.
    out.println
    ("<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
    "<TR BGCOLOR=\"#FFAD00\">\n" +
    " <TH>Item ID<TH>Description\n" +
    " <TH>Unit Cost<TH>Number<TH>Total Cost");
    ItemOrder order;
    // Rounds to two decimal places, inserts dollar
    // sign (or other currency symbol), etc., as
    // appropriate in current Locale.
    NumberFormat formatter =
    NumberFormat.getCurrencyInstance();
    // For each entry in shopping cart, make
    // table row showing ID, description, per-item
    // cost, number ordered, and total cost.
    // Put number ordered in textfield that user
    // can change, with "Update Order" button next
    // to it, which resubmits to this same page
    // but specifying a different number of items.
    for(int i=0; i<itemsOrdered.size(); i++) {
    order = (ItemOrder)itemsOrdered.get(i);
    out.println
    ("<TR>\n" +
    " <TD>" + order.getItemID() + "\n" +
    " <TD>" + order.getShortDescription() + "\n" +
    " <TD>" +
    formatter.format(order.getUnitCost()) + "\n" +
    " <TD>" +
    "<FORM>\n" + // Submit to current URL
    "<INPUT TYPE=\"HIDDEN\" NAME=\"itemID\"\n" +
    " VALUE=\"" + order.getItemID() + "\">\n" +
    "<INPUT TYPE=\"TEXT\" NAME=\"numItems\"\n" +
    " SIZE=3 VALUE=\"" +
    order.getNumItems() + "\">\n" +
    "<SMALL>\n" +
    "<INPUT TYPE=\"SUBMIT\"\n "+
    " VALUE=\"Update Order\">\n" +
    "</SMALL>\n" +
    "</FORM>\n" +
    " <TD>" +
    formatter.format(order.getTotalCost()));
    String checkoutURL =
    response.encodeURL("../Checkout.html");
    // "Proceed to Checkout" button below table
    out.println
    ("</TABLE>\n" +
    "<FORM ACTION=\"" + checkoutURL + "\">\n" +
    "<BIG><CENTER>\n" +
    "<INPUT TYPE=\"SUBMIT\"\n" +
    " VALUE=\"Proceed to Checkout\">\n" +
    "</CENTER></BIG></FORM>");
    out.println("</BODY></HTML>");
    }

    Sorry.
    actually this is my coding on the bottom.
    Pleease disregard my previous coding. I got the different one.
    My first approach is using <% %> around the whole doGet method such as:
    <%
    String[] ids = { "hall001", "hall002" };
    setItems(ids);
    setTitle("All-Time Best Computer Books");
    out.println("<HR>\n</BODY></HTML>");
    %>
    I am not sure how to break between code between
    return;
    and
    response.setContentType("text/html");
    Here is my coding:
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
         String[] ids = { "hall001", "hall002" };
         setItems(ids);
         setTitle("All-Time Best Computer Books");
    if (items == null) {
    response.sendError(response.SC_NOT_FOUND,
    "Missing Items.");
    return;
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String docType =
    "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
    "Transitional//EN\">\n";
    out.println(docType +
    "<HTML>\n" +
    "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
    "<BODY BGCOLOR=\"#FDF5E6\">\n" +
    "<H1 ALIGN=\"CENTER\">" + title + "</H1>");
    CatalogItem item;
    for(int i=0; i<items.length; i++) {
    out.println("<HR>");
    item = items;
    if (item == null) {
    out.println("<FONT COLOR=\"RED\">" +
    "Unknown item ID " + itemIDs[i] +
    "</FONT>");
    } else {
    out.println();
    String formURL =
    "/servlet/coreservlets.OrderPage";
    formURL = response.encodeURL(formURL);
    out.println
    ("<FORM ACTION=\"" + formURL + "\">\n" +
    "<INPUT TYPE=\"HIDDEN\" NAME=\"itemID\" " +
    " VALUE=\"" + item.getItemID() + "\">\n" +
    "<H2>" + item.getShortDescription() +
    " ($" + item.getCost() + ")</H2>\n" +
    item.getLongDescription() + "\n" +
    "<P>\n<CENTER>\n" +
    "<INPUT TYPE=\"SUBMIT\" " +
    "VALUE=\"Add to Shopping Cart\">\n" +
    "</CENTER>\n<P>\n</FORM>");
    out.println("<HR>\n</BODY></HTML>");

  • How to optimize this code + is design proper

    Well I have to implement tree programming here , what i mean by tree
    programming is i have data stored in tree format i,e I have parent
    object which will have child objects of same type the level of depth can
    go any long:
    I am able to store objects in tree format and also able to display properly Here
    is code but I am facing problems when i have to filter some child nodes based on some conditions:
    I have two question is this code fine is there anything wrong with desin Plus how to handle removing child node in tree scenation where child can be in any place.Below is code
    package menu;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import com.chartis.gp.support.util.BrokerSupportUtil;
    import com.chartis.gp.support.vo.Links;
    import com.chartis.kernel.user.UserVO;
    import com.chartis.kernel.utils.Utils;
    public class Utility{
         /* IN this class NavModel,CModel,CNode are some dummy classes
          * which help us read contents form some resources which are stored in dummy format
          * as Example of tree format stored data below is the example
          *    tree
          *       child1
          *       child2
          *       child3
          *              child3-1
          *                       child:q
          *                       child:r
          *                               child:a
          *              child3-2
          *       child4
         private static void populateChildLinks(NavModel navModel, Object objectNode, Links parent ){
              try{
                   List<Links> childLinks = new ArrayList<Links>();
                   Iterator it = navModel.getChildren( objectNode );
                   while( it.hasNext() ){
                        NavNode node = (NavNode) it.next();
                        CNode contentNode = node.getContentNode();
                        Links links = new Links();
                        links.setNodeName( contentNode.getNodeName() );
                        childLinks.add( links );
                        if( navModel.hasChildren( node ) ){
                             populateChildLinks( node, links );
                   parent.setChildren( childLinks );
              catch( Exception e ){
         private static Links createCategoryLinks(String categoryLinkName){
              Links categoryLinks = new Links();
              categoryLinks.setNodeName( categoryLinkName );
              return categoryLinks;
         public static Links setupLinks(String categoryLinkName,String name) {
              Links categoryLinks=null;
              CModel contentModel = new CModel();
              NavModel navModel = new NavModel();
              categoryLinks = Utility.createCategoryLinks( categoryLinkName);
              Object objectNode = contentModel.getLocator().findByUniqueName(name);
              if( objectNode != null ){
                   if( navModel.hasChildren( objectNode ) ){
                        populateChildLinks( navModel,objectNode, categoryLinks );
                  // This is where i am facing issue once i get list of links of childs
              // i have to delete how can i find that particular child in the list
              // do i have to iterate through all the links and delete or  which
              // way is better
         private static void filterLinks( Links parentNode,
                   List<Links> childNodeList ){
              List<Links> filteredResourceList = new ArrayList<Links>();
              if(  childNodeList!=null ){
                   Iterator<Links> childNodeIt = childNodeList.iterator();
                   while( childNodeIt.hasNext() ){
                        Links childNode = (Links) childNodeIt.next();
                        if(childNode.getChildren().size() >0 ){
                           filterLinks( childNode, childNode.getChildren() );
                        boolean removeNode = filterContents( childNode);
                        if(! removeNode ){
                             filteredResourceList.add( childNode );
              Iterator<Links> filteredResourceIt = filteredResourceList.iterator();
              while( filteredResourceIt.hasNext() ){
                   Links childNode = (Links) filteredResourceIt.next();
                   parentNode.getChildren().remove( childNode );
         // Let us consider this as some dummy method which returns true or false based on some conditions
         private static boolean filterContents( menu.Links childNode ){
              return false;
      package menu;
    import java.util.List;
    public class Links{
          private String nodeName;
         private List<Links> children;
         public List<Links> getChildren(){
              return children;
         public void setChildren( List<Links> children ){
              this.children = children;
         public String getNodeName(){
              return nodeName;
         public void setNodeName( String nodeName ){
              this.nodeName = nodeName;
    package menu;
    public class TreeDisplay{
         public static void main( String[] args ){
          Links link = Utility.setupLinks( "SomeName", "ResiyrbceBane");
           Utility.filterLinks( link, link.getChildren() );
    }Is the utility class with so many static class is ok?

    Vicky wrote:
    Thanks TPD
    If you could write more on it , it will be great i rarely find ocasations of using interfaces , however i don't think creating a new tree with valid node could be better solution as you have to create a new tree keeping the same hierarchy .The advantage is that all other components do not need to know that they work with a filtered tree.
    Certainly you can do it the other way around bye passing the tree and the filter to eg. the <tt>NotePrinter</tt> Object, but than all components working with the tree meight neet to know that ther are Node filters.
    I just came up with the Idea to give the nodes themselfes knowlege of the Filter via <tt>setFilter(Filter<Links> myFilter)</tt>. You would call this on the root node and in the <tt>getChildren()</tt> method you would check if the child apllies to the filter and pass that filter to the eliable childs before putting them into a new collection which is returned to the caller. Ofcause you should initialise the <tt>this.filter</tt> property in <tt>Links</tt> with a <tt>ALL_NODES</tt> constant.
    Also you should resist the tamptation to make the <tt>this.filter</tt> property in <tt>Links</tt> static. This would save you one line of code in the <tt>getCildren()</tt> method by the cost that you cannot have different trees with different filters in the same JVM.
    This kind of interference between threads is pretty hard to find later in production environments...
    bye
    TPD

  • How to test this code ???

    Hi All,
    One quick question:
    ..>>>>How do you test below InterfaceImpl classes in a simple program to test the code ???
    //below is the sample of the example I am running .
    Thanks
    Jack
    //interface 1
    same package;
    interface someInterfaceName1 {
    public void setLastName();
    public String getLastName();
    //inerface 2
    same package;
    interface someInterfaceName2{
    public void setBillingAddress(somename1 billing){
    public void setShippingAddress(somename1 shipping){
    // implementation class1
    samepackage;
    public class someInterfaceName1Impl implements someInterfaceName1 {
    private String lastName="";
    someInterfaceName1Impl();
    public void setLastName(String lastName){
    this.lastName=lastName;
    public String getLastName(){
    return LastName;
    //implementatio class2 for interface 2
    samepackage;
    class someInterfaceName2Impl implements someInterfaceName2
    public void setBillingAddress(interface1 billto){
    billto.setlastName(someValue); --?????
    public void setShippingAddress(interface1 shipto) {
    shipto.setFirstName(someValue); --- ?????
    //How to test the code ??
    package samepackage;
    class testMyCode {
    public static void main(String args[]){
    // how do you get the interfaces implementation here to test with dummy values ????

    Something along these lines (but departing from your code a bit...) public static void test() {
        Interface1 ifc1 = new Impl1();
        String tmpStr;
        int tmpInt;
        ifc1.setName("joe");
        tmpStr = ifc1.getName();
        if (!("joe".equals(tmpStr))) {
            System.err.println("set/getName failed. Put in joe but got out " + tmpStr);
        ifc1.setBirthdate("May 1 1980");
        tmpInt = ifc1.getAge();
        if (tmpInt != 24) {
            System.err.println("setBirthdate/getAge failed. Put in May 1 1980, expected 24 but got " + tmpInt);
        try {
            tmpStr = "Booger 99, 19seventy-beer";
            ifc1.setBirthdate(tmpStr);
            //shouldn't get here
           System.err.println("setBirthdate accepted invalid date: " + tmpStr);
        catch (InvalidBirthdateException exc) {
            // we want this, since it means our code properly rejected a bad date
    } Or, when you start writing serious code, look into junit
    &#12472;

  • In general, how do I put code into a loop?

    I have access to a procedure that takes a parameter and spits out a single result. I need to figure out how to use that procedure and spit out many results. This example should clear things up.
    VARIABLE enum NUMBER;
    EXEC :enum := 7566;
    -- my procedure. Cannot change code here.
    -- Prints out a formatted name and job, given an empno stored in :enum
    SELECT ename || ' (' || job || ')' AS "myrow"
    FROM scott.emp
    WHERE empno = :enum;
    -- end of my procedureHere, I can't change anything from the SELECT to the semi-colon. Now I would like to put this into a PL/SQL LOOP, but I can't figure it out. Let's say I want to print out all of the employees with a job of manager. Somehow I will need enum to take the value of the current iteration from within the loop.
    something like this:
    BEGIN
    -- first get the list of employees
    CURSOR e_cur IS
    SELECT empno
    FROM scott.emp
    WHERE job="MANAGER';
    END;
    BEGIN
    FOR r_cur IN e_cur LOOP
    :enum = r_cur.empno
    -- my procedure. Cannot change code here.
    -- Prints out a formatted name and job, given an empno stored in :enum
    SELECT ename || ' (' || job || ')' AS "myrow"
    FROM scott.emp
    WHERE empno = :enum;
    -- end of my procedure
    END LOOP;
    END;
    {code}
    of course, this code does not work, and I don't know what else to try.
    Thanks in advance for any help!
    Skip                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Oh boy, do I owe you guys an apology. Absolutely no excuse, but I screwed up big time yesterday. I am working on a couple of projects and got some wires crossed. I would like to start over. Forget everything I asked yesterday. I wouldn't be surprised if no one answered, but I could still use some help. I am embarrassed because I am usually pretty good at these things, and again, I humbly apologize.
    Still with me? Here we go:
    I have a SQL script that is quite long. It has 25 select statements, 4 unions, 7 minus'es, lots of joins, sub-queries, etc. The script expects two bind variables to be set before running. The code was written to execute once (like a report). But the code does exactly what I need, but I need to run it on a much larger set. So I would like to wrap it in a loop. Now, I am pretty good at other programming languages (I know, hard to believe given yesterday's exchange). If I have some java code that I want to wrap in a FOR-NEXT loop, often all I need to do is put one line at the top of the code and one line at the bottom. Then I make sure the variables that need t be updated through each iteration are properly updated. Bada-bing, bada-boom, it's done.
    It doesn't seem as easy here. I know that I will have to convert my SQL script to PL/SQL. But I am wrestling with the DECLAREs, BEGINs and LOOPs, and changes to the existing code to ensure the bind variables are updated each iteration. I have tried all of what I thought would be the simple solutions as I described with my java example above, but it has not worked. So, as my subject line indicates, I was wondering if there was a general methodology to LOOP-ifying existing code. I know this is a pretty nebulous question, and I probably blew it yesterday, but I really do need some help. Even if it is "read this and that website/book/etc". That's really it. sigh All that stuff yesterday about "unmodifiable code"--forget about that. I should never have said that. Anything goes.
    Maybe there isn't a simple solution here. SQL isn't Java. And that's OK. At least then I will know I will need to look for a different solution or I will have to get a LOT smarter with SQL and PL/SQL. I thought my super-simple example yesterday was a good enough substitute for what I am faced with, but maybe that isn't a good assumption.

Maybe you are looking for

  • Login as SYSDBA or SYSOPER

    Can OO4O connect with SYS as SYSDBA or SYSOPER. we have certain scripts that run with 'sys' username only. This needs to be executed when an adminsitrator clicks a button on our website. I tried the following: Set OraDatabase=OraSession.OpenDatabase(

  • CS3 master suite installation complete Finally

    Finally   I Was able to get CS3 Master suite installed . all of it. by just doing it one  to two programs at a time. ( or a complete suite) which worked perfectly. after months of playing around with this program which was poorly designed as a suite

  • InDesign Server Stops Including INDD Files

    We are generating a book and use InDesign to create the exhibits (art) that go into the book. We have over 140 INDD files that are referenced by the book INDD. When the server reaches about the 140 mark it suddenly stops pulling in the remaining INDD

  • Can i set organizer in pse9 to see only videos?

    It seems logical there must be a way to set organizer in PSE 9 to display videos only. Any suggestion greatly appreciated. Thanks

  • Hp deskjet 3050 j611

    I have searched the internet and searched this site and after 2 full days of trying to connect my computer I cannot.  I have (2) imacs running Lion and I can not get the printer to  work wirelessly.  The one works fine when plugged into the usb.  How