Af:foreach Question?

I am not sure if I am using a foreach correctly as it seems to hit the bean once for each item in the list of items?
For instance
I have a list of menu Items that I get with a method (See code below) and I have a foreach that I want to loop and display each menu item
So far this works perfect except that I notice that my getMenuItems getter is beign hit one time for every menuItem in the list? I assume that this also means that
toplink is going to the database each time to get a new list of items???
This seems like it's going to be fairly slow if the number of menuitems is large?
Am I doing this correctly or am I missing something here?
Any help would be greatly appreciated.
thanks
J
<af:foreach items="#{MenuManagedBean.menuItems}" var"#{menuItem}">
<af:outputText value="#{menuItem.Text}"/>
</af:foreach>
public List<MenuItem> menuItems
public void getMenuItems()
FacesContext fc = FacesContext.getCurrentInstance();
ValueBinding vb = fc.getApplication().createValueBinding("#{data}");
BindingContext bctx = (BindingContext)vb.getValue(fc);
DCDataControl dc = bctx.findDataControl("MenuItemPublicFacadeDataControl");
MenuItemPublicFacade facade = (MenuItemPublicFacade)dc.getDataProvider();
return facade.findAllMenuItems();
public void setMenuItems(List<Menuitem> menuItems)
thisl.menuItems = menuItems;
}

Your method could look something like this:
    public List<MenuItem> getMenuItems(){
        if(FacesContext.getCurrentInstance().getExternalContext().getSessionMap().containsKey("menuItems")){
            return (List<MenuItem>)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("menuItems");
        else{
            FacesContext fc = FacesContext.getCurrentInstance();
            ValueBinding vb = fc.getApplication().createValueBinding("#{data}");
            BindingContext bctx = (BindingContext)vb.getValue(fc);
            DCDataControl dc = bctx.findDataControl("MenuItemPublicFacadeDataControl");
            MenuItemPublicFacade facade = (MenuItemPublicFacade)dc.getDataProvider();
            menuItems =  facade.findAllMenuItems();
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("menuItems", menuItems);
            return menuItems;
{code}
From your code, I think you are using JDeveloper 10g and as far as I know viewScope is not yet available, so this code uses sessionScope. The value you store in sessionMap is there as long as user session is active, so you should implement something that will reset "menuItems" (if menuItems changes in run time).
Pedja                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • Access database query data in Java SCriptlet

    Question:
    Creating a web page and plotting points on the page:
    1) Database query results in decimal values latitude and longitude.
    2) Perform calculations on lati. & long. in a <% java scriptlet %>
    I don't know how to pass the data back and forth between the
    java server page and the java scriplet.
    After the calculation translates the latitude and longitude
    into xpos and ypos, a data point is plotted on a map.
    I tried many ways of doing it but am just guessing as
    to how to pass the data.
    Thanks in Advance. - John
    Here is what I am trying so far .... see snippet below:
    *** Query the database ***
    <sql:query var="qryBio">
    SELECT
    DEC_LATITUDE,
    DEC_LONGITUDE,
    ENTRY_TIMESTAMP
    FROM app.biosurvey where
    </sql:query>
    *** for each row retreived from the database ***
    <c:forEach var="row" items="${qryBio.rows}">
    <c:set var="latvar" value="${row.dec_latitude}" scope="page"/>
    <c:set var="longvar" value="${row.dec_longitude} "scope="page" />
    *** java code scriptlet - ***
    *** convert latitude and longitude to xpos and ypos for display ***
    <%
    latitude = (Float)pageContext.getAttribute("latvar");
    longitude = (Float)pageContext.getAttribute("longvar");
    xpos = (int)Math.round(latitude);
    ypos = (int)Math.round(longitude);
    xpos = 1082 - xpos;
    ypos = 700 + ypos;
    pageContext.setAttribute("xpos", xpos);
    pageContext.setAttribute("ypos", ypos);
    %>
    *** plot a point on the display html page overlaying the map ***
    <IMG ID="Row" SRC="smallredbox.jpg" ALT="red box"
    STYLE="position:absolute;
    top:<%=xposMpls%> px;
    left:<%=yposMpls%> px;
    z-index:2">
    </c:forEach>

    Question:
    Creating a web page and plotting points on the page:
    1) Database query results in decimal values latitude and longitude.
    2) Perform calculations on lati. & long. in a <% java scriptlet %>
    I don't know how to pass the data back and forth between the
    java server page and the java scriplet.
    After the calculation translates the latitude and longitude
    into xpos and ypos, a data point is plotted on a map.
    I tried many ways of doing it but am just guessing as
    to how to pass the data.
    Thanks in Advance. - John
    Here is what I am trying so far .... see snippet below:
    *** Query the database ***
    <sql:query var="qryBio">
    SELECT
    DEC_LATITUDE,
    DEC_LONGITUDE,
    ENTRY_TIMESTAMP
    FROM app.biosurvey where
    </sql:query>
    *** for each row retreived from the database ***
    <c:forEach var="row" items="${qryBio.rows}">
    <c:set var="latvar" value="${row.dec_latitude}" scope="page"/>
    <c:set var="longvar" value="${row.dec_longitude} "scope="page" />
    *** java code scriptlet - ***
    *** convert latitude and longitude to xpos and ypos for display ***
    <%
    latitude = (Float)pageContext.getAttribute("latvar");
    longitude = (Float)pageContext.getAttribute("longvar");
    xpos = (int)Math.round(latitude);
    ypos = (int)Math.round(longitude);
    xpos = 1082 - xpos;
    ypos = 700 + ypos;
    pageContext.setAttribute("xpos", xpos);
    pageContext.setAttribute("ypos", ypos);
    %>
    *** plot a point on the display html page overlaying the map ***
    <IMG ID="Row" SRC="smallredbox.jpg" ALT="red box"
    STYLE="position:absolute;
    top:<%=xposMpls%> px;
    left:<%=yposMpls%> px;
    z-index:2">
    </c:forEach>

  • Running perl programs through java.

    How do i run a perl program through java?
    arg.pl :
    while(<STDIN>)
    print;
    java program that I tried:
    import java.io.*;
    class runtime
        static Process p;
        static BufferedReader stdOutput;
        static BufferedWriter stdInput;
        public static void main(String args[]) throws IOException
            int i = 0;
            try{
                String cmd[] = new String[] {"perl","arg.pl"};
                p = Runtime.getRuntime().exec(cmd,null,new File("./"));
                stdOutput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                stdInput = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
            catch(Exception ex){
                System.out.println("Unable to initiate Process : " + ex);
            stdInput.write("abcd\n");
            stdInput.write("1234\n");
            stdInput.write("efgh\n");
            stdInput.write("5678\n");
            stdInput.close();
            System.out.println(stdOutput.readLine());
            System.out.println(stdOutput.readLine());
            System.out.println(stdOutput.readLine());
            System.out.println(stdOutput.readLine());
    }This works well. But I need to read the output line by line as and when i give the standard input line by line to it.
    I tried the following :
    import java.io.*;
    class runtime
        static Process p;
        static BufferedReader stdOutput;
        static BufferedWriter stdInput;
        public static void main(String args[]) throws IOException
            int i = 0;
            try{
                String cmd[] = new String[] {"perl","arg.pl"};
                p = Runtime.getRuntime().exec(cmd,null,new File("./"));
                stdOutput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                stdInput = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
            catch(Exception ex){
                System.out.println("Unable to initiate Process : " + ex);
            stdInput.write("abcd\n");
            stdInput.flush();
            System.out.println(stdOutput.readLine());
            stdInput.write("1234\n");
            stdInput.flush();
            System.out.println(stdOutput.readLine());
            stdInput.write("efgh\n");
            stdInput.flush();
            System.out.println(stdOutput.readLine());
            stdInput.write("5678\n");
            stdInput.flush();
            System.out.println(stdOutput.readLine());
            stdInput.close();
    }This doesn't work well. It just halts without any output.
    Can anyone help me?
    Edited by: Vijayakrishna on Dec 5, 2007 8:30 AM

    Let me be more specific.
    I want to use a class which will look something like this.
    import java.io.*;
    public class FindAnswer{
        Process p;
        BufferedReader stdOutput;
        BufferedWriter stdInput;
        public FindAnswer()
            try{
                String cmd[] = new String[] {"perl","arg.pl"};
                p = Runtime.getRuntime().exec(cmd,null,new File("./"));
                stdOutput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                stdInput = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
            catch(Exception ex){
                System.out.println("Unable to initiate Process. Error: " + ex);
        public String getAnswer(String question)
            String answer = question;
            try{
                stdInput.write(question + System.getProperty("line.separator"));
                stdInput.flush();
                answer = stdOutput.readLine();
            catch(Exception ex){
                System.out.println("Exception. Error: " + ex);
            return answer;
        public void close()
            if (p != null) {
                try {
                    if (p.getInputStream() != null)
                        p.getInputStream().close();
                    if (p.getOutputStream() != null)
                        p.getOutputStream().close();
                    if (p.getErrorStream() != null)
                        p.getErrorStream().close();
                catch (Exception e) {
                    System.out.println("Exception in Closing Streams - " + e);
    }The perl program takes lot of initialization time. I dont want to run the program foreach question i have. I'll just create an object to this class and find and answer by passing question to the object's getAnswer method. Here, I dont know all the questions in the beginning itself. I'll know one by one only and I should find answer without terminating the process.
    Kindly help me in this.

  • A jsp page for searching employees

    this jsp page is used for searching employees and displaying the search results.
    when the submit button is clicked, the http request will be sent to a servlet java class.
    <%@ page contentType="text/html" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <html>
    <head>
    <title>SEARCH STAFF</title>
    </head>
    <body>
    <p align="center"><font color="#008000">SEARCH STAFF</font></p>
    <FORM METHOD=POST ACTION="/servlet/ReqHandler?action=searchstaffget">
    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%">
        <tr>
        <td width="50%">Staff ID:</td>
        <td width="50%"><INPUT NAME=staffid SIZE=15></td>
      </tr>
      <tr>
        <td width="50%">First Name:</td>
        <td width="50%"><INPUT NAME=firstname SIZE=30></td>
      </tr>
        <tr>
        <td width="50%">Last Name:</td>
        <td width="50%"><INPUT NAME=lastname SIZE=30></td>
      </tr>
      <tr>
        <td width="50%">Gender:</td>
        <td width="50%"><select size="1" name="sex">
        <option value="m" selected>Male</option>
        <option value="f">Female</option>
        </select></td>
      </tr>
       <tr>
        <td width="50%">E-mail:</td>
        <td width="50%"><INPUT NAME=email SIZE=30></td>
      </tr>
      <tr>
        <td width="50%">Birth date:</td>
        <td width="50%"><INPUT NAME=birthdate SIZE=10></td>
      </tr>
      <tr>
        <td width="50%">Address:</td>
        <td width="50%"><input type="text" name="addr" size="30"></td>
      </tr>
      <tr>
        <td width="50%">Phone number (Home):</td>
        <td width="50%">
    <input type="text" name="phoneno" size="8"></td>
      </tr>
      <tr>
        <td width="50%">Phone number (Mobile):</td>
        <td width="50%">
       <input type="text" name="mobileno" size="8"></td>
      </tr>
      <tr>
        <td width="50%">ID card number:</td>
        <td width="50%"><input type="text" name="idno" size="8"></td>
      </tr>
        <tr>
          <td width="50%">Position:</td>
          <td width="50%"><select size="1" name="position">
        <option value="deliveryman" selected>Deliveryman</option>
        <option value="normalstf">Normal Staff</option>
        </select></td>
      </tr>
    </table>
    <P align="center">
    <INPUT TYPE=SUBMIT></FORM>
    <!--
    I WANT THE SEARCH RESULTS TO BE DISPLAYED HERE IN THIS JSP PAGE.
    THIS MEANS THAT, AFTER THE SUBMIT BUTTON IS CLICKED, THE FORM ABOVE WILL NOT DISAPPEAR AND THE SEARCH RESULTS WILL DISPLAY BELOW THE FORM.
    --> the java servlet class will then forward the search parameters(last name, first name....etc.) to a database accessor class and this class will then return an arraylist of all the columns for each row in the database that match the search criteria. Each column of a row is stored as a String object in the arraylist.
    what i would like to ask is, what codes should i use in the servlet class, and what codes should i use in the jsp page, in order that, the search results will finally display in <TABLE> format.
    please help, thanks a lot~~~~~~~~

    put the search results in session in your servlet
    using
    request.getSession().setAttribute("SEARCH_RESULT_SESSI
    ON", searchResult);
    where searchResult is your arrayList.
    in your JSP page:
    <c:set var="SEARCH_RESULT"
    value="<%=SEARCH_RESULT_SESSION%>"/>
    <c:set var="searchResult"
    value="${sessionScope.SEARCH_RESULT}"
    scope="request"/>
    and use this searchResult to display your results in
    whatever format you want.
    <c:forEach var="result" items="searchResult">
         <c:out value="${result}"/>
         result is the string that you stored in arrayList.
    </c:forEach>
    Questions, let me know.thanks but.....
    this doesn't work for me, i placed this statement in my java servlet class:
    request.getSession().setAttribute("SEARCH_RESULT_SESSION", searchResult);and i placed the other statements in the JSP page like this:
    <%@ page contentType="text/html" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <%@ page isELIgnored="false" %>
    <%@ page import="java.util.ArrayList" %>
    <html>
    <head>
    <title>SEARCH STAFF</title>
    </head>
    <body>
    <p align="center"><font color="#008000">SEARCH STAFF</font></p>
    <FORM METHOD=POST ACTION="/servlet/ReqHandler?action=searchstaffget">
    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%">
    <tr>
    <td width="50%">Staff ID:</td>
    <td width="50%"><INPUT NAME=staffid SIZE=15></td>
    </tr>
    <tr>
    <td width="50%">First Name:</td>
    <td width="50%"><INPUT NAME=firstname SIZE=30></td>
    </tr>
    <tr>
    <td width="50%">Last Name:</td>
    <td width="50%"><INPUT NAME=lastname SIZE=30></td>
    </tr>
    <tr>
    <td width="50%">Gender:</td>
    <td width="50%"><select size="1" name="sex">
    <option value="m" selected>Male</option>
    <option value="f">Female</option>
    </select></td>
    </tr>
    <tr>
    <td width="50%">E-mail:</td>
    <td width="50%"><INPUT NAME=email SIZE=30></td>
    </tr>
    <tr>
    <td width="50%">Birth date:</td>
    <td width="50%"><INPUT NAME=birthdate SIZE=10></td>
    </tr>
    <tr>
    <td width="50%">Address:</td>
    <td width="50%"><input type="text" name="addr" size="30"></td>
    </tr>
    <tr>
    <td width="50%">Phone number (Home):</td>
    <td width="50%">
    <input type="text" name="phoneno" size="8"></td>
    </tr>
    <tr>
    <td width="50%">Phone number (Mobile):</td>
    <td width="50%">
    <input type="text" name="mobileno" size="8"></td>
    </tr>
    <tr>
    <td width="50%">ID card number:</td>
    <td width="50%"><input type="text" name="idno" size="8"></td>
    </tr>
    <tr>
    <td width="50%">Position:</td>
    <td width="50%"><select size="1" name="position">
    <option value="deliveryman" selected>Deliveryman</option>
    <option value="normalstf">Normal Staff</option>
    </select></td>
    </tr>
    </table>
    <P align="center">
    <INPUT TYPE=SUBMIT></FORM>
    <c:set var="SEARCH_RESULT" value="<%=SEARCH_RESULT_SESSION%>"/>
    <c:set var="searchResults" value="${sessionScope.SEARCH_RESULT}" scope="request"/>
    <c:forEach begin="1" end="3" var="result" items="searchResults">
    <c:out value="${result}"/>
    </c:forEach>
    </body>
    </html>
    i typed some data in the text fields and clicked "submit" button
    but it turned into a blank page
    i was sure the arraylist contained the search results because i tried to write them into the stdout.log file.
    could you please tell me why it's like this?

  • Yet another Try Catch question. Iterating through a ForEach loop

    Confused on error handling in a Powershell ForEach loop. I’m looping through a list of registry keys, attempting
     to open each one. If it succeeds, I do a bunch of stuff. If it fails, I want to skip to the next iteration.
    If I was doing It in VBScript I’d do this:
    For Each Thing In colThings
    Open Thing
    If Err.Number <> 0 Then
    “oops”
    Else
    Do stuff
    Do stuff
    Do stuff
    End If
    Next
    This is what I came up with in PowerShell. It seems to work, but just doesn’t seem powershell-ish. There must be a better way to use the catch output than just creating a $return variable and assigning it success or fail?
    ForEach ($subKeyName in $subKeyNames)
    try{$subKey = $baseKey.OpenSubKey("$subKeyName")}
    catch{$return = "error" }
    If($return -eq "error" )
    “Oops”
    Else
    Do stuff
    Do stuff
    Do Stuff

     
    I totally get what you're saying about formatting. I don't' have any habits yet, since I've only been working in Powershell since... well, what time is it now?
    Unfortunately, It Has Been Decreed that we are no longer to use VBScript for any engineering solutions at work, so my 15 years experience in it now needs to be transitioned over asap. I don't have the luxury of crawling before I run. I'm trying not to be
    frustrated, but it's like an English major waking up one day and being told "You must now speak French exclusively. Here's a book."
    The Do Stuff example of my ForEach loop is about 50 lines of code involving matching values in subkeys of this registry key with another and collecting output. I tried wrapping the whole thing in a try section based on some examples, but it seemed odd, that's
    why I'm asking. I'm used to tightly focused error handling at the point where an error may occur.
    In this example I'm only interested in whether or not I can open the subkey (it exists, but I may not have permission). If I can't, there's no point in continuing with this iteration of the loop, I want to skip to the next one. So why include all the "Do
    Stuff" in the the try section? From a readability viewpoint, it doesn't seem helpful.
    Also, there may be more error handling deeper in the code. If I then put that in a try/catch, and then something else inside that, now I have nested try/catches mixed in with nested if/elses, all wrapped in a For loop.
    Again, I can see how it works logically, but for readability not so much, and having all these braces 50 lines apart to match up is giving me eye strain :).
    It sounds like David is agreeing with jrv, that putting the entire ForEach loop code into a try/catch is the conventional way to do it. I guess it makes as much sense as putting it all in an If-else-Endif, and I just need to adjust my paradigm.
    But if not, my specific question was more along the lines of, is there a built in way to tell that the catch section has been executed, rather than me using it to populate an arbitrary variable and then read it? In VBScript, you execute something, and the
    next line, you check the Err.number. I wasn't sure if you could do that with a try/catch.

  • General question re. c:forEach

    Hi all,
    I've got Tomcat 5.5 and using JSTL 1.1.2
    I've just started reading JSTLs and have got my <c:out> examples to work. When it comes to <c:forEach> however, I end up getting exception errors.
    Below is my code example.
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <% String names[]={"first","second","third"};
    request.setAttribute("myList",names); %>
    <c:forEach var="element" items="${myList}">
    ${element}
    </c:forEach>I have the jstl and standard .jar files in my WEB-INF/lib directory. I've also copied all the .tld files to Tomcat's WEB-INF folder too. I'd be appreciative if anyone could advice me on were I'm going wrong and how to go about fixing the error that shows up re. the <c:forEach> tag.
    In case it'll help, my taglib for the "c" prefix looks as follows:
    <taglib>
    <taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
    <taglib-location>/WEB-INF/c.tld</taglib-location>
    </taglib>
    I'd be very appreciative for any advice. Thanks in advance,
    ph
    Edited by: phosse1 on Mar 31, 2008 9:35 PM

    Here's example from my app which iterates over a javax.servlet.jsp.jstl.sql.Result.
    public static Result getObjects(HttpServletRequest request) {
    connect to db and return a javax.servlet.jsp.jstl.sql.Result
    <jsp:scriptlet>               
            request.setAttribute("table", DBSettings.getObjects(request)); 
            </jsp:scriptlet>
    <c:forEach var="row" items="${table.rows}">
    <c:choose>
        <c:when test='${param.images}'>             
            <c:choose>
                <c:when test="${linecount == table.rowCount-1}">
                    <tr class="lastRow">
                </c:when>
                <c:otherwise>               
                    <tr>
                </c:otherwise>
            </c:choose> 
        </c:when>
        <c:otherwise>
            <tr onMouseOver="this.bgColor = '#F3F3E2'" onMouseOut ="this.bgColor = '#FFFFEB'">
        </c:otherwise>
    </c:choose>
    <td nowrap="nowrap">    
        <c:choose>
            <c:when test="${row.datediff1 == 0}">
                hoje             
            </c:when>
            <c:when test="${row.datediff1 == 1}">
                ontem             
            </c:when>                  
            <c:otherwise>                           
            </c:otherwise>
        </c:choose>
        <c:if test="${(empty images || images eq 'false') && row.datediff1 < 2}">       
        </c:if>   
        <c:if test="${(empty images || images eq 'false') && row.datediff1 > 1}">       
            <c:out value="${row.daynumber}"/>
            <c:out value="${row.monthnumber==12?'Dec':(row.monthnumber==11?'Nov':(row.monthnumber==10?'Oct':(row.monthnumber==9?'Set':(row.monthnumber==8?'Ago':(row.monthnumber==7?'Jul':(row.monthnumber==6?'Jun':(row.monthnumber==5?'Ma':(row.monthnumber==4?'Ap':(row.monthnumber==3?'Mar':(row.monthnumber==2?'Feb':(row.monthnumber==1?'Jan':'')))))))))))}"/>
        </c:if>   
        <c:if test="${not param.images}">
    </td>
    <td nowrap="nowrap">
        </c:if>
        <c:if test="${param.images}">
            <br>
        </c:if>
        <c:out value="${fn:substring(row.clocktime,0,5)}"/>
    </td>
    <td> <c:choose>
            <c:when test='${param.images}'>              
              <c:if test="${not empty row.imageurl}">             
                  <a href="/vi/${row.id}.htm"> <img src="http://www.montao.com.br/pictures/${row.id}.thumb.${row.imageurl}"></a>
            </c:if> </c:when>
            <c:otherwise>
                <c:if test="${not empty row.imageurl && empty row.imageurl2}">
                    <img src="http://www.montao.com.br/images/kamera.gif" alt="">
                </c:if>
                <c:if test="${not empty row.imageurl && not empty row.imageurl2}">
                    <img src="http://www.montao.com.br/images/flerabildericon1.gif" alt="">
            </c:if></c:otherwise>
    </c:choose></td>
    <td>
        <c:choose>
            <c:when test='${param.images}'>
                <a href="/vi/${row.id}.htm">${row.subject} </a>
                <br><fmt:formatNumber value="${row.price}" type="currency" currencySymbol="R$ "/>       
                <c:if test="${not empty row.price && not empty row.oldprice && row.price < row.oldprice}">
                    <img src="images/pil.gif" alt=""/>
                </c:if>
            </c:when>
            <c:otherwise>
                <a href="/vi/${row.id}.htm">${row.subject}</a>  <c:if test="${not empty row.price && not empty row.oldprice && row.price < row.oldprice}">
                    <img src="images/pil.gif" alt="">
                </c:if>
            </c:otherwise>
        </c:choose>  
    </td> <c:choose>
        <c:when test='${param.images}'>           
        </c:when>
        <c:otherwise>
            <td align="right" nowrap="nowrap"> 
              <fmt:formatNumber value="${row.price}" type="currency" currencySymbol="R$ "/>
            </td>
        </c:otherwise>
    </c:choose>
    <c:choose>
        <c:when test="${locationid eq 'SP' || locationid eq 'RJ' || locationid eq 'estado' || locationid eq 'BR' || locationid eq '999' || locationid eq '1002' || locationid eq '11002' || locationid eq '1999'}">
            <td nowrap="nowrap">   
                ${row.multiplelocation}${empty row.multiplelocation? row.location :''}${not empty row.hasmultiplelocation && empty multiplelocation?',...':''}
            </td>           
            <c:choose>
                <c:when test="${empty param.categoryid || param.categoryid eq '1001' || param.categoryid eq '1002' || param.categoryid eq '1003' || param.categoryid eq '1004' || param.categoryid eq '1005' || param.categoryid eq '1006' || param.categoryid eq '1007' || param.categoryid eq '1008'}">
                    <td nowrap="nowrap">
                       ${row.category}${row.company?'(e)':''}
                    </td>
                </c:when>
                <c:otherwise>                   
                </c:otherwise>
            </c:choose>
        </c:when>
        <c:when test="${empty locationid || locationid eq '1001'}"><td nowrap="nowrap">
                ${not empty row.displaylocation ? fn:trim(row.displaylocation) : ''}${empty row.displaylocation && not empty row.multiplelocation ? row.multiplelocation :''}${not empty row.displaylocation || (empty row.displaylocation && not empty row.multiplelocation) ? ',...' :''}${empty row.displaylocation && empty row.multiplelocationd && empty row.multiplelocation? row.location :''}${empty row.displaylocation && empty row.multiplelocationd && empty row.multiplelocation && not empty row.hasmultiplelocation? ',...' :''}
            </td>
            <c:choose>
                <c:when test="${empty param.categoryid || param.categoryid eq '1001' || param.categoryid eq '1002' || param.categoryid eq '1003' || param.categoryid eq '1004' || param.categoryid eq '1005' || param.categoryid eq '1006' || param.categoryid eq '1007' || param.categoryid eq '1008'}">
                    <td nowrap="nowrap">
                   ${row.category}${row.company?'(e)':''}</td>
                </c:when>
                <c:otherwise>
                    <td> ${row.company?'(e)':''}
                    </td>
                </c:otherwise>
            </c:choose>
        </c:when>
        <c:otherwise>
            <c:choose>
                <c:when test="${empty param.categoryid || param.categoryid eq '1001' || param.categoryid eq '1002' || param.categoryid eq '1003' || param.categoryid eq '1004' || param.categoryid eq '1005' || param.categoryid eq '1006' || param.categoryid eq '1007' || param.categoryid eq '1008'}">
                    <td nowrap="nowrap">
                       ${row.category}
                        ${row.company?'(e)':''}
                    </td>
                </c:when>
                <c:otherwise>
                    <td>${row.company?'(e)':''}
                    </td>
                </c:otherwise>
            </c:choose>       
        </c:otherwise>
    </c:choose> <c:set var="linecount" scope="page" value="${linecount+1}"/>
    </tr>
    </c:forEach>Regards,
    Niklas

  • Call to action inside c:forEach (simple question)

    Here's my problem: I have a pojo called Document, inside this pojo I have an id, the document name and description and the document file.
    When displaying my JSP (called DetailProcess), I have a list of documents, that I have to show the user and let him click the document name and start downloading. To display the names I used:
    <c:forEach items="${searchProcess.document}" var="document">
         <p>><U><c:out value="${document.name}"/></U>
    </c:forEach>Example output:
    > Infomations
    > Price guide
    > Offers
    What I want to do now, is call a method that will download the file of the document which is stored inside the database. The method is inside the same Action that generated this JSP (DetailProcessAction). I was told that I had to use a hidden field containing the id of the document, and create a javascript that would receive this id and call the download method.
    But I have no ideia how to do this. I mean, placing a hidden field contaning the id, and allowing the user to click the name and send a call for the javascript. Also, I don't think that using javascript might be the best ideia, since some people have it disabled...
    Can someone give me a help, and tell me the best way to do this?

    Well, you will need to use a link with a document id to uniquely identify the document to download. The link would point to an action on the server that does the download. So, for example, you would want the output in HTML to be:
    <p><a href="downloadDocument?name=Informations">Informations</a></p>An example of the JSTL would be:
    <c:forEach ${searchProcess.document}" var="document">
      <c:url var="dlPage" value="downloadDocument">
        <c:param name="name" value="${document.name}"/>
      </c:url>
      <p><a href="<c:out value="${dlPage}"/>"><c:out value="${document.name}"/></a></p>
    </c:forEach>Then on the receiving side of the request, whatever you map the downloadDocument action to, you would get the name of the document to download from the request parameter:
    String documentToDownload = request.getParameter("name");and call the method which causes the document to be downloaded.

  • JSTL Tag Question - forEach

    Hi there, I have this piece of code;
    <c:forEach var="row" items="${linkQuery.rows}" varStatus="status">
    <tr>
    <td>
    <c:out value="<%= altField %>"/>
    </td>
    </tr>
    </c:forEach>
    You see the field to be displayed is a variable; altField, of which the string value is;
    "${row.SOMEFIELDNAME}"
    however when run, it simply prints out the value between the speech marks rather than evaluating the expression.
    It prints;
    <c:out value="<%= altField %>"/>
    Instead of;
    <c:out value="${row.SOMEFIELDNAME}"/>
    I ve tried escaping the speech marks however I get a compilation error if I try this.
    It needs to be a variable because the field name varies on each instance. Any help greatly received,
    Simon.

    I'm not sure if you've tried this, but I think it ought to look like:
    <c:forEach var="row" items="${linkQuery.rows}" varStatus="status">
    <tr>
    <td>
    <c:out value="${row.SOMEFIELDNAME}"/>
    </td>
    </tr>
    </c:forEach>It sounds like you're mixing and matching the EL and scriptlets - not a good idea. That's what the EL is for - getting all that scriptlet code out of your JSPs.
    My JSPs print successfully doing it this way. See if yours does, too. - MOD

  • Foreach loop iteration question

    Here's what I want to do. I have a list of items that I need to insert a comma between. For the last item there should be no comma afterward, so I need to flag this loop iteration as special.
    <c:set var="numRsns" value="${fn.length(networksForm.regionalSportsNetworkStations)}"/>
    <c:forEach var="rsn" items="${networksForm.regionalSportsNetworkStations}" varStatus="rsncounter">
         <c:if test="??? < numRsns" >
                               <b><c:out value="${rsn.description}" escapeXml="false" /></b>
                     </c:if>
         <b><c:out value="${rsn.description}," escapeXml="false" /></b>
    </c:forEach>How can I find out what the current iteration of the loop is? I am fairly new to JSP and JSTL so all help is appreciated.
    Thanks!

    Another useful feature of the loop status variable - it has boolean properties "first" and "last" to indicate if it is the first or last row
    <b>
    <c:forEach var="rsn" items="${networksForm.regionalSportsNetworkStations}" varStatus="rsncounter">
      <c:out value="${rsn.description}" escapeXml="false" />
      <c:if test="${rsncounter.last}>,</c:if>
    </c:forEach>
    </b>{code}
    Also because everything in your loop is bolded, why not just put bold tags around the whole thing, rather than mark up each individual element?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Question about the JSTL forEach tag

    <c:forEach var = "someItem" items="${myBean.getItems}">
    Is this possible if myBean (a Java Bean) contains a function called getItems, which behind the scenes queries the database and stores the results in a structure, such as a list... the list might be an ArrayList or perhaps my own structure which simply extends the ArrayList class.
    The contents of this list will be another object. This object, for example say is a book, which then contains properties such as a title, author, etc.
    Is this possible:
    <c:forEach var = "someItem" items="${myBean.getItems}">
    <c:out value = "${someItem.title}">
    </c:forEach>
    Or does the var HAVE to be a String?

    I try to make and example and I am getting this error:
    org.apache.jasper.JasperException: /test.jsp(13,0) According to TLD or attribute directive in tag file, attribute items does not accept any expressions
    why?
    jsp
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
    <jsp:useBean id="obj" scope="application" class="demo.TestPersona"/>
    <html>
    <head>
    <title>beanDemo Tutorial</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body>
    <c:forEach items="${obj.personas}" var="item">
    <c:out value="${item.apellido}"/>
    </c:forEach>
    </BODY>
    </HTML>
    javaBean
    package demo;
    import java.util.*;
    public class TestPersona {
    Collection<Persona> personas = new Vector();
    public TestPersona() {
    personas.add(new Persona("Rodriguez", "Diego", new Date()));
    personas.add(new Persona("Fernandez", "Gabriela", new Date()));
    public Collection getPersonas() {
    return personas;
    package demo;
    import java.util.*;
    public class Persona {
    String apellido = null;
    String nombre = null;
    Date edad = null;
    public Persona(String apellido, String nombre, Date edad) {
    this.apellido = apellido;
    this.nombre = nombre;
    this.edad = edad;
    public String getApellido() {
    return apellido;
    }

  • How can I load a .xlsx File into a SQL Server Table using a Foreach Loop Container in SSIS?

    I know I've REALLY struggled with this before. I just don't understand why this has to be soooooo difficult.
    I can very easily do a straight Data Pump of a .xlsX File into a SQL Server Table using a normal Excel Connection and a normal Excel Source...simply converting Unicode to DT_STR and then using an OLE DB Destination of the SQL Server Table.
    If I want to make the SSIS Package a little more flexible by allowing multiple .xlsX spreadsheets to be pumped in by using a Foreach Loop Container, the whole SSIS Package seems to go to hell in a hand basket. I simply do the following...
    Put the Data Flow Task within the Foreach Loop Container
    Add the Variable Mapping Variable User::FilePath that I defined as a Variable and a string within the FOreach Loop Container
    I change the Excel Connection and its Expression to be ExcelFilePath ==> @[User::FilePath]
    I then try and change the Excel Source and its Data Access Mode to Table Name or view name variable and provide the Variable Name User::FilePath
    And that's when I run into trouble...
    Exception from HRESULT: 0xC02020E8
    Error at Data Flow Task [Excel Source [56]]:SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occured. Error code: 0x80004005.
    Error at Data Flow Task [Excel Source [56]]: Opening a rowset for "...(the EXACT Path and .xlsx File Name)...". Check that the object exists in the database. (And I know it's there!!!)
    I don't understand by adding a Foreach Loop Container to try and make this as efficient as possible has caused such an error unless I'm overlooking something. I have even tried delaying my validations and that doesn't seem to help.
    I have looked hard in Google and even YouTube to try and find a solution for this but for the life of me I cannot seem to find anything on pumping a .xlsX file into SQL Server using a Foreach Loop Container.
    Can ANYONE please help me out here? I'm at the end of my rope trying to get this to work. I think the last time I was in this quandry, trying to pump a .xlsX File into a SQL Server Table using a Foreach Loop Container in SSIS, I actually wrote a C# Script
    to write the contents of the .xlsX File into a .csv File and then Actually used the .csv File to pump the data into a SQL Server Table.
    Thanks for your review and am hoping and praying for a reply and solution.

    Hi ITBobbyP,
    If I understand correctly, you want to load data from multiple sheets in an .xlsx file into a SQL Server table.
    If in this scenario, please refer to the following tips:
    The Foreach Loop container should be configured as shown below:
    Enumerator: Foreach ADO.NET Schema Rowset Enumerator
    Connection String: The OLE DB Connection String for the excel file.
    Schema: Tables.
    In the Variable Mapping, map the variable to Sheet_Name, and change the Index from 0 to 2.
    The connection string for Excel Connection Manager is the original one, we needn’t make any change.
    Change Table Name or View name to the variable Sheet_Name.
    If you want to load data from multiple sheets in multiple .xlsx files into a SQL Server table, please refer to following thread:
    http://stackoverflow.com/questions/7411741/how-to-loop-through-excel-files-and-load-them-into-a-database-using-ssis-package
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Get the current runspace of a powershell instance (Follow up to a previous question - Link in question)

    So this is a follow up question to a question I posted last week
    If
    PS {some Path}>C: = PS C:\> then why not HKLM: = PS HKLM:\>
    So here is where I am with the question above
    After running pretty much all of the powershell related DLL files through redgate's .NET Reflector I fiinally discovered where those "C:" = "Set-Location C:" were being created.
    namespace System.Management.Automation.Runspaces
    public class InitialSessionState
    // More here but cut them out to save space in this post
    internal static SessionStateFunctionEntry[] BuiltInFunctions = new SessionStateFunctionEntry[]
    new SessionStateFunctionEntry("prompt", DefaultPromptString),
    // More here but cut them out to save space in this post
    new SessionStateFunctionEntry("A:", "Set-Location A:"),
    new SessionStateFunctionEntry("B:", "Set-Location B:"),
    new SessionStateFunctionEntry("C:", "Set-Location C:"),
    new SessionStateFunctionEntry("D:", "Set-Location D:"),
    new SessionStateFunctionEntry("E:", "Set-Location E:"),
    new SessionStateFunctionEntry("F:", "Set-Location F:"),
    new SessionStateFunctionEntry("G:", "Set-Location G:"),
    new SessionStateFunctionEntry("H:", "Set-Location H:"),
    new SessionStateFunctionEntry("I:", "Set-Location I:"),
    new SessionStateFunctionEntry("J:", "Set-Location J:"),
    new SessionStateFunctionEntry("K:", "Set-Location K:"),
    new SessionStateFunctionEntry("L:", "Set-Location L:"),
    new SessionStateFunctionEntry("M:", "Set-Location M:"),
    new SessionStateFunctionEntry("N:", "Set-Location N:"),
    new SessionStateFunctionEntry("O:", "Set-Location O:"),
    new SessionStateFunctionEntry("P:", "Set-Location P:"),
    new SessionStateFunctionEntry("Q:", "Set-Location Q:"),
    new SessionStateFunctionEntry("R:", "Set-Location R:"),
    new SessionStateFunctionEntry("S:", "Set-Location S:"),
    new SessionStateFunctionEntry("T:", "Set-Location T:"),
    new SessionStateFunctionEntry("U:", "Set-Location U:"),
    new SessionStateFunctionEntry("V:", "Set-Location V:"),
    new SessionStateFunctionEntry("W:", "Set-Location W:"),
    new SessionStateFunctionEntry("X:", "Set-Location X:"),
    new SessionStateFunctionEntry("Y:", "Set-Location Y:"),
    new SessionStateFunctionEntry("Z:", "Set-Location Z:"),
    new SessionStateFunctionEntry("cd..", "Set-Location .."),
    new SessionStateFunctionEntry(@"cd\", @"Set-Location \"),
    Then further down in the class it is called 
    public static InitialSessionState CreateDefault()
    InitialSessionState state = new InitialSessionState();
    state.Variables.Add(BuiltInVariables);
    state.Commands.Add(new SessionStateApplicationEntry("*"));
    state.Commands.Add(new SessionStateScriptEntry("*"));
    state.Commands.Add(BuiltInFunctions);
    state.Commands.Add(BuiltInAliases);
    foreach (PSSnapInInfo info in PSSnapInReader.ReadEnginePSSnapIns())
    try
    PSSnapInException exception;
    state.ImportPSSnapIn(info, out exception);
    catch (PSSnapInException exception2)
    throw exception2;
    state.LanguageMode = PSLanguageMode.FullLanguage;
    state.AuthorizationManager = new PSAuthorizationManager(Utils.DefaultPowerShellShellID);
    return state.Clone();
    So the InitialSessionState class fills in these values.
    My problem now is I cannot seem to find out how to get an attachment to the CURRENT either
    InitialSessionState
    Runspace
    I can find plenty of forum posts and blogs about how to run powershell in c# but they ALL involve instantiating a NEW powershell runtime.
    I can and have written
    InitialSessionState iss = InitialSessionState.CreateDefault();
    and I can step through the debugger and watch it fill in the functions but as soon as it finally gets to the powershell prompt all the functions are gone.
    On another attempt I tried to create a runspace from the current host
    thisRunspace = RunspaceFactory.CreateRunspace(this.Host);
    where this is public class ConfluenceProvider : NavigationCmdletProvider
    And the line of code above is called in 
            protected override System.Collections.ObjectModel.Collection<PSDriveInfo> InitializeDefaultDrives()
    When I run the code and debug  the runspace created has a different InstanceId than what ultimately shows up in the powershell console if I do $Host.Runspace.InstanceId
    This provider will ultimately be a part of a module with other cmdlets and functions but I would like to know how to attach to the actual runspace, sessionstate, WHATEVER will do the trick that the module is loaded into so I can add functions to it.
    So if anyone has any clue or knows of other blogs, walkthroughs i could read through that covers this it would be a huge help.
    Thanks again everyone
    Quidquid latine dictum sit, altum videtur

    Hi Tofubug,
    Since I'm not familiar about C#, however, if want to run powershell script in C#, the script below may be helpful for you:
    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    runspace.Open();
    RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
    Pipeline pipeline = runspace.CreatePipeline();
    //Here's how you add a new script with arguments
    Command myCommand = new Command(scriptfile);
    CommandParameter testParam = new CommandParameter("key","value");
    myCommand.Parameters.Add(testParam);
    pipeline.Commands.Add(myCommand);
    // Execute PowerShell script
    results = pipeline.Invoke();
    And these threads for your reference:
    Execute PowerShell Script from C# with Commandline Arguments
    How to run PowerShell scripts from C#
    How do you set FullLanguage mode
    for remote PowerShell from C#?
    If I have any misunderstanding, please feel free to let me know.
    Best Regards,
    Anna Wang

  • How to add a new property security question in atg profile?

    Hi All,
    I want to add a new field in registration.jsp named as Security Questions; it has 3 questions and it should be ordered and cannot contain duplicate values.
    For this I have created
    1) a customUserProfile.xml under /MyModule/config/atg/userprofiling/customUserProfile.xml with the following content-
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
        <!DOCTYPE gsa-template PUBLIC "-//Art Technology Group, Inc.//DTD General SQL Adapter//EN"
            "http://www.atg.com/dtds/gsa/gsa_1.0.dtd">
    <gsa-template>
        <header>
            <name>Registration</name>
            <author></author>
        </header>
        <item-descriptor name="securityquestions">
      <table name="security_questions" id-column-names="securequestions_id">
        <property name="securityquestions" data-type="enumerated">
        <attribute name="useCodeForValue" value="false"/>
          <option value="what is your birth place" code="0"/>
      <option value="what is your favourite colour" code="1"/>
      <option value="what is your pet name" code="2"/>
        </property>
      </table>
    </item-descriptor>   
    2) a definition file under named as /MyModule/config/atg/userprofiling/customUserProfile.properties-
    $class=atg.adapter.gsa.GSARepository
    $scope=global
    repositoryName=customUserProfile
    # database access- for making repositry as versioned, use SwitchingDataSource else use JTDataSource
    dataSource=/atg/dynamo/service/jdbc/SwitchingDataSource
    transactionManager=/atg/dynamo/transaction/TransactionManager
    # our XML definitionFile
    definitionFiles=/atg/userprofiling/customUserProfile.xml
    # XML parsing
    XMLToolsFactory=/atg/dynamo/service/xml/XMLToolsFactory
    # id generation
    idGenerator=/atg/dynamo/service/IdGenerator
    </gsa-template>
    3) a droplet names as /MyModule/src/com/pa/SecurityQuestionLogin.java
    4) a registration jsp with the following code snippet for security questions-
    <dsp:droplet name="SecurityQuestionLogin">
    <dsp:select bean="SecurityQuestionLogin.securityQuestions">
        <dsp:droplet name="PossibleValues">
          <dsp:param name="itemDescriptorName" value="securityquestions"/>
          <dsp:param name="propertyName" value="type"/>
          <dsp:oparam name="output">
            <dsp:droplet name="ForEach">
              <dsp:param name="array" param="values"/>
              <dsp:oparam name="output">
                <dsp:option param="element"/>
                <dsp:valueof param="element"/>
              </dsp:oparam>
            </dsp:droplet>
    But I don't know what logic can I implement in java class for this requirement.
    Is the above structure is right for this purpose,please help!
    Regards,
    Vikas

    Hi Nitin,
    extend ATG userProfile.xml and add properties there in user item-descriptor
    I created userProfile.xml under C:\ATG\ATG10.0.3\MyModule\config\atg\userprofiling with following contents-
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE gsa-template
            PUBLIC "-//Art Technology Group, Inc.//DTD General SQL Adapter//EN"
            "http://www.atg.com/dtds/gsa/gsa_1.0.dtd">
    <gsa-template>
      <item-descriptor name="user" cache-mode="simple" xml-combine="append">
    <table name="security_questions" type="auxiliary" id-column-name="securequestions_id">
    <property name="securityquestions" column-name="securityquestions" data-type="enumerated">
    <attribute name="useCodeForValue" value="false"/>
          <option value="what is your birth place" code="0"/>
      <option value="what is your favourite colour" code="1"/>
      <option value="what is your pet name" code="2"/>
      </property>
    </table>
    </item-descriptor>
    </gsa-template>
    and created userProfile.properties file with following content-
    $class=atg.adapter.gsa.GSARepository
    $scope=global
    repositoryName=userProfile
    # database access- for making repositry as versioned, use SwitchingDataSource else use JTDataSource
    dataSource=/atg/dynamo/service/jdbc/SwitchingDataSource
    transactionManager=/atg/dynamo/transaction/TransactionManager
    # our XML definitionFile
    definitionFiles=/atg/userprofiling/userProfile.xml
    # XML parsing
    XMLToolsFactory=/atg/dynamo/service/xml/XMLToolsFactory
    # id generation
    idGenerator=/atg/dynamo/service/IdGenerator
    and change the jsp code as-
    <dsp:select bean="/atg/userProfiling/Profile.securityQuestions">
        <dsp:droplet name="PossibleValues">
          <dsp:param name="itemDescriptorName" value="securityquestions"/>
          <dsp:param name="propertyName" value="type"/>
          <dsp:oparam name="output">
            <dsp:droplet name="ForEach">
              <dsp:param name="array" param="values"/>
              <dsp:oparam name="output">
                <dsp:option param="element"/>
                <dsp:valueof param="element"/>
              </dsp:oparam>
            </dsp:droplet>
          </dsp:oparam>
        </dsp:droplet>
      </dsp:select>
      </dsp:droplet>
    Have I done right?
    And what else I need to do,should I run the startsqlrepository script to create the table structure for this property?
    Thanks & Regards,
    Vikas

  • [Forum FAQ] How to calculate the total count of insert rows within a Foreach Loop Container in SSIS?

    Introduction
    We need to loop through all the flat files that have the same structure in a folder and import all the data to a single SQL Server table. How can we obtain the total count of the rows inserted to the destination SQL Server table?
    Solution
    We can use Execute SQL Task or Script Task to aggregate the row count increment for each iteration of the Foreach Loop Container. The following steps are the preparations before we add the Execute SQL Task or Script Task:
    Create a String type variable FilePath, two Int32 type variables InsertRowCnt and TotalRowCnt.
    Drag a Foreach Loop Container to the Control Flow design surface, set the Enumerator to “Foreach File Enumerator”, specify the source folder and the files extension, and set the “Retrieve file name” option to “Fully qualified”.
    On the “Variable Mappings” tab of the container, map the variable FilePath to the collection value.
    Drag a Data Flow Task to the container, in the Data Flow Task, add a Flat File Source, a Row Count Transformation, and an OLE DB Destination, and join them. Create a Flat File Connection Manager to connect to one of the flat files, and then configure the
    Flat File Source as well as the OLE DB Destination adapter. Set the variable for the Row Count Transformation to “User::InsertRowCnt”.
    Open the Property Expressions Editor for the Flat File Connection Manager, and set the expression of “ConnectionString” property to
    “@[User::FilePath]”.
    (I) Execute SQL Task Method:
    In the Control Flow, drag an Execute SQL Task under the Data Flow Task and join them.
    Create one or using any one existing OLE DB Connection Manager for the Execute SQL Task, set the “ResultSet” option to “Single row”, and then set the “SQLStatement” property to:
    DECLARE @InsertRowCnt INT,
                   @TotalRowCnt INT
    SET @InsertRowCnt=?
    SET @TotalRowCnt=?
    SET @TotalRowCnt=@InsertRowCnt+@TotalRowCnt
    SELECT TotalRowCnt=@TotalRowCnt
    On to parameter 1. 
    On the “Result Set” tab of the Execute SQL Task, map result 0 to variable “User::TotalRowCnt”.
    (II) Script Task Method:
    In the Control Flow, drag a Script Task under the Data Flow Task and join them.
    In the Script Task, select variable InsertRowCnt for “ReadOnlyVariables” option, and select variable TotalRowCnt for “ReadWriteVariables”.
    Edit the Main method as follows (C#):
    public void Main()
    // TODO: Add your code here
    int InsertRowCnt = Convert.ToInt32(Dts.Variables["User::InsertRowCnt"].Value.ToString()
    int TotalRowCnt = Convert.ToInt32(Dts.Variables["User::TotalRowCnt"].Value.ToString());
    TotalRowCnt = TotalRowCnt + InsertRowCnt;
    Dts.Variables["User::InsertRowCnt"].Value = TotalRowCnt;
    Dts.TaskResult = (int)ScriptResults.Success;
              Or (VB)
              Public Sub Main()
            ' Add your code here
            Dim InsertRowCnt As Integer =        
            Convert.ToInt32(Dts.Variables("User::InsertRowCnt").Value.ToString())
            Dim TotalRowCnt As Integer =
            Convert.ToInt32(Dts.Variables("User::TotalRowCnt").Value.ToString())
            TotalRowCnt = TotalRowCnt + InsertRowCnt
            Dts.Variables("User::TotalRowCnt").Value = TotalRowCnt
            Dts.TaskResult = ScriptResults.Success
           End Sub
    Applies to
    Microsoft SQL Server 2005
    Microsoft SQL Server 2008
    Microsoft SQL Server 2008 R2
    Microsoft SQL Server 2012
    Microsoft SQL Server 2014
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

    Hi ITBobbyP,
    If I understand correctly, you want to load data from multiple sheets in an .xlsx file into a SQL Server table.
    If in this scenario, please refer to the following tips:
    The Foreach Loop container should be configured as shown below:
    Enumerator: Foreach ADO.NET Schema Rowset Enumerator
    Connection String: The OLE DB Connection String for the excel file.
    Schema: Tables.
    In the Variable Mapping, map the variable to Sheet_Name, and change the Index from 0 to 2.
    The connection string for Excel Connection Manager is the original one, we needn’t make any change.
    Change Table Name or View name to the variable Sheet_Name.
    If you want to load data from multiple sheets in multiple .xlsx files into a SQL Server table, please refer to following thread:
    http://stackoverflow.com/questions/7411741/how-to-loop-through-excel-files-and-load-them-into-a-database-using-ssis-package
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Can I append the file name from a Foreach Loop Container Enumerator into a SQL Server Statement?

    I would like to pass back via an Email the name of the file that was successfully FTP'ed to a remote server. And I was hoping to do this via an Execute SQL Task with the following SQL Statement...but I just don't know if it will append the Foreach Loop Container
    variable enumerator to the appended Email message that I am building in SQL Server or if I can and how I can...
    I sort of get the feeling that I can try and do this via Dynamic SQL...I just don't know if by building dynamic SQL if my Foreach Loop Container enumerator variable will be appended to my Email Message via the SQL Server UPDATE 
    @[User::FTPFHFileName]
    Or do I add a Data Flow Task and an OLE DB Command and pass the Foreach Loop Container enumerator variable to a Stored Procedure referenced in the OLE DB Command via a "?"
    Thanks for your review and am hopeful for a reply.

    Hello,
    It seems that the issue had been solved and thanks for your sharing. It will be very beneficial for other community members who have similar questions.
    I’d like to mark this issue as "Answered". Please also feel free to unmark the issue, with any new findings or concerns you may have.
    Regards,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

Maybe you are looking for

  • MS office report

    Hi, I am trying to generate a report using the MS office express vi and after follow the instructions in the manuals and check the examples I cant fill a table predefined in my own template!! and I get an error Error -41110 occurred at NI_ReportGener

  • Windows XP; Adobe Reader XI; Google Chrome

    I have an old PC running on Windows XP with Adobe Reader XI installed and my browser is Google Chrome. No problems up until recently when (I don't know how) my PC was 'invaded' by a 'browser hijacker' called VOSTERAN which, according to all the websi

  • Stuck trying to remove Cluster/RAC 11Gr1 in prep for 11Gr2 install...

    Hello all, I'm thinking I'm missing something simple here...but I can't figure it out yet. Ok, I have a 3 node RAC cluster, Oracle 11Gr1...I want to remove all instance, and clustering (ASM is ok to keep)...before I try to put on 11Gr2. This is on RH

  • ABAP WebService Issue

    Hello Champs, I am consuming web service using ABAP, configuration done from SOAMANAGER  and its working fine when I am testing it from SE80. but same is not working when I have created program from SE38 not Error no Output nothing. Requesting your i

  • AddressBook's (Mac ;-) "Me" card not transferred to iPhone

    I won't call myself very often, but... I'd like to have myself stored among contacts on my iPhone. Any suggestion? (apart... using a different name to avoid duplicates in AddressBook Thanks!