Figure 2 Managed XMLHttpRequest Interface
namespace XMLHttp
{
#region Framework Classes used
using System;
using System.Xml;
using System.Net;
using System.IO;
using System.Text;
#endregion
public class XMLHttpRequest
{
public XMLHttpRequest() {}
public void Dispose(){}
public event EventHandler OnReadyStatusChange;
public void Open(string Method, string Url, bool Asynch,
string User, string Password) {}
public void SetRequestHeader(string headerName,
string headerValue){}
public string GetResponseHeader(string Header){}
public string[] GetAllResponseHeaders(){}
public void Send(string body){}
public void Abort(){}
public int GetStatus(){}
public string GetStatusText(){}
public XmlDocument GetResponseXML(){}
public string GetResponseText(){}
public byte[] GetResponseBody(){}
public System.IO.Stream GetResponseStream(){}
public eReadyState GetReadyState(){}
}
}
Figure 3 XMLHttpRequest
Member
|
Description
|
Abort
|
Cancels the current HTTP request
|
GetAllResponseHeaders
|
Retrieves the values of all the HTTP headers
|
GetResponseHeader
|
Retrieves the value of an HTTP header from the response body
|
OnReadyStateChange
|
Event handler to be called when the readystate changes
|
Open
|
Initializes a HttpWebRequest, and specifies the method, URL, and authentication information for the request
|
GetReadyState
|
Represents the state of the request
|
GetResponseBody
|
Represents the response entity body as an array of unsigned bytes
|
GetResponseStream
|
Represents the response entity body as a SystemIOStream
|
GetResponseText
|
Represents the response entity body as a string
|
GetResponseXML
|
Represents the response entity body as parsed by the XMLDOM parser
|
Send
|
Sends an HTTP request to the server and receives a response
|
SetRequestHeader
|
Specifies the name of an HTTP header
|
GetStatus
|
Represents the HTTP status code returned by a request
|
GetStatusText
|
Represents the HTTP response line status
|
Figure 4 ReadyState Values
Value
|
Description
|
0 (UNINITIALIZED)
|
The object has been created, but has not been initialized (open has not been called)
|
1 (LOADING)
|
The object has been created, but the send method has not been called
|
2 (LOADED)
|
The send method has been called and the status and headers are available, but the response is not yet available
|
3 (INTERACTIVE)
|
Some data has been received. You can call GetResponseBody and GetResponseText to get the current partial results
|
4 (COMPLETED)
|
All the data has been received, and the complete data is available in GetResponseBody and GetResponseText
|
Figure 5 ReadyState Enum Declaration
namespace XMLHttp
{
#region Framework Classes used
using System;
using System.Xml;
using System.Net;
using System.IO;
using System.Text;
#endregion
#region Public Enums
public enum eReadyState: int
{
UNINITIALIZED = 0,
LOADING = 1,
LOADED = 2,
INTERACTIVE = 3,
COMPLETED = 4
}
#endregion
public class XMLHttpRequest
{
private eReadyState lgReadyState = eReadyState.UNINITIALIZED;
}
Figure 6 Implementing the Open Method
public void Open(string Method, string Url, bool Asynch, string User,
string Password)
{
if (request != null)
throw new InvalidOperationException("Connection Already open");
if (Url == "" || Url==null)
throw new ArgumentNullException("URL must be specified");
System.Uri uriObj = new System.Uri(Url);
if (!((uriObj.Scheme == System.Uri.UriSchemeHttp) ||
(uriObj.Scheme == System.Uri.UriSchemeHttps)))
throw new ArgumentOutOfRangeException("URL Scheme is not
http or https");
if (Method==null ||
(Method.ToUpper()!="POST" && Method.ToUpper()!="GET" &&
Method.ToUpper()!="PUT" &&
Method.ToUpper()!="PROPFIND"))
throw new ArgumentOutOfRangeException("Method
argument type not defined");
lgbIsAsync = Asynch;
lgRequest = (HttpWebRequest)WebRequest.CreateDefault(uriObj);
lgRequest.Method = Method;
lgRequest.ContentType = "text/xml";
lgRequest.Credentials = new SingleCredential(User, Password);
lgReadyState = eReadyState.LOADING;
}
Figure 7 Implementing SetRequestHeader
public void SetRequestHeader(string headerName, string headerValue)
{
try
{
if (lgReadyState != eReadyState.LOADING)
throw new InvalidOperationException("Setting request headers
is not allowed at this ReadyState");
switch(headerName)
{
case "Accept":
lgRequest.Accept = headerValue;
break;
case "Connection":
lgRequest.Connection = headerValue;
break;
case "Content-Length":
lgRequest.ContentLength = Convert.ToInt32(headerValue);
break;
case "Content-Type":
lgRequest.ContentType = headerValue;
break;
case "Expect":
lgRequest.Expect = headerValue;
break;
case "Date":
throw new Exception("These headers are set by the
system");
case "Host":
throw new Exception("These headers are set by the
system");
case "Range":
throw new Exception("This header is set with AddRange");
case "Referer":
lgRequest.Referer = headerValue;
break;
case "Transfer-Encoding":
lgRequest.TransferEncoding = headerValue;
break;
case "User-Agent":
lgRequest.UserAgent = headerValue;
break;
default:
lgRequest.Headers.Add(headerName , headerValue);
break;
}
}
catch(Exception e)
{
throw new Exception ("Error occurred while setting request
headers",e);
}
}
Figure 8 Implementing the Send Method
public void Send(string body)
{
if (lgReadyState != eReadyState.LOADING)
throw new InvalidOperationException("Sending a message is not
allowed at this ReadyState");
if (body != null)
{
StreamWriter stream = new StreamWriter
(lgRequest.GetRequestStream(), Encoding.ASCII);
stream.Write(body);
stream.Close();
lgResponse = (HttpWebResponse)lgRequest.GetResponse();
lgReadyState = eReadyState.COMPLETED;
}
}
Figure 9 Implementing GetResponseXML
public XmlDocument GetResponseXML()
{
try
{
if(lgReadyState==eReadyState.COMPLETED)
{
Stream stream = GetResponseStream();
XmlTextReader reader = new XmlTextReader(stream);
XmlDocument document = new XmlDocument();
document.Load(reader);
reader.Close();
stream.Close();
return document;
}
else
throw new InvalidOperationException("Getting response XML is
forbidden at current
ReadyState");
}
catch (Exception e)
{
throw new Exception ("Error occurred while retrieving XML
response",e);
}
}
Figure 10 Implementing the Satellite Methods
public string GetResponseHeader(string Header)
{
if(lgReadyState == eReadyState.LOADED ||
lgReadyState == eReadyState.INTERACTIVE ||
lgReadyState == eReadyState.COMPLETED)
return lgResponse.GetResponseHeader(Header);
else
throw new InvalidOperationException("Getting Response Headers
forbidden at current ReadyState");
}
public string[] GetAllResponseHeaders()
{
if(lgReadyState == eReadyState.LOADED ||
lgReadyState == eReadyState.INTERACTIVE ||
lgReadyState == eReadyState.COMPLETED)
return lgResponse.Headers.All;
else
throw new InvalidOperationException("Getting Response Headers
forbidden at current ReadyState");
}
public int GetStatus()
{
if(lgReadyState==eReadyState.COMPLETED)
return lgResponse.Status;
else
throw new InvalidOperationException("Getting response status is
forbidden at current ReadyState");
}
public string GetStatusText()
{
if(lgReadyState==eReadyState.COMPLETED)
return lgResponse.StatusDescription;
else
throw new InvalidOperationException("Getting response status is
forbidden at current ReadyState");
}
public eReadyState GetReadyState()
{
return lgReadyState;
}
Figure 11 Implementing GetResponseBody
public string GetResponseText()
{
if(lgReadyState==eReadyState.COMPLETED)
{
StreamReader reader = new StreamReader(GetResponseStream());
return reader.ReadToEnd();
}
else
throw new InvalidOperationException("Getting response text is
forbidden at current ReadyState");
}
public byte[] GetResponseBody()
{
if(lgReadyState==eReadyState.COMPLETED)
{
Stream stream = GetResponseStream();
BinaryReader reader = new BinaryReader(stream);
long count = stream.Length;
return reader.ReadBytes((int)count);
}
else
throw new InvalidOperationException("Getting response body is
forbidden at current ReadyState");
}
Figure 12 Implementing the Asynchronous Send Method
public void Send(string body)
{
if (lgReadyState != eReadyState.LOADING)
throw new InvalidOperationException("Sending a message is not
allowed at this ReadyState");
if (body != null)
{
lgRequest.ContentLength = body.Length;
if(lgbIsAsync)
{
lgMsg = body;
IAsyncResult res = lgRequest.BeginGetRequestStream(new
AsyncCallback(ReqCallback),lgRequest);
lgReadyState = eReadyState.LOADED;
}
else
{
StreamWriter stream = new StreamWriter
(lgRequest.GetRequestStream(), Encoding.ASCII);
stream.Write(body);
stream.Close();
lgResponse = (HttpWebResponse)lgRequest.GetResponse();
lgReadyState = eReadyState.COMPLETED;
}
}
}
private void ReqCallback(IAsyncResult ar)
{
HttpWebRequest req = (HttpWebRequest) ar.AsyncState;
System.IO.Stream stream = req.EndGetRequestStream(ar);
StreamWriter streamW = new StreamWriter(stream);
streamW.Write(lgMsg);
streamW.Close();
stream.Close();
IAsyncResult resp = req.BeginGetResponse(new
AsyncCallback(RespCallback), req);
}
private void RespCallback(IAsyncResult ar)
{
WebRequest req = (WebRequest) ar.AsyncState;
lgResponse = (HttpWebResponse)req.EndGetResponse(ar);
lgReadyState = eReadyState.COMPLETED;
EventArgs e = new EventArgs();
OnReadyStatusChange(this,e);
}
Figure 14 Initializing the XMLHttpRequest Object
public frmTest()
{
InitializeComponent();
httpRequest = new XMLHttpRequest();
httpRequest.OnReadyStatusChange += new
EventHandler(OnReadyStatusChange);
cboUDDINode.SelectedIndex = 1;
}
void OnReadyStatusChange(object sender, EventArgs e)
{
}
Figure 15 Sending a Message
protected void cmdSend_Click (object sender, System.EventArgs e)
{
if(chkUseProxy.Checked==true)
setProxy();
else
GlobalProxySelection.Select=null;
bool bAsync=true;
if(optSynch.Checked)
bAsync=false;
string msg = getMessage();
httpRequest.Open("POST", cboUDDINode.Text, bAsync, "", "");
httpRequest.SetRequestHeader("Accept","text/xml");
httpRequest.SetRequestHeader("Cache-Control","no-cache");
httpRequest.SetRequestHeader("Content-Length",msg.Length.ToString());
httpRequest.SetRequestHeader("SOAPAction","\"\"");
httpRequest.Send(msg);
if(!bAsync)
{
System.Xml.XmlDocument doc = httpRequest.GetResponseXML();
txtUDDIResponse.Text = doc.OuterXml;
httpRequest.Dispose();
}
}
void OnReadyStatusChange(object sender, EventArgs e)
{
System.Xml.XmlDocument doc = httpRequest.GetResponseXML();
txtUDDIResponse.Text = doc.OuterXml;
httpRequest.Dispose();
}
|