PunchOut Web Site - Reading Data Stream. Need to Respond back Via Datastream. How?

Last post 07-20-2009 9:37 AM by ecomba. 6 replies.

Sort Posts:

  • PunchOut Web Site - Reading Data Stream. Need to Respond back Via Datastream. How?

    04-22-2005, 9:07 AM
    • Member
      73 point Member
    • PatrickRR
    • Member since 04-22-2005, 1:05 PM
    • Posts 21

    I am working on a punch-out supplier web site using Ariba cxml.org standards.

    The procurement site is posting a setup request to me. This setup request contains cXML that I transform in my ASP.NET web site to create my response back to the site. In essence completing the “handshake”.

    The problem is, on how to respond back? I cannot do a form post back. The cXML.org site has an ASP web site sample and all it does is just render an HTML page with the XML response in the page. It should contain nothing but the XML.  Trying this it does not work either. It appears to me I have to response using some type of output data stream, since I am reading a data stream to get the first request from the site.

    Here are the details. (The procurement site is java, the supplier site, mine, is ASP.NET_

    I. Step 1: The procurement site uses java and posts to my site using the code below. Then I extract their cXML and prepare to communicate back to them a success status code 200.

      232      public void run(){
       233          try {
       234                          //if(isHttpsConnection) { //HTTPS Connection
       235                                  //com.sun.net.ssl.HttpsURLConnection connection = (com.sun.net.ssl.HttpsURLConnection) url.openConnection();
       236                          //      connection = (com.sun.net.ssl.HttpsURLConnection) url.openConnection();
       237                          //      ((com.sun.net.ssl.HttpsURLConnection)connection).setHostnameVerifier(new NullHostnameVerifier());
       238                          //} else {
       239                  connection = (HttpURLConnection) url.openConnection();
       240                          //}
       241
       242              if (mimeData != null || postData != null){
       243                  connection.setDoOutput(true);
       244                  connection.setRequestMethod(POST);
       245
       246                                  //  -------KSN PHASE II CHANGES--------
       248                                  //      This is to set the BasciAuthSting (encoded)
       249                                  // This is for Basic Authentication
       250                                  if(sAuthStr != null){
       251                                          //System.out.println(sAuthStr+"2ndnew");
       252                          connection.setRequestProperty(AUTHORIZATION,sAuthStr);
       253                                  }
       254
       255                  connection.setRequestProperty(CONTENT_TYPE,contentType);
       256                  httpOut = new BufferedOutputStream(connection.getOutputStream(), 1024);
       257
       258                  if (mimeData != null) mimeData.writeTo(httpOut);
       259                  else httpOut.write(postData);
       260
       261                  httpOut.flush();
       262              }
       263
       264                          if(checkResponseCode)   {
       265                                  // === do posting to gxs and get response differently ===
       266                                  int nResponseCode = connection.getResponseCode();
       267                                  String nResponseMessage = connection.getResponseMessage();
       268                  setResponse(nResponseMessage+"-"+nResponseCode);
       269                          } else {
       270                          in = new BufferedInputStream(connection.getInputStream(), 1024);
       271              bufferOut = new ByteArrayOutputStream(1024);
       272              int val = 0;
       273              while ( (val = in.read()) != -1){
       274                  bufferOut.write(val);
       275              }
       276              bufferOut.flush();
       277
       278              setResponse(bufferOut.toString("UTF-8"));
       279                          } // == end of else loop ===
       280
       281          }
       282          catch (Exception ex) {
       283              ex.printStackTrace();
       284          }
       285      }

    II. Step 2: My ASP.NET Application reads the CXML using a datastream, This works fine I get the XML from the datatream then I transform it and now I need to issue a response back.

    Function ReturnStream() As String

            Dim str As Stream, strmContents As String
            Dim counter, strLen, strRead As Integer

            ' Create a Stream object.
            str = Request.InputStream
            ' Find number of bytes in stream.
            strLen = CInt(str.Length)
            ' Create a byte array.
            Dim strArr(strLen) As Byte
            ' Read stream into byte array.
            strRead = str.Read(strArr, 0, strLen)

            strmContents = System.Text.Encoding.UTF8.GetString(strArr)
            Return Server.UrlDecode(strmContents)


        End Function

    III. Step 3: Responding Back. Here comes the problem. The procurement site, in step 1 The developer on their end is telling me two things.

    a. Send the XML back to their site in the same connection. The connection they made in Step #1. How is this done???
    b. He also tells me that I can just render the XML in my page and they should get it. I tried this but it does not work so I think option a is what is required.

    Question: How do I send string data back through the same connection that was made in Step 1? Do I have to use an Output Stream similar to the Input Stream used in Step 2?  Is this possible?

    This link is to an ASP project http://xml.cxml.org/current/Fulfill.zip that responds back to a procurement site. In the end all it does is just render an HTML page with XML data and nothing else. Using this example his site does not see the XML. This is why it appears to me I must have to do some type of output stream to the connection made in Step #1.

    I hope someone there can help me on this issue. In all my years of development I have never been stuck on an issue like this before.

    In summary: I am looking for ASP.NET (vb.net) code that allows me to responds with the contents of a string variable back to the requestor in Step1. This string variable will contain XML data.

    I have spent countless hours on this issue of pushing my response back to his java application. I am totally stuck. Either I am getting bad information from the vendor, their site has problems and I cannot just render an HTML page with the XML.

    IV. This is the java code that would read the response sent in III above.  The java site using this code the read the repsonse back from my asp.net site. Hope this adds something to help solve this issue.

    287          protected Document parseRequest() throws Exception
       288          {
       289          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       290          DocumentBuilder builder = null;
       291
       292          //get the xmlstring in the response
       293          ServletInputStream is =request.getInputStream();
       294
       295          InputStreamReader isr = new InputStreamReader(is,"UTF8");
       296
       297
       298      /*
       299          StringBuffer sb = new StringBuffer("");
       300          int ch=0;
       301          while ((ch=isrb.read()) !=-1)
       302         {
       303            sb.append((char) ch);
       304         }
       305
       306          CXMLUtilities.logMessage(sb.toString());
                   */
    Regards,
    Patrick

  • Re: PunchOut Web Site - Reading Data Stream. Need to Respond back Via Datastream. How?

    04-26-2005, 11:10 PM
    • Participant
      1,855 point Participant
    • jhouse
    • Member since 09-28-2002, 8:06 PM
    • Northern California
    • Posts 372
  • Re: PunchOut Web Site - Reading Data Stream. Need to Respond back Via Datastream. How?

    10-30-2007, 11:24 PM
    • Member
      64 point Member
    • tarique_s
    • Member since 05-22-2007, 1:25 PM
    • Posts 35

     

    Hi Patrick,

     I am working on an ASP.Net punch out website using cXML.org standards. I looked at your post and i am in a similiar position. Were you able to figure out how to implement it? Did you find any useful resources on the web?

    I would appreciate any help you could give me.

    Thanks,

    Tarique
  • Re: PunchOut Web Site - Reading Data Stream. Need to Respond back Via Datastream. How?

    01-17-2008, 5:50 PM
    • Star
      7,532 point Star
    • thuhue
    • Member since 09-18-2003, 1:54 PM
    • Posts 2,232

    Any update on the above?

    Please mark the post(s) that have helped you as "Answer"
  • Re: PunchOut Web Site - Reading Data Stream. Need to Respond back Via Datastream. How?

    07-01-2009, 1:38 PM
    • Member
      6 point Member
    • ecomba
    • Member since 07-01-2009, 9:47 AM
    • Posts 3

    Hi, need help to implement a single application with asp.net punchout, please if someone can provide some code example I would be very useful

    Thanks

  • Re: PunchOut Web Site - Reading Data Stream. Need to Respond back Via Datastream. How?

    07-14-2009, 8:37 PM
    • Member
      73 point Member
    • PatrickRR
    • Member since 04-22-2005, 1:05 PM
    • Posts 21

    I had a few people contact me regarding this issue. The site went live not long after my first post. I never followed up with the resolution. Many years later I took a snippet of the code and pasted it below. It has been a long time since I worked on a punch-out site, so hopefully the code here can help some folks.   The code is VB.NET, and today I work in C# and my coding style has changed much since the days of this code... this is my disclaimer.

    Anyway, this is code from a shopping cart page and a check out page. Just in summary. After the user adds items to the cart and is ready to check out I build a session variable with XML. Then server.redirect the user to another page. That page pulls the XML from the session, response.clears the request, writes the new page from the XML session object that has the Ketera XML, and posts to Ketera... then a response comes back... and you know the rest. All login codes and urls have been changed to protect the innocent. Wink


    --------------------------------
    1. Page Shopping Cart Page
    --------------------------------

    Created XML that will post to Ketera


     Private Sub BtnLiveCheckOut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnLiveCheckOut.Click

            Dim strURL As String = Session("PostCartToURL")

            Dim ErrorTest As Boolean = False

            Try
                Create_PostForm_CartCXML("FormCXML", strURL, "Post")
                Server.Transfer("Checkout.aspx")
            Catch ex As Exception
                ErrorTest = True
                Session("EmailType") = "HTML"
                Session("DBError") = "Error Posting Cart to Ketera"
                Session("ITSource_Error") = ex.Message & " Catch All Error CheckOut.aspx: " & ViewState("ErrorMsg")
            End Try

            If ErrorTest = True Then
                Server.Transfer("dbErrorPage.aspx")
            Else
                Server.Transfer("Checkout.aspx")
            End If

        End Sub


        '====================================================================================================
        ' Create the HTML FORM to Post to Ketera & The CXML for thier cart.
        '====================================================================================================
        Sub Create_PostForm_CartCXML(ByVal strFormName As String, ByVal strURL As String, ByVal strMethod As String)

            Dim cXML_Form As String = ""
            'Build The Post Shopping Cart cXML

            '---------------------------------------------------------------
            '1. javascript to submit the form
            '---------------------------------------------------------------
            cXML_Form = cXML_Form & "<HTML>" & vbCrLf
            cXML_Form = cXML_Form & "<HEAD>" & vbCrLf
            cXML_Form = cXML_Form & "<script type='text/javascript' language='javascript'>" & vbCrLf
            cXML_Form = cXML_Form & " function SubmitForm(){" & vbCrLf
            cXML_Form = cXML_Form & " document.FormCXML.submit();" & vbCrLf
            cXML_Form = cXML_Form & " }" & vbCrLf & vbCrLf
            cXML_Form = cXML_Form & " </script>" & vbCrLf
            cXML_Form = cXML_Form & "</HEAD>" & vbCrLf & vbCrLf & vbCrLf

            '----------------------------------------------------------------
            '1. Get the CXML for the form. Do not use URL Encoding
            '----------------------------------------------------------------
            'Dim strCXML As String = Server.UrlEncode(Build_CXML()) 'Encoded
            Dim strCXML As String = Build_CXML()

            '----------------------------------------------------------------
            '2. Build the form
            '----------------------------------------------------------------
            'Submit the form when the page loads <body onload="dothis()">
            cXML_Form = cXML_Form & "<BODY onload='SubmitForm();'> " & vbCrLf

            '<form method="POST" name="frmFirstPage" action="http://localhost/CNF/Test.aspx">
            cXML_Form = cXML_Form & "<FORM method='" & strMethod & "'" & " name='" & strFormName & "'" & " action ='" & strURL & "'>"

            '----------------------------
            '3.Put CXML data here
            '----------------------------
            '<input type="hidden" name="FirstName" Value='Data Here'">
            cXML_Form = cXML_Form & "<input type='hidden' name='" & "cXML-urlencoded" & "'" & " Value='" & strCXML & "'>"

            'End of the form
            cXML_Form = cXML_Form & "</FORM>" & vbCrLf & vbCrLf & vbCrLf
            cXML_Form = cXML_Form & "</BODY>" & vbCrLf
            cXML_Form = cXML_Form & "</HTML>" & vbCrLf

            'Hold it and create the form in the next page.
            Session("cXML_Form") = cXML_Form

        End Sub


        '==============================================================================
        ' Build the detail lines for the CXML Submit Form
        '==============================================================================
        Function Build_CXML() As String

            Dim sp As New Spider
            Dim strURL As String
            Dim PayloadID As String = Session("PayloadID")
            Dim strCartTotal As String = Session("CartTotal")
            Dim TimeStamp As String = Session("TimeStamp")
            Dim BuyerCookie As String = Session("BuyerCookie")
            Dim PostToKeteraURL As String = Session("PostCartToURL")
            Dim Cust_AddressID As String = Session("Cust_AddressID")

            '--------------------------------------------
            '1. Delete all shopping cart related rows,
            '   then insert updated cart.
            '--------------------------------------------
            Delete_ShoppingCart_Rows()

            '------------------------------------
            '2. Save this session info to the DB
            '-----------------------------------
            CreateUser_TrackingTable(BuyerCookie, PayloadID, TimeStamp, PostToKeteraURL, Cust_AddressID)

            '--------------------------------
            '3. Get the Header for the CXML
            '--------------------------------
            Dim strPath As String = Server.MapPath("./XML_Templates/Punchout_Header_Create.txt")
            Dim CXML_Header As String
            'Dim CreateOrEdit As String = Session("CreateOrEdit") 'create' 'edit'
            CXML_Header = sp.GetHTML(strPath)

            CXML_Header = Replace(CXML_Header, "@@TimeStamp", TimeStamp)
            CXML_Header = Replace(CXML_Header, "@@PayLoadID", PayloadID)
            CXML_Header = Replace(CXML_Header, "@@ArrowDUNS", "99999992")
            CXML_Header = Replace(CXML_Header, "@@KeteraID", "AN099999999") '>> PROD ID
            'CXML_Header = Replace(CXML_Header, "@@KeteraID", "AN088888880-T") '>> TEST ID
            CXML_Header = Replace(CXML_Header, "@@BuyerCookie", BuyerCookie)
            CXML_Header = Replace(CXML_Header, "@@TOTAL", strCartTotal)
            CXML_Header = Replace(CXML_Header, "@@Shipping", "0")
            CXML_Header = Replace(CXML_Header, "@@Tax", "0")
            'CXML_Header = Replace(CXML_Header, "@@CreateOrEdit", CreateOrEdit)
            CXML_Header = Replace(CXML_Header, "@@CreateOrEdit", "edit")

            '-----------------------------------------
            '4. Build the Detail Lines & Save to SQL
            '-----------------------------------------
            Dim CXML_DetailHold, CXML_Detail, CXML_Detail_Accum As String
            strPath = Server.MapPath("./XML_Templates/PunchOut_Detail_Create.txt")
            CXML_DetailHold = sp.GetHTML(strPath)

            Dim ds As DataSet = Session("dsCart")
            Dim row As DataRow
            Dim strCriteria As String = "GroupNumber > 0 "
            Dim strSortOrder As String = "GroupNumber asc"
            Dim aRows As DataRow() = ds.Tables("Garments").Select(strCriteria, strSortOrder)

            'Get each garment row and build the CXML
            For Each row In aRows
                'Reset it to the CXML with the @@Fields.
                CXML_Detail = CXML_DetailHold
                CXML_Detail = Replace(CXML_Detail, "@@QTY", row("QTY"))
                CXML_Detail = Replace(CXML_Detail, "@@GroupPartID", row("GroupItemNumber"))
                CXML_Detail = Replace(CXML_Detail, "@@JDEItemNumber", row("JDEItemNumber"))
                CXML_Detail = Replace(CXML_Detail, "@@UnitPrice", row("Price"))

                Dim Desc As String = Replace(row("ItemDescription"), "'", "")
                Desc = Trim(Desc) & " #" & row("JDEItemNumber")
                CXML_Detail = Replace(CXML_Detail, "@@Description", Desc)

                CXML_Detail = Replace(CXML_Detail, "@@UOM", "EA")
                CXML_Detail = Replace(CXML_Detail, "@@Shipping", "0")
                CXML_Detail = Replace(CXML_Detail, "@@Shipper", "")

                'Accumulate all the detail to return to the form.
                CXML_Detail_Accum = CXML_Detail_Accum & CXML_Detail

                '--------------------------------------------------
                ' SQL SERVER: Save Garment Shopping Cart.
                '--------------------------------------------------
                Save_Garments_To_SQLSERVER(BuyerCookie, row("GroupNumber"), row("GroupItemNumber"), row("ProductType"), row("SubType"), row("JDEItemNumber"), row("SKU"), row("ItemDescription"), row("Color"), row("Size1"), row("Size2Display"), row("Size2Real"), row("Qty"), row("Price"), row("ExtPrice"))

                '--------------------------------------------------
                '5. Accumulate all the CXML for the emblems
                '--------------------------------------------------
                CXML_Detail_Accum = CXML_Detail_Accum & Get_Emblems(BuyerCookie, row("GroupNumber"), CXML_DetailHold)
            Next row

            '-----------------------------------------
            '6. Get the trailer, then submit the form
            '-----------------------------------------
            Dim CXML_Trailer As String
            strPath = Server.MapPath("./XML_Templates/PunchOut_Trailer_Create.txt")
            CXML_Trailer = sp.GetHTML(strPath)

            '----------------------------------------------------------------------
            '7. Return the CXML to the calling sub to add it to the form variable
            '----------------------------------------------------------------------
            Dim CXML_Complete As String = CXML_Header & vbCrLf & CXML_Detail_Accum & vbCrLf & CXML_Trailer
            Return CXML_Complete


        End Function

    --------------------------------
    2. To Post to Ketra....
    --------------------------------

    -- Performed a server redirect to another page. That page cleared the response then wrote the Punchout XML to the response.


        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

     

            Dim cXML_Form As String

            cXML_Form = Session("cXML_Form")
            'Cls_HELP.SendEmail("CXML Form", cXML_Form)

            'Create the form to post back
            Response.Clear()
            Response.Write(cXML_Form)
            Session.Abandon()


        End Sub

     

    ------------------------------------------------------------------------
    3. These snippets are code for reading the response from Ketera. They
       send a Binary Stream not clear XML Text
    ------------------------------------------------------------------------


        Sub Post_Response()
            Dim strMsg As String

            'Sample of the cXML Code.
            '  <?xml version="1.0" ?>
            '  <!DOCTYPE cXML (View Source for full doctype...)>
            '- <cXML payloadID="20099999999999999999999@172.99.999.9" timestamp="1011118540" version="1.1.009">
            '    - <Response>
            '       <Status code="200" text="success" />
            '     - <PunchOutSetupResponse>
            '      - <StartPage>
            '       <URL>http://www.supplier.com/web/index.php?b2b_session=155556674</URL>
            '        </StartPage>
            '       </PunchOutSetupResponse>
            '     </Response>
            ' </cXML>

            '----------------------------------------------------------------------------------
            ' Create the XML to post to Ketera.
            '----------------------------------------------------------------------------------
            Dim BuyerCookie As String = Session("BuyerCookie")
            If Len(BuyerCookie) = 0 Then
                Session("ErrorMsg") = "No buyer Cookie - Post Response Sub"
                Session("StatusCode") = "406"
            End If

            '----------------------------------------------------------------------------------
            ' Create the XML to post to Ketera.
            '----------------------------------------------------------------------------------
            Dim strPayLoadID As String = Session("PayloadID")
            Dim strTimeStamp As String = Session("TimeStamp")
            Dim strCXML As String

            '----------------------------------------------------------------------------------
            ' Form to submit the CXML to Ketera
            '----------------------------------------------------------------------------------
            Dim strHTML As String = ""
            Dim strjava As String = ""
            Dim strKeteraURL As String = Session("PostCartToURL")

            '----------------------------------------------------------------------------------
            'Format cXML. It will be placed in the hidden form field in the next step
            '----------------------------------------------------------------------------------
            'A. Create the URL
            Dim strMySiteURL As String
            Dim StatusCode As String = Session("StatusCode")

            If StatusCode <> "200" Then
                'Give Ketera this ERROR URL
                strMsg = Session("ErrorMsg")
                Cls_HELP.SendEmail("Punchout Error - Status Code <> 200!", strMsg)
                strMySiteURL = "https://www.MySite.com/CNF/dBErrorPage.aspx=?ErrorMsg=" & Server.UrlEncode(strMsg)
            Else
                'Give Ketera this GOOD URL
                strMsg = "success"
                strMySiteURL = "https://www.MySite.com/CNF/SetupRequest.aspx?BuyerCookie=" & BuyerCookie
            End If
            'Dim UTF8 As New UTF8Encoding
            'strMySiteURL = Server.UrlEncode(strMySiteURL)

            'B. Create the cXML
            strCXML = strCXML & "<?xml version=" & """" & "1.0" & """" & "?>" & vbCrLf
            strCXML = strCXML & "<!DOCTYPE cXML SYSTEM " & """" & "http://xml.cxml.org/schemas/cXML/1.1.009/cXML.dtd" & """" & ">" & vbCrLf
            strCXML = strCXML & " <cXML payloadID=" & """" & strPayLoadID & """" & " timestamp=" & """" & strTimeStamp & """" & ">" & vbCrLf
            strCXML = strCXML & "  <Response>" & vbCrLf
            strCXML = strCXML & "   <Status code=" & """" & StatusCode & """" & " text=" & """" & strMsg & """>" & " </Status>" & vbCrLf
            strCXML = strCXML & "   <PunchOutSetupResponse> " & vbCrLf
            strCXML = strCXML & "     <StartPage>" & vbCrLf
            strCXML = strCXML & "       <URL>" & strMySiteURL & "</URL>" & vbCrLf
            strCXML = strCXML & "     </StartPage>" & vbCrLf
            strCXML = strCXML & "   </PunchOutSetupResponse>" & vbCrLf
            strCXML = strCXML & " </Response>" & vbCrLf
            strCXML = strCXML & "</cXML>" & vbCrLf
            Response.Write(strCXML)
            'Cls_HELP.SendEmail("After Response Write", strCXML)
            Exit Sub

        End Sub

     

        '-----------------------------------------------------------------------------------------------
        ' Get the input data stream, it is not a form post, but a binary data stream.
        '-----------------------------------------------------------------------------------------------
        Function ReturnStream() As String

            'MSDN Version of this code.
            'http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebHttpRequestClassInputStreamTopic.asp

            'This is a long verision.
            'http://www.eggheadcafe.com/articles/20030813.asp

            Dim str As Stream, strmContents As String
            Dim counter, strLen, strRead As Integer

            ' Create a Stream object.
            str = Request.InputStream
            ' Find number of bytes in stream.
            strLen = CInt(str.Length)
            ' Create a byte array.
            Dim strArr(strLen) As Byte
            ' Read stream into byte array.
            strRead = str.Read(strArr, 0, strLen)

            strmContents = System.Text.Encoding.UTF8.GetString(strArr)
            Return Server.UrlDecode(strmContents)


        End Function

  • Re: PunchOut Web Site - Reading Data Stream. Need to Respond back Via Datastream. How?

    07-20-2009, 9:37 AM
    • Member
      6 point Member
    • ecomba
    • Member since 07-01-2009, 9:47 AM
    • Posts 3

    Thanks Patrick, I need the following help, I have developed an eprocurement application and I need generate a punchout request so that then get the response with the selected items and generating a requisition in this eprocurement application.

    can you help me with this?

    I developed a test application using httpRequest and HttpResponse object, but I get the following error:

        <Response>

     

            <Status code="400" text="Bad Request">No valid To credential was supplied [ANCLS-741435]</Status>

     

        </Response>

    I need urls valids and account for this test. Please Help me.

    Thanks


Page 1 of 1 (7 items)