ASPNETnewbie
Programmer
Below is my code for a USPS Address Validator and Label Generator but the problem is it does not seem to be working at all and I can not seem to figure out what the problem is. For some reason... I can basically build and debug with no problem but when information is entered, nothing else happens. Can anyone else help?
Thanks in Advance
DOTNETNEWBIE
Below is the actual Handler for my code
========================================
Thanks in Advance
DOTNETNEWBIE
Code:
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Net
Imports System.IO
Imports System.Collections.Generic
Imports System.Text
Imports System.Drawing
Imports System.Xml
Imports System.Web.SessionState
Partial Class _Default
Inherits System.Web.UI.Page
Private PID As String = "12"
Private _userid As String = "126NONE05575"
Private Const ProductionUrl As String = "[URL unfurl="true"]http://production.shippingapis.com/ShippingAPI.dll"[/URL]
Private TestingUrl As String = "[URL unfurl="true"]http://testing.shippingapis.com/ShippingAPITest.dll"[/URL]
Private _TestMode As Boolean = true
Private ToFirmNames As String
Private ToAddress1s As String
Private ToAddress2s As String
Private ToCitys As String
Private ToStates As String
Private ToZips As String
Private ToZip4s As String
Dim addressxml As String
Private package As Package = New Package()
Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As WizardNavigationEventArgs)
ValidateAddress()
End Sub
Dim url As String = ProductionUrl
Private ReadOnly Property GetURL()
Get
If (TestMode) Then
url = TestingUrl
End If
Return url
End Get
End Property
Public Property TestMode()
Get
Return _TestMode
End Get
Set(ByVal value)
_TestMode = value
End Set
End Property
Public Sub ValidateAddress()
Dim validateUrl As String = "?API=Verify&XML=<AddressValidateRequest USERID=""{0}""><Address ID=""{1}""><Address1>{2}</Address1><Address2>{3}</Address2><City>{4}</City><State>{5}</State><Zip5>{6}</Zip5><Zip4>{7}</Zip4></Address></AddressValidateRequest>"
Dim url As String = GetURL()
url = String.Format(url, _userid, PID, ToAddress1.Text, ToAddress2.Text, ToCity.Text, ToState.Text, Tozipp.Text, ToZip2.Text)
Try
Dim myReq As HttpWebRequest
' Create the web request
myReq = DirectCast(WebRequest.Create(url), HttpWebRequest)
myReq.Method = "POST"
myReq.ContentType = "application/x-[URL unfurl="true"]www-form-urlencoded"[/URL]
Dim Resp As HttpWebResponse
' Get response
Resp = DirectCast(myReq.GetResponse(), HttpWebResponse)
Dim reader As StreamReader
' Get the response stream into a reader
reader = New StreamReader(Resp.GetResponseStream())
addressxml = reader.ReadToEnd()
resp.Close()
reader.Close()
If (addressxml.Contains("<Error>")) Then
Dim idx1 As Integer = addressxml.IndexOf("<Description>") + 13
Dim idx2 As Integer = addressxml.IndexOf("</Description>")
Dim l As Integer = addressxml.Length
Dim errDesc As String = addressxml.Substring(idx1, idx2 - idx1)
Updatelabel.Text = errDesc
Wizard1.ActiveStepIndex = 1 'send userback to page where the problem most exists
Else 'else continue to process it
Updatelabel.Text = "Address was successfully Validated"
FromXml(addressxml)
'Decide what type of label to print
If (LabelType.SelectedIndex = 1) Then
GetSignatureConfirmationLabel() 'go ahead and call for label to be printed
Else
GetDeliveryConfirmationLabel() 'go ahead and call for label to be printed
End If
End If
Catch ex As Exception
Console.WriteLine(ex)
End Try
End Sub
Public Sub FromXml(ByVal xml As String)
Dim doc As System.Xml.XmlDocument = New System.Xml.XmlDocument()
doc.LoadXml(Xml)
Dim element As XmlNode = doc.SelectSingleNode("/AddressValidateResponse/Address/FirmName")
If (element.Value) Then
ToFirmNames = element.InnerText
End If
element = doc.SelectSingleNode("/AddressValidateResponse/Address/Address1")
If (element.Value) Then
ToAddress1s = element.InnerText
End If
element = doc.SelectSingleNode("/AddressValidateResponse/Address/Address2")
If (element.Value) Then
ToAddress2s = element.InnerText
End If
element = doc.SelectSingleNode("/AddressValidateResponse/Address/City")
If (element.Value) Then
ToCitys = element.InnerText
End If
element = doc.SelectSingleNode("/AddressValidateResponse/Address/State")
If (element.Value) Then
ToStates = element.InnerText
End If
element = doc.SelectSingleNode("/AddressValidateResponse/Address/Zip5")
If (element.Value) Then
ToZips = element.InnerText
End If
element = doc.SelectSingleNode("/AddressValidateResponse/Address/Zip4")
If (element.Value) Then
ToZip4s = element.InnerText
End If
End Sub
Private Sub Setinfo()
package.LabelType = CType(LabelType.SelectedIndex, LabelType)
package.WeightInOunces = Int32.Parse(weight.Text)
package.ServiceType = CType(Servicetype.SelectedIndex, ServiceType)
'package.SeparateReceiptPage
package.OriginZipcode = OriginZip.Text
package.LabelImageType = CType(imagetype.SelectedIndex, LabelImageType)
package.ReferenceNumber = Referencenum.Text
If (AddressService.SelectedIndex = 1) Then
package.AddressServiceRequested = True
Else
package.AddressServiceRequested = False
package.PackageType = CType(PackageType.SelectedIndex, PackageType)
package.PackageSize = CType(Packagesize.SelectedIndex, PackageSize)
End If
End Sub
' <summary>
' Fills a package's ShippingLabel with a Byte{} containing the Image for the label
' </summary>
' <param name="package">Package with From and To addresses provided</param>
'<returns>The same package with the ShippingLabel</returns>
Public Sub GetSignatureConfirmationLabel()
Dim url As String = "?API=SignatureConfirmationV3&XML=<SignatureConfirmationV3.0Request USERID=""{0}""><Option>{1}</Option><ImageParameters></ImageParameters><FromName>{2}</FromName><FromFirm>{3}</FromFirm><FromAddress1>{4}</FromAddress1><FromAddress2>{5}</FromAddress2><FromCity>{6}</FromCity><FromState>{7}</FromState><FromZip5>{8}</FromZip5><FromZip4>{9}</FromZip4><ToName>{10}</ToName><ToFirm>{11}</ToFirm><ToAddress1>{12}</ToAddress1><ToAddress2>{13}</ToAddress2><ToCity>{14}</ToCity><ToState>{15}</ToState><ToZip5>{16}</ToZip5><ToZip4>{17}</ToZip4><WeightInOunces>{18}</WeightInOunces><ServiceType>{19}</ServiceType><POZipCode>{20}</POZipCode><ImageType>{21}</ImageType><LabelDate>{22}</LabelDate><CustomerRefNo>{23}</CustomerRefNo><AddressServiceRequested>{24}</AddressServiceRequested></SignatureConfirmationV3.0Request>"
url = GetURL() + url
url = String.Format(url, _userid, CType(package.LabelType, Integer), fromFirstName.Text + " " + fromFirstName.Text, FromFirm.Text, FromAddress1.Text, FromAddress2.Text, FromCity.Text, FromState.Text, Fromzip.Text, FromZip2.Text, ToFirstName.Text + " " + ToLastName.Text, ToFirmNames, ToAddress1s, ToAddress2s, ToCitys, ToStates, ToZips, ToZip4s, package.WeightInOunces.ToString(), package.ServiceType.ToString().Replace("_", " "), package.OriginZipcode, package.LabelImageType.ToString(), package.ShipDate.ToShortDateString(), package.ReferenceNumber, package.AddressServiceRequested.ToString())
Try
Dim myReq As HttpWebRequest
' Create the web request
myReq = DirectCast(WebRequest.Create(url), HttpWebRequest)
myReq.Method = "POST"
myReq.ContentType = "application/x-[URL unfurl="true"]www-form-urlencoded"[/URL]
Dim Resp As HttpWebResponse
' Get response
Resp = DirectCast(myReq.GetResponse(), HttpWebResponse)
Dim reader As StreamReader
' Get the response stream into a reader
reader = New StreamReader(Resp.GetResponseStream())
Dim xml As String = reader.ReadToEnd()
Resp.Close()
reader.Close()
'since xml is global a separate call will send the information to session then
If (xml.Contains("<Error>")) Then
Dim idx1 As Integer = xml.IndexOf("<Description>") + 13
Dim idx2 As Integer = xml.IndexOf("</Description>")
Dim l As Integer = xml.Length
Dim errDesc As String = xml.Substring(idx1, idx2 - idx1)
Updatelabel.Text = errDesc
Wizard1.ActiveStepIndex = 1
Else
Dim i1 As Integer = xml.IndexOf("<SignatureConfirmationLabel>") + 28
Dim i2 As Integer = xml.IndexOf("</DeliveryConfirmationLabel>")
package.ShippingLabel = StringToUTF8ByteArray(xml.Substring(i1, i2 - i1)) 'byte information returned from the decoding
'is sent to the method to save it to session
SaveBytesToSession(package.ShippingLabel)
End If
Catch ex As Exception
Console.WriteLine(ex)
End Try
End Sub
Private Sub SaveBytesToSession(ByVal byteArr As Byte())
' ------------------------------------------------------------------------
' Store the Label image in Session to be picked up by an HttpHandler later
' ------------------------------------------------------------------------
Dim ctx As HttpContext = HttpContext.Current
Dim imageID As String = Guid.NewGuid().ToString()
ctx.Session(imageID) = byteArr
LabelImg.ImageUrl = String.Concat("Shiplabel.ashx?", imageID)
End Sub
Public Sub GetDeliveryConfirmationLabel()
Dim labeldate As String = package.ShipDate.ToShortDateString()
Dim url As String = "?API=DeliveryConfirmationV3&XML=<DeliveryConfirmationV3.0Request USERID=""{0}""><Option>{1}</Option><ImageParameters></ImageParameters><FromName>{2}</FromName><FromFirm>{3}</FromFirm><FromAddress1>{4}</FromAddress1><FromAddress2>{5}</FromAddress2><FromCity>{6}</FromCity><FromState>{7}</FromState><FromZip5>{8}</FromZip5><FromZip4>{9}</FromZip4><ToName>{10}</ToName><ToFirm>{11}</ToFirm><ToAddress1>{12}</ToAddress1><ToAddress2>{13}</ToAddress2><ToCity>{14}</ToCity><ToState>{15}</ToState><ToZip5>{16}</ToZip5><ToZip4>{17}</ToZip4><WeightInOunces>{18}</WeightInOunces><ServiceType>{19}</ServiceType><POZipCode>{20}</POZipCode><ImageType>{21}</ImageType><LabelDate>{22}</LabelDate><CustomerRefNo>{23}</CustomerRefNo><AddressServiceRequested>{24}</AddressServiceRequested><SenderName>{25}</SenderName><SenderEMail>{26}</SenderEMail><RecipientName>{27}</RecipientName><RecipientEMail>{28}</RecipientEMail></DeliveryConfirmationV3.0Request>"
url = GetURL() + url
'url = String.Format(url,this._userid, (int)package.LabelType, package.FromAddress.Contact, package.FromAddress.FirmName, package.FromAddress.Address1, package.FromAddress.Address2, package.FromAddress.City, package.FromAddress.State, package.FromAddress.Zip, package.FromAddress.ZipPlus4, package.ToAddress.Contact, package.ToAddress.FirmName, package.ToAddress.Address1, package.ToAddress.Address2, package.ToAddress.City, package.ToAddress.State, package.ToAddress.Zip, package.ToAddress.ZipPlus4, package.WeightInOunces.ToString(), package.ServiceType.ToString().Replace("_", " "), package.OriginZipcode, package.LabelImageType.ToString(), labeldate, package.ReferenceNumber, package.AddressServiceRequested.ToString(), package.FromAddress.Contact, package.FromAddress.ContactEmail, package.ToAddress.Contact, package.ToAddress.ContactEmail)
url = String.Format(url, _userid, CType(package.LabelType, Integer), fromFirstName.Text + " " + fromFirstName.Text, FromFirm.Text, FromAddress1.Text, FromAddress2.Text, FromCity.Text, FromState.Text, Fromzip.Text, FromZip2.Text, ToFirstName.Text + " " + ToLastName.Text, ToFirmNames, ToAddress1s, ToAddress2s, ToCitys, ToStates, ToZips, ToZip4s, package.WeightInOunces.ToString(), package.ServiceType.ToString().Replace("_", " "), package.OriginZipcode, package.LabelImageType.ToString(), labeldate, package.ReferenceNumber, package.AddressServiceRequested.ToString(), "", "", "", "")
Try
Dim myReq As HttpWebRequest
' Create the web request
myReq = DirectCast(WebRequest.Create(url), HttpWebRequest)
myReq.Method = "POST"
myReq.ContentType = "application/x-[URL unfurl="true"]www-form-urlencoded"[/URL]
Dim Resp As HttpWebResponse
' Get response
Resp = DirectCast(myReq.GetResponse(), HttpWebResponse)
Dim reader As StreamReader
' Get the response stream into a reader
reader = New StreamReader(Resp.GetResponseStream())
Dim xml As String = reader.ReadToEnd()
Resp.Close()
reader.Close()
If (xml.Contains("<Error>")) Then
Dim idx1 As Integer = xml.IndexOf("<Description>") + 13
Dim idx2 As Integer = xml.IndexOf("</Description>")
Dim l As Integer = xml.Length
Dim errDesc As String = xml.Substring(idx1, idx2 - idx1)
Updatelabel.Text = errDesc
Wizard1.ActiveStepIndex = 1 'send user back to the page where the problem most
Else ' only execute if there was no error
Dim i1 As Integer = xml.IndexOf("<DeliveryConfirmationLabel>") + 27
Dim i2 As Integer = xml.IndexOf("</DeliveryConfirmationLabel>")
package.ShippingLabel = StringToUTF8ByteArray(xml.Substring(i1, i2 - i1))
SaveBytesToSession(package.ShippingLabel)
End If
Catch ex As Exception
Console.WriteLine(ex)
End Try
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'happens when page is loaded
Service_type.Text = "Service Type: " + Servicetype.SelectedValue
packagesizes.Text = "Package Size: " + PackageType.SelectedValue
packagetypes.Text = "Package Type: " + PackageType.SelectedValue
packageweight.Text = "Package Weight: " + weight.Text
Label_type.Text = "Label Type: " + LabelType.SelectedValue
Image_type.Text = "Image Type: " + imagetype.SelectedValue
Originzipcode.Text = "Origin Zipcode: " + OriginZip.Text
Address_service.Text = "Address Service: " + AddressService.SelectedValue
waiver_sig.Text = "Waiver: " + waiver.SelectedValue
CustomerName.Text = "Customer Name: " + fromFirstName.Text + " " + FromLast.Text
CustomerEmail.Text = "Customer Email: " + FromEmail.Text
CustomerPhone.Text = "Customer Phone: " + FromPhone.Text
CustomerAddress.Text = "Customer Address " + FromAddress1.Text + " " + FromAddress2.Text + " " + FromCity.Text + " " + FromState.Text + " " + Fromzip.Text + " " + FromZip2.Text
CustomerRef.Text = "Customer Reference Num: " + Referencenum.Text
RecieversAddress.Text = "Reciever's Address: " + ToAddress1.Text + " " + ToAddress2.Text + " " + ToCity.Text + " " + ToState.Text + " " + Tozipp.Text + " " + ToZip2.Text
RecieversEmail.Text = "Reciever's Email: " + ToEmail.Text
RecieversName.Text = "Reciever's Name: " + ToFirstName.Text + " " + ToLastName.Text
RecieversPhone.Text = "Reciever's Phone: " + ToPhone.Text
End Sub
'#region
' <summary>
' To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
' </summary>
'<param name="characters">Unicode Byte Array to be converted to String</param>
'<returns>String converted from Unicode Byte Array</returns>
Private Function UTF8ByteArrayToString(ByRef characters As Byte())
Dim encoding As UTF8Encoding = New UTF8Encoding()
Dim constructedString As String = encoding.GetString(characters)
Return (constructedString)
End Function
' <summary>
' Converts the String to UTF8 Byte array and is used in De serialization
'</summary>
' <param name="pXmlString"></param>
' <returns></returns>
Private Function StringToUTF8ByteArray(ByVal pXmlString As String)
Dim encoding As UTF8Encoding = New UTF8Encoding()
Dim byteArray As Byte() = encoding.GetBytes(pXmlString)
Return byteArray
End Function
'#End Region
End Class
Below is the actual Handler for my code
========================================
Code:
<%@ WebHandler Language="VB" Class="ShipLabel" %>
Imports System
Imports System.Web
Public Class ShipLabel : Implements IHttpHandler
Public Sub ProcessRequest(ByVal ctx As HttpContext) Implements IHttpHandler.ProcessRequest
Dim chartID As String = ctx.Request.QueryString(0)
ctx.ClearError()
ctx.Response.Expires = 0
ctx.Response.Buffer = True
ctx.Response.Clear()
Dim memStream As IO.MemoryStream = New IO.MemoryStream(DirectCast(ctx.Session(chartID), Byte()))
memStream.WriteTo(ctx.Response.OutputStream)
memStream.Close()
ctx.Response.ContentType = "image/Jpeg"
ctx.Response.StatusCode = 200
ctx.Response.End()
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class