Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Connecting to USPS WebTOOl

Status
Not open for further replies.

ASPNETnewbie

Programmer
May 9, 2006
93
US
This program is supposed to collect at the needed data from my ASPX Form and transmit the information to the USPS API which in turned returns the information for printing out a Label but it seems not to work and I would appreciate it if someone can help please...


ASPNETnewbie

Code:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;

public partial class Controls_GetLabel : System.Web.UI.UserControl
{
    // put together the XML to transmit so you can get your LABEL
    private string BuiltXML;
    private string user_id = " ";
    private string theURL = "[URL unfurl="true"]http://servername/shippingAPITest.dll?API=";[/URL]

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void buildXML()
    {
      
BuiltXML += "<ExpressMailLabelRequest USERID=" +  user_id + "><Option/><EMCAAccount/>";
BuiltXML += "<EMCAPassword/><ImageParameters/>";

        BuiltXML +=  Session["FromAddress"];
        BuiltXML += Session["FromPhone"];
        BuiltXML += Session["ToAddress"];
        BuiltXML += Session["ToPhone"];

    }

    protected void ExpressShipLabel_Click(object sender, EventArgs e)
    {
        buildXML();

        if (Flatrate.SelectedValue == "Yes")
        {
            BuiltXML += "<WeightInOunces>" + weight.Text + "</WeightInOunces>";
        }
        else
        {
            BuiltXML += "<FlatRate>True</FlatRate>";
        }
        if (waiver.SelectedIndex==0)
        {
            BuiltXML += "<WaiverOfSignature>True</WaiverOfSignature>";
        }

        if (Defer.SelectedIndex==1)
        {
            BuiltXML += "<NoWeekend>True</NoWeekend>";
        }
        else if (Defer.SelectedIndex==2)
        {
            BuiltXML += "<NoHoliday>True</NoHoliday>";
        }
        if (newZip.Text != "")
        {
            BuiltXML += "<POZipCode>+ newZip.Text+ </POZipCode>";
        }
        if (imaget.SelectedIndex== 1)
        {
            BuiltXML += "<ImageType>PDF</ImageType>";
        }
        BuiltXML += "</ExpressMailLabelRequest>";
        retrieveLabel();
    }//End ShipLable_Click

    string response;
    // Now sent it and get the information back for post
    protected void retrieveLabel()
    {

        try
        {
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(theURL + BuiltXML);
            myReq.Method = "POST";

            HttpWebResponse resp = (HttpWebResponse)myReq.GetResponse();
            StreamReader loResponseStream = new StreamReader(resp.GetResponseStream());
            response = loResponseStream.ReadToEnd();
            resp.Close();
            loResponseStream.Close();
            bool iserror = IsResponseError();
            if (!iserror)
            {
                Console.WriteLine( "Address Validated");
            }
        }
        catch (Exception f)
        {
           Console.WriteLine(f.Message);
        }
    }//End retrieveLabel

    private bool IsResponseError()
    {
        if (response.Contains("/error"))
        {
            Console.WriteLine("Please make sure to enter correct address information");
            return true;
        }
        else { return false; }
    }//End IsReponseError
}
 
but it seems not to work
If you want any help, you'll have to be more descriptive than that.


____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 
I am trying to contact the USPS web service to not only validate address but also print Labels directly from my site or my page but so far having problem getting the right information from the server. The code I have below when tested works for the text call but when I try to duplicate the same call using constructed data from my form, I get back an error message instead I get an error message from the server instead

<Error>
<Number>80040b19</Number>
<Description>XML Syntax Error: Error getting USERID
attribute.</Description>
<Source>UspsCom::DoAuth</Source>
</Error>


I would appreciate any help to fix the problem please. thanks in advance...

asp newbie


Code:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;

public partial class ShippingConfirmation : System.Web.UI.Page
{
    private string pID = "12";
    private string BuiltXML;// put together the XML to transmit so you can get your LABEL
    private string user_id = "xxxxxxxx";
    private string Verifymethod="Verify&XML=";
    private string Labelmethod="ExpressMailLabelCertify&XML=";
    private string URL = " [URL unfurl="true"]http://testing.shippingapis.com/ShippingAPITest.dll?API=";[/URL]
    private string theURL = "[URL unfurl="true"]http://testing.shippingapis.com/ShippingAPITest.dll?API=ExpressMailLabelCertify&XML=";[/URL]
    public string response;//holds the retrieved info from server
    private string fromAddress;//holds information on sender
    private string toAddress;//holds the final information on reciever info
    private string VAB;//Holds the XML for Address validation
    private bool IsAddresserror;
    private bool IsLabelerror;

//creates the XML to be transmitted to the USPS Server       
private void ValidateTheAddress()
{
    IsAddresserror = false;//just incase, set it to false at first
        try
        {
        //Generate the Xml document to transmit
        HttpWebRequest myReq =(HttpWebRequest)WebRequest.Create(URL + Verifymethod + VAB);
        myReq.Method = "GET";
        HttpWebResponse resp=(HttpWebResponse) myReq.GetResponse();
        StreamReader loResponseStream = new StreamReader(resp.GetResponseStream());
       //get the response from server
        response = loResponseStream.ReadToEnd();
        resp.Close();
        loResponseStream.Close();
            //check if the returned information carries an error message
        IsAddressResponseError();
          if (IsAddresserror = false)
          {
              Update.Text = "Address has been validated   " + response;
             
            }
        }
        catch (Exception f)
        {
            Update.Text = f.Message;
        }
}

    private void validateAddress()
    {//create the XML request and save it to string SB 
        VAB += ("<AddressValidateRequest UserID=\"xxxxxxxx\">");
        VAB += ("<Address ID=\"" +pID + "\">");
        //append other toAddress information
       VAB += ("<ToAddress1>" + ToAddress1.Text + "</ToAddress1>");
        VAB += ("<ToAddress2>" + ToAddress2.Text + "</ToAddress2>");
       VAB += ("<ToCity>" + ToCity.Text + "</ToCity>");
       VAB += ("<ToState>" + ToState.Text + "</ToState>");
       VAB += ("<ToZip5>" + Tozipp.Text + "</ToZip5>");
       VAB+= ("<ToZip4>" + ToZip2.Text + "</ToZip4>");
        VAB += ("</Address>");
        VAB += ("</AddressValidateRequest>");
    }

    //send and retrieve XML call for the Label

    private void retrieveLabel()
    {
        try
        {
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(theURL + Labelmethod);
            myReq.Method = "POST";

            HttpWebResponse resp = (HttpWebResponse)myReq.GetResponse();
            StreamReader loResponseStream = new StreamReader(resp.GetResponseStream());
            response = loResponseStream.ReadToEnd();
            resp.Close();//close the connection
            loResponseStream.Close();//close stream
            IsAddressResponseError();//check for error
            if (!IsLabelerror)//as long as all went well
            {
                Update.Text = "Shipping Label Retrieved !";//announce success
                int idx1 = response.IndexOf("<EmLabel>") + 9;//get index of the Label tags
                int idx2 = response.IndexOf("</EmLabel>");
                int tracknum1 = response.IndexOf("<EmConfirmationNumber>") + 22;//get index of the Label tags
                int tracknum2 = response.IndexOf("</EmConfirmationNumber");
                string Labelcode = response.Substring(idx1, idx2 - idx1);
                //work to decode information in between the tags
                // Convert the Base64 UUEncoded input into binary output.
                byte[] binaryData;
                try
                {
                    binaryData =
                        System.Convert.FromBase64String(Labelcode);
                }
                catch (System.ArgumentNullException)
                {
                    System.Console.WriteLine("Base 64 string is null.");
                    return;
                }
                catch (System.FormatException)
                {
                    System.Console.WriteLine("Base 64 string length is not " +
                        "4 or is not an even multiple of 4.");
                    return;
                }
                // Write out the decoded data.
                System.IO.FileStream outFile;
                string outfilename = "/Label/" + response.Substring(tracknum1, tracknum2 - tracknum1) + ".pdf";
                try
                {//write the information to a file and then open it
                    outFile = new System.IO.FileStream(outfilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                    outFile.Write(binaryData, 0, binaryData.Length);
                    outFile.Close();
                }
                catch (System.Exception exp)
                {
                    // Error creating stream or writing to it.
                    System.Console.WriteLine("{0}", exp.Message);
                }
            }
        }
        catch (Exception f)
        {
            Console.WriteLine(f.Message);
        }
    }//End retrieveLabel
    private void LabelXML()
    {
      BuiltXML += "<ExpressMailLabelRequest USERID=" + user_id + "><Option/><EMCAAccount/>";
        BuiltXML += "<EMCAPassword/><ImageParameters/>";
        //retrieve and append base information to XMLstring
        baseInfo();
        BuiltXML += fromAddress;
        collectRecieverInfoforLabel();
        BuiltXML += toAddress;
        ShipInfo();
    }
    private void ShipInfo()
    {
        if (Flatrate.SelectedValue == "Yes")
        {
            BuiltXML += "<WeightInOunces>" + weight.Text + "</WeightInOunces>";
        }
        else
        {
            BuiltXML += "<FlatRate>True</FlatRate>";
        }
        if (waiver.SelectedIndex == 0)
        {
            BuiltXML += "<WaiverOfSignature>True</WaiverOfSignature>";
        }
        if (Defer.SelectedIndex == 1)
        {
            BuiltXML += "<NoWeekend>True</NoWeekend>";
        }
        else if (Defer.SelectedIndex == 2)
        {
            BuiltXML += "<NoHoliday>True</NoHoliday>";
        }
        if (newZip.Text != "")
        {
            BuiltXML += "<POZipCode>"+ newZip.Text+ "</POZipCode>";
        }
        if (imaget.SelectedIndex == 1)
        {
            BuiltXML += "<ImageType>PDF</ImageType>";
        }
        BuiltXML += "</ExpressMailLabelRequest>";
        retrieveLabel();//go to call to retrieve the Label
    }//End ShipLable_Click
    private void IsLabelResponseError()
    {
        if (response.Contains("/error"))
        {
            Console.WriteLine("Please make sure to enter correct shipping information");
            IsLabelerror = true;
        }
        else { IsLabelerror= false; }
    }//End IsReponseError
    private void baseInfo()
{
	fromAddress += ("<FromFirstName>" + FromFirm.Text + "</FromFirstName>");
        fromAddress += ("<FromLastName>" + FromAddress1.Text + "</FromLastName>");
        fromAddress += ("<FromFirm>" + FromFirm1.Text + "</FromFirm>");
        fromAddress += ("<FromAddress1>" + FromAddress1.Text + "</FromAddress1>");
        fromAddress += ("<FromAddress2>" + FromAddress2.Text + "</FromAddress2>");
        fromAddress += ("<FromCity>" + FromCity.Text + "</FromCity>");
        fromAddress += ("<FromState>" + FromState.Text + "</FromState>");
        fromAddress += ("<FromZip5>" + Fromzip.Text + "</FromZip5>");
        fromAddress += ("<FromZip4>" + FromZip2.Text + "</FromZip4>");
	fromAddress +=("<FromPhone>" + FromPhone.Text + "</FromPhone>");
	toAddress += ("<ToFirstName>" + ToFirstName.Text + "</ToFirstName>");
        toAddress += ("<ToLastName>" + ToLastName.Text + "</ToLastName>");
	
}
private void collectRecieverInfoforLabel()
{//collect the reeiever addressinformation 
	toAddress += ("<ToFirm>" + ToFirm.Text + "</ToFirm>");
    toAddress += ("<ToAddress1>" + ToAddress1.Text + "</ToAddress1>");
    toAddress += ("<ToAddress2>" + ToAddress2.Text + "</ToAddress2>");
    toAddress += ("<ToCity>" + ToCity.Text + "</ToCity>");
    toAddress += ("<ToState>" + ToState.Text + "</ToState>");
    toAddress += ("<ToZip5>" + Tozipp.Text + "</ToZip5>");
    toAddress += ("<ToZip4>" + ToZip2.Text + "</ToZip4>");
	toAddress += ("<ToPhone>" + ToPhone.Text + "</ToPhone>");
}
    private void IsAddressResponseError()
    {  
        if (response.Contains("</error>"))
        {
            Update.Text = "Please make sure to enter correct address information";
            IsAddresserror = true;
        }
        else { IsAddresserror = false; }

    }

    protected void Validator_Click(object sender, EventArgs e)
    {
        validateAddress();
        ValidateTheAddress();
        if (!IsAddresserror)
        {
            Validator.Enabled = false;
        }
    }
    protected void getLabel_Click(object sender, EventArgs e)
    {
        LabelXML();
        if (!IsLabelerror)//disable button if label has already been created
        {
            getLabel.Enabled = false;
        }
    }
    protected void ValidateConfirm_Click(object sender, EventArgs e)
    {
        getLabel.Enabled = false;
        Validator.Enabled = false;
        validateAddress();
        ValidateTheAddress();
        if (!IsAddresserror)
        {
            LabelXML();
        }
        
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string sURL = "[URL unfurl="true"]http://testing.shippingapis.com/ShippingAPITest.dll?API=Verify&XML=<AddresssValidateRequest[/URL] UserID=\"126NONE05575\"><Address ID=\"1\"><Address1></Address1><Address2>8 Wildwood Drive</Address2><City>Old Lyme</City><State>CT</State><Zip5>06371</Zip5><Zip4></Zip4></Address></AddressValidateRequest>";
        try
        {
            //Generate the Xml document to transmit
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(sURL);
            myReq.Method = "GET";
            HttpWebResponse resp = (HttpWebResponse)myReq.GetResponse();
            StreamReader loResponseStream = new StreamReader(resp.GetResponseStream());
            //get the response from server
            response = loResponseStream.ReadToEnd();
            resp.Close();
            loResponseStream.Close();
            //check if the returned information carries an error message
            IsAddressResponseError();
            if (!IsAddresserror)
            {
                Update.Text = "Address has been validated";
            }
        }
        catch (Exception f)
        {
            Update.Text = f.Message;
        }
    }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top