JSP - ImageLoader from Database (BalusC code)

ImageServlet
Firstly @ BalusC amazing code thanx
I have been playing with the ImageServlet and Wow.
It works perfectly
Here is my problem:
I want to load the image from my SQL Server 2000 database
but when I load the image it doesn't display and no errors occur
public class SQLImage{
  Connection conn = null;
  public SQLImage(){
    //init();
  public byte[] getImage(String name){
    try{
      PreparedStatement prepStat = conn.prepareStatement("SELECT [DATA] FROM [IMAGE_TABLE] WHERE [NAME] = '" + name + "'");
      ResultSet rs = prepStat.executeQuery();
      byte[] bytes = null;
      if(rs.hasNext())
        bytes = rs.getBytes(1);
      return bytes;
    }catch(Exception ex){
      ex.printStackTrace();
      return null;
  } The only thing I have changed on the ImageServlet is:
FROM
BufferedInputStream input = null;
BufferedOutputStream output = null;
        try {
            // Open image file.
            input = new BufferedInputStream(new FileInputStream(imageFile)); TO
BufferedInputStream input = null;
BufferedOutputStream output = null;
SQLImage sqlImage = new SQLImage();
        try {
            // Open image file.
            byte[] data = sqlImage.getImage(imageFileName);
            if(data == null){
              JOptionPane.showMessageDialog(null,"Null Value");
              return;
            input = new BufferedInputStream(new ByteArrayInputStream(data)); The Dialog is never displayed so that means that data contains a value
I take it the image data in the DB is the same as the image file
can anyone tell me what has changed and why it doesn't work?

DM_Is_SM
You know me to well,
I found the problem as suggested
        if (!imageFile.exists()) {
            // Do your thing if the file appears to be non-existing.
            // Throw an exception, or show default/warning image, or just ignore it.
            return;
        } as the file was located on the DB it will always return;.
I removed all the unnecessary code from ImageServlet
And this is the working code I am left with for ImageServlet
package mypackage;
import DataBase.SQL.SQLImage;
import java.io.ByteArrayInputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLConnection;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
* The Image servlet for retrieving image from Database
* @author BalusC - original
* @author gtRpr - Edited
* @link Orig - http://balusc.blogspot.com/2007/04/imageservlet.html
* @link Edit - http://forum.java.sun.com/thread.jspa?messageID=10340335
public class ImageServlet extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
    String imageFileName = request.getParameter("file");
    Validate:
      imageFileName = imageFileName.replaceAll("'","<Apos">);
//    replace all ' chars with <Apos> when image is added to DB
//    and when retrieved from DB
//    Helps prevent SQL injection
//    EG:
//    "image?id=';TRUNCATE TABLE Image--"
//    Becomes
//    "image?id=<Apos>;TRUNCATE TABLE Image--"
    // Prepare streams.
    SQLImage sqlImage = new SQLImage();
    BufferedInputStream input = null;
    BufferedOutputStream output = null;
    try {
      // Open image file.
      input = new BufferedInputStream(new ByteArrayInputStream(sqlImage.ReadImage(imageFileName)));
      int contentLength = input.available();
      // Init servlet response.
      response.reset();
      response.setContentLength(contentLength);
      response.setHeader("Content-disposition", "inline; filename=\"" + imageFileName + "\"");
      output = new BufferedOutputStream(response.getOutputStream());
      // Write file contents to response.
      int data;
      while ((data = input.read()) != -1) {
        output.write(data);
      // Finalize task.
      output.flush();
    } catch (IOException e) {
      // Something went wrong?
      response.sendredirect("Error.jsp";);
    } finally {
      // Gently close streams.
      output.close();
      input.close();
}

Similar Messages

  • Error:Failed to retrieve data from database [Vendor Code:3001]

    Hello FOlks am trying to run a crystal report but when i try to run it somehow returns this error i.e [Error:Failed to retrieve data from database [Vendor Code:3001], I have no clue wats happening with this.Can anybody please throw some light on this.Am providing the sql behind this report for reference.
    SELECT "CLIENT"."CLIENT_NAME",
            "RECOVERY"."AMOUNT",
            "RECOVERY"."RECOVERY_TRANSACTION_INTERNAL",
            "RECOVERY"."ALLOCATION_CHECK_AMOUNT",
            "RECOVERY"."RECOVERY_DATE"
       FROM "HRI1_OWNER"."CLIENT""CLIENT",
            "HRI1_OWNER"."EVENT_CASE""EVENT_CASE",
            "HRI1_OWNER"."SETTLEMENT""SETTLEMENT",
            "HRI1_OWNER"."RECOVERY""RECOVERY"
      WHERE "CLIENT"."CLIENT_ID" = "EVENT_CASE"."CLIENT_ID"
        AND "EVENT_CASE"."EVENT_CASE_ID" = "SETTLEMENT"."EVENT_CASE_ID"
        AND "SETTLEMENT"."SETTLEMENT_ID" = "RECOVERY"."SETTLEMENT_ID"
        AND "CLIENT"."CLIENT_CODE" <> 'CLIENT  1'
        AND "CLIENT"."MAJOR_CLIENT_ID" in
            (Select major_client_id
               from major_client
              where major_client_code in ('LA', 'PFG'))
      ORDER BY "CLIENT"."CLIENT_NAME"Edited by: user11961230 on Nov 12, 2009 6:57 AM

    @oradba:Hi Thanks for getting bak. Well i have ran the query using PL/SQL Developer tool and yes its mapping to ORA-03001:unimplemented feature. i dont know what the problem is.
    @centinul: well i dont have any views in there.but still cudnt figure out why its throwing tht error
    Thanks
    Edited by: user11961230 on Nov 12, 2009 7:12 AM

  • Select list in JSP (Options from database)

    I am developing a web application on struts.
    I am having problem with my JSP.
    I have a form from where users input the keywords for search
    and when they click on a database query is performed and
    result is shown on the screen.
    Where i am stuck is that in the display screen, i wanna have one
    set of result in the drop down list (same as select in html).
    If the result from the database search is 1 i want the first option of
    select to be Yes and if its 0 then i want the first option of select to be
    No.
    what i have in JSP is following
    <select name="attt" size="2"><option value="<bean:write name="sList" property="att"/>">Yes
    <option value="<bean:write name="sList" property="att"/>">No
    Where I am stuck is that I dont know where to perform whether the
    result from database is 1 or not. Can someboday help me on how
    to solve this or get this done? Am i right so far?
    thanx in advance

    The best I could come up with was to use the second layout I mention and then add some Javascript on the page to do something like
    <style type="text/css">
    label.l {position:absolute;top:100px;left:210px;}
    input.i {position:absolute;top:100px;left:200px;}
    </style>
    <script type="text/javascript">
    var f=$x('P1_RADIO');
    var l=f.getElementsByTagName('label')[1];
    var i=f.getElementsByTagName('input')[1];
    l.className += "l";
    i.className += "i";
    </script>Basically, it takes that "Radiogroup Option 2" and the form input field and uses absolute CSS positioning to place it to the right of the Select list.
    Works great in FF (as usual), but the usual IE inconsistencies with CSS box model rear their ugly head. Looks terrible in IE, totally mis-aligned.
    Any other ideas?
    Thanks

  • Code that handles a set of questions from database and place it on JSP

    Hi,
    How to write a code that handles a set of Quiz questions from database and place it on JSP page..
    Thanks in advance
    Haritha

    975033 wrote:
    Hi,
    I hav got the answer from you r previous link, but not completly. I need help regarding on how to do code that handles a set of questions from database and place it on JSP.
    Any help is highly appreciated.Yes but what kind of help do you expect to get? What kind of help do you think is possible through something as cold and distant as a forum, where you clearly require personal guidance and tutoring?
    If you are going to answer "example code", I should warn you that the answers are not going to be to your liking.

  • From database to jsp form drop downlist

    is there a way to put database values from certain fields in the database,into the dropdown list in my jsp form?
    if there is a way what do they call that method?

    hi,
    First you retrive the fields from database and store those values in a List or any collection.
    after that write the code in jsp as like this..
    <select name="list" >
    <%                    
         for(int i=0;i<dblist.size();i++)
              String listitem = dblist.get(i);
    %>
          <option value="<%=listitem%>">
          <%=listitem%>
    <%             
    %>
    </select>Here dblist is a collection which contains the fields which you retrived from the database
    regards,
    sekhar.alla

  • How to gather option values from database in jsp

    jsp experts
    my problem is that i have to populate the optional values that user has to selecet his choice .
    we could have done it by :
    <optional value="item1">item1
    <optional value="item2">item2
    </select>
    but in our database if new category of item is enlisted then what ??? ,thats why we go for populating the values from fetching from database by simple class & populate values in the optional values.
    can any one help about it

    Hi Avina,
    You need to invoke a method from your jsp file which interacts with the database. If you are following the MVC pattern which segregates the View and Contoller part, invoke the controller jsp from your View using the include tag.
    Say this is the View.jsp
    // all your initial page include statements --
    <%
    // all your java code (if necessary)
    %>
    <jsp:include page="Controller.jsp" >
    <jsp:param name="command" value="getOptionList"/>
    </jsp:include>
    <!-- all your html tags -->
    // If you are following my technique, there should be a Controller.jsp which interacts with your database thru some class which you instantiate in this jsp, which invokes some method (that is why i have passed a parameter, so that if u want to make a check you can do so - u may or may not pass the parameters - based on ur requirements).
    Code in Controller.jsp:
    <%
    // MyClass is the class which does the querying into the database.
    // obj.getOptions() is a method in that class which returns a Vector
    // containing all the options from your database.
    // Please ensure that you import the package in this jsp file, so as
    // to get the MyClass.class in this jsp.
    String getWhat = request.getParameter("command");
    if ( getWhat != null && getWhat.equalsIgnoreCase("command") ) {
    MyClass obj = new MyClass();
    java.util.Vector optionsAvailable = obj.getOptions();
    session.setAttribute("Options", optionsAvailable);
    %>
    -------------- End of Controller.jsp related work ---------------
    // Returning back to the code in the View.jsp:
    Once the including is over, the control will return to the next line of code in View.jsp. Just retrieve the data from the session:
    Continued - View.jsp
    <select name="itemsInDB">
    <option value="Select"> Select </option>
    <%
    /* Now you have a vector containing all the options from
    your database. */
    java.util.Vector vecOptions = (java.util.Vector)
    session.getAttribute("Options");
    for (int i=0; i<vecOptions.size(); i++) {
    %>
    <option value="<%=vecOptions.elementAt(i)%>"><%=vecOptions.elementAt(i)%></option>
    <%
    %>
    </select>
    Well thats all thats required. Your problem is solved. You will get a list of all the options in your database. Happy Coding

  • Why database related code not wriiten in jsp's

    hi all
    what all resons are there for which database related code
    is not written in jsp's
    one thing that i know is
    it's not a j2ee architecture to do so
    so is it the thing that doing so hits the performance issue
    thanx

    Me, I'm still trying to get my head around Java 1.5, J2EE, Tomcat, JBoss, and Oracle RAC (both programming and DBAing)... My head hurts... Badly...
    Back to the topic, though... I also agree with the previous posters...
    I agree there are exceptions to the "no JDBC in JSP rule of thumb"- I have a JSP-based generic table browser as a tool for emergency maintenance from a (presumably) hostile network, it provides read-only access and automatic password rotation. The flexibility of having it in the JSP has saved my bacon in a crisis; when travelling, I had to talk a non-programmer through applying a code fix (damn developers, using reserved words as column name...)( I had the source on my laptop...). To get a class file fixed, I would have had to get a programmer on the phone, and get the server to reload the class which in our environment at the time required an application restart... The project I work on is about 70 man-years of work, mostly Java, and we have maybe 6 or 8 JSPs that access the DB directly...
    Most of the time though, good design says that you access a particular "type" of data (table or group of tables) in the same "chunk" of code, jsp or class file. It's a lot harder to share a jsp among different invokers than it is a class file. It's also better to isolate presentation from data access.
    Imagine that you have a "USER" table, with first name, last name, username, and password. You program a "login" jsp, a user "edit" jsp and an administrator "edit" jsp. Then a security audit declares that saving an unexcrypted password in the database is insecure; you now have to change evey place that can access the password. If the user object was accessed through a single Java class file, then there would be only one place to fix. Of course, it's possible to use jsp includes to simulate class files, but that's just about as much work as creating the class file to begin with, with more problems.
    Another big advantage of keeping your data access out of JSPs is that you can write unit tests much more easily for the Java classes, using something like JUnit. You can have a set of tests for all your persisted data, which can be run anytime your data model changes. This makes it a lot harder for "side effect" bugs to creep into your code.

  • Maching Chart on jsp page by retriving the data from database

    Hi.
    I want to draw bar, pi etc chart on the web page by getting the values from database oracle while implementing in jsp. kindly tell me how i can do this. Please write down the detailed code for it. Thankx.

    Maybe you should try Cewolf which is a chart tag library based on JFreeChart to generate all kinds of charts in a JSP. See http://cewolf.sourceforge.net.
    Regards,
    Guido

  • Swing Applet in JSP: problem with fetching data from database

    i am facing a problem while fetching data from database using Swing Applet plugged in a JSP page.
    // necessary import statements
    public class NewJApplet extends javax.swing.JApplet {
    private JLabel jlblNewTitle;
    private Vector vec;
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    NewJApplet inst = new NewJApplet();
    frame.getContentPane().add(inst);
    ((JComponent)frame.getContentPane()).setPreferredSize(inst.getSize());
    frame.pack();
    frame.setVisible(true);
    public NewJApplet() {
    super();
    initGUI();
    private void initGUI() {
    try {
    this.setSize(542, 701);
    this.getContentPane().setLayout(null);
    jlblTitle = new JLabel();
    this.getContentPane().add(jlblTitle);
    jlblTitle.setText("TITLE");
    jlblTitle.setBounds(197, 16, 117, 30);
    jlblTitle.setFont(new java.awt.Font("Dialog",1,20));
    jlblNewTitle = new JLabel();
    this.getContentPane().add(jlblNewTitle);
    Vector vecTemp = getDBDatum(); // data fetched fm DB r stored here.
    jlblNewTitle.setText(vecTemp.get(1).toString());
    jlblNewTitle.setBounds(350, 16, 117, 30);
    jlblNewTitle.setFont(new java.awt.Font("Dialog",1,20));
    } catch (Exception e) {
    e.printStackTrace();
    }//end of initGUI()
    private Vector getDBDatum() {
    // fetches datum from oracle database and stores it in a vector
    return lvecData;
    }//end of getDBDatum()
    }//end of class
    in index.jsp page i have included the following code for calling this applet:
    <jsp:plugin type="applet" code="NewJApplet.class" codebase="applets"
    width="600" height="300">
    <jsp:fallback>Could not load applet...</jsp:fallback>
    </jsp:plugin>
    if i view it in using AppletViewer it runs perfectly and display the data in JLabel. (ie, both jlblTitle and jlblNewTitle).(ie, DATA FETCHES FROM db AND DISPLAYS PROPERLY)
    BUT IF I CLICK ON INDEX.JSP, ONLY jlblTitle APPEARS. jlblnNewTitle WILL BE BLANK(this label name is supposed to fetch from database)
    EVERY THING IS DISPAYING PROPERLY EXCEPT DATA FROM DATABASE!!!
    i signed the applet as follows :
    grant {
    permission java.security.AllPermission;
    Can any body help me to figure out the problem?

    This is the Swing Applet java code
    import java.awt.Dimension;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Vector;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.JScrollPane;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTree;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.SwingConstants;
    public class HaiApplet extends javax.swing.JApplet {
         private JLabel     jlblTitle;
         private JLabel     jlblNewTitle;
         private Vector     vec;
         * main method to display this
         * JApplet inside a new JFrame.
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              NewJApplet inst = new NewJApplet();
              frame.getContentPane().add(inst);
              ((JComponent)frame.getContentPane()).setPreferredSize(inst.getSize());
              frame.pack();
              frame.setVisible(true);
         public HaiApplet() {
              super();
              initGUI();
         private void initGUI() {
              try {               
                   this.setSize(542, 701);
                   this.getContentPane().setLayout(null);
                        jlblTitle = new JLabel();
                        this.getContentPane().add(jlblTitle);
                        jlblTitle.setText("OMMS");
                        jlblTitle.setBounds(197, 16, 117, 30);
                        jlblTitle.setFont(new java.awt.Font("Dialog",1,20));
                        jlblTitle.setHorizontalAlignment(SwingConstants.CENTER);
                        jlblTitle.setForeground(new java.awt.Color(0,128,192));
                        jlblNewTitle = new JLabel();
                        this.getContentPane().add(jlblNewTitle);
                        Vector vecTemp = getDBDatum();
                        jlblNewTitle.setText(vecTemp.get(1).toString());
                        jlblNewTitle.setBounds(350, 16, 117, 30);
                        jlblNewTitle.setFont(new java.awt.Font("Dialog",1,20));     
              } catch (Exception e) {
                   e.printStackTrace();
         }//end of initGUI()
         private Vector getDBDatum() {
              Vector lvecData = new Vector(10,5);
              Connection lcon = null;
              Statement lstmt = null;
              ResultSet lrsResults = null;
              String lstrSQL = null;
              String lstrOut = null;
              try {
                   OmmsDBConnect db = new OmmsDBConnect();
                   lcon = db.connectDb();
                   lstmt = lcon.createStatement(lrsResults.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
                   lstrSQL = "select DT_ID from P_DATATABLES";
                   lrsResults = lstmt.executeQuery(lstrSQL);        
                   int i = 0;
                   lrsResults.last();
                   int length = lrsResults.getRow();
                   System.out.println(length);
                   lrsResults.beforeFirst();
                   int recCount = 0;
                   while (lrsResults.next()) {
                        recCount++;
                        lvecData.addElement(new String(lrsResults.getString("DT_ID")));
                   //     System.out.println("ID :  " + lrsResults.getString(1));
                        i++;
                   }System.out.println("here 3 out fm while");
              catch(SQLException e) {
                   System.out.print("SQLException: ");
                   System.out.println(e.getMessage());
              catch(Exception ex) {
                   lstrOut = "Exception Occured " + ex.getMessage();
              finally {
                   try {
                        lrsResults.close();
                        lstmt.close();
                        lcon.close();
                        System.out.println("[DONE]");
                   catch(Exception e) {
                        System.out.println(e);
             }//end of finally
              return lvecData;
         }//end of getDBDatum()
    }//end of classOfcourse the above code compiles and runs well. in Applet Viewer
    I plugged the above Swing Applet in a JSP page index.jsp
    <jsp:plugin type="applet" code="NewJApplet.class" codebase="applets"
                   width="600" height="300">
         <jsp:fallback>Could not load applet...</jsp:fallback>
    </jsp:plugin>Every thing is working fine in AppletViewer...But if i view this in any browser, then only the jlblTitle is displaying. jlblNewTitle is not displaying(this label name is actually fetching from thedatabase)
    can any body help me regarding this matter.? Thx in Advance.

  • Setting the Data into a DropDownListBox in index.jsp from DataBase

    Hi,
    I want to put some data in dropdownlist.
    // in PageFlow Controller class
    public String[] items = {"aaa","bbb","ccc"};
    and in index.jsp
    <netui:select optionsDataSource="{pageFlow.items}" dataSource="{actionForm.selections}">
    I run the index.jsp and getting the dropdownlist with items aaa,bbb and ccc.
    Now I place a method in begin() method
    String[] items = conn.getData();//which returns data from database
    but the begin() method is not executed when I run the index.jsp after that I put the code
    String[] items = conn.getData(); in action() method
    it is giving the dropdownlist but after submitting the form i.e after calling the action.
    please tell me how the items will be set to listbox before action i.e when I run the index.jsp.Where can I put the code
    String[] items = conn.getData();
    and why the begin() method is not invoking.
    Regards,
    Sivaram

    Hi,
    I'm not sure if you have solved this yet?
    The issue you are facing is that you are loading the JSP directly. When you do this the pageflow will not be called and so the begin function not called.
    If you simply enter the URL of the pageflow instead of the JSP this will call the begin function, loading your dropdown values, and it should then redirect through an action to your index.jsp
    Hope that this helps
    Cheers
    IV

  • Setting the Data into a DropDownList in index.jsp from Database

    Hi,
    I want to create a Dynamic dropdownlist.
    // in PageFlow Controller class
    public String[] items = {"aaa","bbb","ccc"};
    and in index.jsp
    <netui:select optionsDataSource="{pageFlow.items}" dataSource="{actionForm.selections}">
    I run the index.jsp and getting the dropdownlist with items aaa,bbb and ccc.
    Now I place a method in begin() method
    String[] items = conn.getData();//which returns data from database
    but the begin() method is not executed when I run the index.jsp after that I put the code
    String[] items = conn.getData(); in action() method
    it is giving the dropdownlist but after submitting the form i.e after calling the action.
    please tell me how the items will be set to listbox before action i.e when I run the index.jsp.Where can I put the code
    String[] items = conn.getData();
    and why the begin() method is not invoking.
    Regards,
    Sivaram

    Hi,
    I'm not sure if you have solved this yet?
    The issue you are facing is that you are loading the JSP directly. When you do this the pageflow will not be called and so the begin function not called.
    If you simply enter the URL of the pageflow instead of the JSP this will call the begin function, loading your dropdown values, and it should then redirect through an action to your index.jsp
    Hope that this helps
    Cheers
    IV

  • How to specifiy the provider to be Oracle.ManagedDataAccess.Client when creating a dynamic connection string with EF Code First from Database?

    I am trying to use the relatively new Code First from Database with the newest EF (6.x) and on an Oracle database (11g, but I have installed the newest ODTwithODAC). First of all, it works fine as long as the connection string is inside the App.Config file. But when I try to build it dynamically in the C# code (or rather, statically at the moment) it fails. I have it working with a dynamically built connection string when doing Model from Database though, so I'm at a loss right now.
    First, I have created a second constructor for the context class that takes a string and does base(connectionString). Then I build the connection string via
    OracleConnectionStringBuilder oracleBuilder = new OracleConnectionStringBuilder();
    oracleBuilder.DataSource = "TEST.BLA.COM";
    oracleBuilder.UserID = "ABC";
    oracleBuilder.Password = "abc";
    oracleBuilder.PersistSecurityInfo = true;
    string connection = oracleBuilder.ToStrin();
    Now trying to open an EntityConnection by giving to it this provider-specific connection string (or even the static one from the App.Config) doesn't work; I get "keyword not supported: user id"). Trying it by creating a context and giving this connection string doesn't work either. I'm pretty sure that this is because I didn't specify the provider to use; after all, it should use the Oracle.ManagedDataAccess.Client provider and not an SQL Server based one.
    I then tried to get around this by using an EntityConnectionStringBuilder on top and specifying the provider keyword there, but then I get "keyword not supported: provider" when using it in the context constructor, and "the 'metadata' keyword is always required" when using it with the EntityConnection constructor.
    As I said above: I bet it's the provider that I have to specify somehow, but I don't know how. The code that does work is the following:
    using (var context = new Model())
    context.Database.Connection.Open();
    context.Database.Connection.Close();
    When I read context.Database.Connection.ConnectionString, it is exactly the provider-specific connection string I created above, but I don't know where to specify the provider again. Do you know of any way to do this? Certainly there must be one.
    PS: I have also posted this question on http://stackoverflow.com/questions/27979454/ef-code-first-from-database-with-managed-oracle-data-access-dynamic-connection because it is quite urgent and I'd like to use Code First from Database. Otherwise I'd have to go "back" to using Model from Database again, which is not ideal because we have updatable views where the .edmx-file has to be edited after every reload of the model, while with Code First from DB inserting into the view automatically works.

    I am trying to use the relatively new Code First from Database with the newest EF (6.x) and on an Oracle database (11g, but I have installed the newest ODTwithODAC). First of all, it works fine as long as the connection string is inside the App.Config file. But when I try to build it dynamically in the C# code (or rather, statically at the moment) it fails. I have it working with a dynamically built connection string when doing Model from Database though, so I'm at a loss right now.
    First, I have created a second constructor for the context class that takes a string and does base(connectionString). Then I build the connection string via
    OracleConnectionStringBuilder oracleBuilder = new OracleConnectionStringBuilder();
    oracleBuilder.DataSource = "TEST.BLA.COM";
    oracleBuilder.UserID = "ABC";
    oracleBuilder.Password = "abc";
    oracleBuilder.PersistSecurityInfo = true;
    string connection = oracleBuilder.ToStrin();
    Now trying to open an EntityConnection by giving to it this provider-specific connection string (or even the static one from the App.Config) doesn't work; I get "keyword not supported: user id"). Trying it by creating a context and giving this connection string doesn't work either. I'm pretty sure that this is because I didn't specify the provider to use; after all, it should use the Oracle.ManagedDataAccess.Client provider and not an SQL Server based one.
    I then tried to get around this by using an EntityConnectionStringBuilder on top and specifying the provider keyword there, but then I get "keyword not supported: provider" when using it in the context constructor, and "the 'metadata' keyword is always required" when using it with the EntityConnection constructor.
    As I said above: I bet it's the provider that I have to specify somehow, but I don't know how. The code that does work is the following:
    using (var context = new Model())
    context.Database.Connection.Open();
    context.Database.Connection.Close();
    When I read context.Database.Connection.ConnectionString, it is exactly the provider-specific connection string I created above, but I don't know where to specify the provider again. Do you know of any way to do this? Certainly there must be one.
    PS: I have also posted this question on http://stackoverflow.com/questions/27979454/ef-code-first-from-database-with-managed-oracle-data-access-dynamic-connection because it is quite urgent and I'd like to use Code First from Database. Otherwise I'd have to go "back" to using Model from Database again, which is not ideal because we have updatable views where the .edmx-file has to be edited after every reload of the model, while with Code First from DB inserting into the view automatically works.

  • Pass the data back from the jsp page to the java code

    Hi,
    I have written an iView that receives an event using EPCF and extracts data from the client data bag.
    I need this iView to pass the data back from the jsp page to the java code.
    I am trying to do this using a hidden input field, but I cannot get the code to work.
    Here is the code on the jsp page.
    <%@ taglib uri="tagLib" prefix="hbj" %>
    <hbj:content id="myContext" >
      <hbj:page title="PageTitle">
       <hbj:form id="myFormId">
    <hbj:inputField id="myInputField" type="string" maxlength="100" value="" jsObjectNeeded="true">
    <% myInputField.setVisible(false);%>
    </hbj:inputField>      
       </hbj:form>
      </hbj:page>
    </hbj:content>
    <script language=JavaScript>
    EPCM.subscribeEvent("urn:com.peter", "namedata", window, "eventReceiver");
    function eventReceiver(eventObj) {
         var url = eventObj.dataObject;
         var funcName = htmlb_formid+"_getHtmlbElementId";
         func = window[funcName];
         var ipField = eval(func("myInputField"));
         ipField.setValue(url);
         var form = document.all(htmlb_formid);
         form.submit();
    </script> 
    Here is my java code
    package com.sap.training.portal;
    import com.sapportals.htmlb.InputField;
    import com.sapportals.htmlb.page.DynPage;
    import com.sapportals.htmlb.page.PageException;
    import com.sapportals.portal.htmlb.page.JSPDynPage;
    import com.sapportals.portal.htmlb.page.PageProcessorComponent;
    public class ListSalesOrder extends PageProcessorComponent {
      public DynPage getPage(){
        return new ListSalesOrderDynPage();
      public static class ListSalesOrderDynPage extends JSPDynPage{
         private String merong;
        public void doInitialization(){
        public void doProcessAfterInput() throws PageException {
              InputField reportfld = (InputField) getComponentByName("myInputField");
              if (reportfld != null)      merong = reportfld.getValueAsDataType().toString();
        public void doProcessBeforeOutput() throws PageException {
              if ( merong != null ) setJspName("merong.jsp");
              else setJspName("ListSalesOrder.jsp");
    Here is DD
    <?xml version="1.0" encoding="utf-8"?>
    <application>
      <application-config>
        <property name="SharingReference" value="com.sap.portal.htmlb"/>
        <property name="PrivateSharingReference" value="com.sap.portal.htmlb"/>
      </application-config>
      <components>
        <component name="SearchSalesOrder">
          <component-config>
            <property name="ComponentType" value="jspnative"/>
            <property name="JSP" value="/pagelet/SearchSalesOrder.jsp"/>
          </component-config>
          <component-profile>
            <property name="tagLib" value="/SERVICE/htmlb/taglib/htmlb.tld"/>
          </component-profile>
        </component>
        <component name="ListSalesOrder">
          <component-config>
            <property name="ClassName" value="com.sap.training.portal.ListSalesOrder"/>
          </component-config>
          <component-profile>
            <property name="tagLib" value="/SERVICE/htmlb/taglib/htmlb.tld"/>
          </component-profile>
        </component>
      </components>
      <services/>
    </application>
    After receive event, then call java script function "eventReceiver" and call "form.submit()".
    But .. PAI Logic in Java code doesn't called ...
    Where is my problme ?
    Help me ...
    Regards, Arnold.

    Hi Arnold,
    you should not do a form.submit yourself. Instead you can put a component called ExternalSubmit to your page:
    ExternalSubmit exSubmit = new ExternalSubmit("EX_SUBMIT"));
    exSubmit.setServerEventName("MyEvent");
    This results in a java script funtion on the page which is called "_htmlb_external_submit_". If you call this function the the form gets submitted and your event handler is called.
    regards,
    Martin

  • Getting image path from database( Remote server)  & display in jsp page

    hai frnds,
    i have one doudt regarding in my web application Development
    . I want to Getting image path from database( **Remote server**) & display in jsp page here iam forwarding my control through Servlets
    how this will passiable
    Thanks in Advance
    SonyKamesh
    [email protected]

    hai
    I think ur doubt will be...
    1) Getting a Image From Remote Server( & U stored a only path name in Data Base)
    2) Image r stroed in saparate Drive( Not in Webroot-- where u Created domine )
    Please Any Help Will be Appriciated
    [email protected]
    Edited by: Sonykamesha on Dec 18, 2007 11:02 PM

  • Failed to retrieve data from the database Database Vendor Code: 2812

    Hi everyone
    Im using Sap Business One Version 2007A SP00 PL49, SQL 2005 and Crystal Reports Basic for Sap Business One (Add on 2.0.0.7). Whenever i try to generate a report from SBO the system displays the following message "Failed to retrieve data from the database DETAILS: [Database Vendor Code: 2812]"
    The scenario is that, according to the Colombia's product local expert, Is not possible to create Stored Procedures, Views, Functions or anything in the customer productive database, in order to improve the performance of the query i created other DB where i created an stored procedure, after that, i called it from Crystal where it's working ok. But when i try to generate it from SBO it show the message promted.
    Someone knows what could be happening
    I'll be thankful

    Hi Cesar,
    Please post your question to the Business One forum.
    I can't move this thread.
    Thank you
    Don

Maybe you are looking for