Library tutorials & articles

Retrieving HTTP content in .NET

Firing events

Other versions of the GetUrl() method return a StreamReader object and yet another version GetUrlEvents() that fires an OnReceiveData event whenever data arrives in the buffer. The event provides a current byte and total byte count (if available) as well as two flags Done and Cancel. Done lets you know when the request is finished, while the Cancel flag lets your code stop downloading data.

To run with the event enabled you just hook up an event handler to the event:

HttpWebRequest loHttp = new wwHttp();

loHttp.OnReceiveData += new
wwHttp.OnReceiveDataHandler(this.loHttp_OnReceiveData);

string lcHtml = loHttp.GetUrlEvents(this.txtUrl.Text.TrimEnd(),4096);

this.txtHTML.Text = lcHtml;

loHttp.OnReceiveData -=
  new wwHttp.OnReceiveDataHandler(
          this.loHttp_OnReceiveData);

Make sure to disconnect the handler at the end of your request, or set it up in a static location that runs only one time. The event handler method can then do some work with the data in the OnReceiveDataArgs object returned to you (Listing 3):

Listing 4: Implementing the wwHttp::OnReceiveData event

private void loHttp_OnReceiveData(object sender,
         wwHttp.OnReceiveDataEventArgs e) {
  if (e.Done)
   MessageBox.Show("Download Complete!");
  else if (e.NumberOfReads == 20) {
   MessageBox.Show("Cancelling... too large.");
   e.Cancel = true;
}
  else
   this.oStatus.Panels[0].Text =
     e.CurrentByteCount.ToString() + " of " +
     e.TotalBytes.ToString() + " bytes read";
}

Using the event is easy. Creating the event on the wwHttp class is a bit more involved and requires three steps:

First the actual event needs to be defined on the class:

public event OnReceiveDataHandler OnReceiveData;

Next the event's arguments need to be wrapped up into a class contains the arguments as properties:

public class OnReceiveDataEventArgs
{
  public long CurrentByteCount=0;
  public long TotalBytes = 0;
  public int NumberOfReads = 0;
  public char [] CurrentChunk;
  public bool Done = false;
  public bool Cancel = false;
}

Creating a public Delegate which acts as the method signature for the Event to be called:

public delegate void
 OnReceiveDataHandler(object sender,
           OnReceiveDataEventArgs e);

You only need to define this delegate if you want to pass custom parameters. If no parameters are required you can just define your event use the standard System.EventHandler delegate. These three pieces make up the event interface.

To actually fire the event you can simply run your code and call the call the function pointer that the user assigned to the event. Here's the relevant code from wwHttp that demonstrates how the Response loop is read and how the event is fired on each update cycle.

Listing 5: Reading the Response Stream and firing events

StreamReader oHttpResponse = this.GetUrlStream(Url);
if (oHttpResponse == null)
  return "";

long lnSize = BufferSize;

// *** Use StringBuilder to create the result string
StringBuilder loWriter = new StringBuilder((int) lnSize);
// *** Create the argument structure used as event parm
OnReceiveDataEventArgs oArgs = new OnReceiveDataEventArgs();
oArgs.TotalBytes = lnSize;

while (lnSize > 0) {
  lnSize = oHttpResponse.Read(lcTemp,0,(int) BufferSize);
  if (lnSize > 0)
  {
   loWriter.Append(lcTemp, 0,(int) lnSize);
   lnCount++;
   lnTotalBytes += lnSize;

   // *** Raise an event if hooked up
   if (this.OnReceiveData != null)
   {
     /// *** Update the event handler
     oArgs.CurrentByteCount = lnTotalBytes;
     oArgs.NumberOfReads = lnCount;
     oArgs.CurrentChunk = lcTemp;

    // *** Call the event method
     this.OnReceiveData(this,oArgs);

     // *** Check for cancelled flag
     if (oArgs.Cancel)
      goto CloseDown;
   }
  }
} // while

The key to this code is the delegate OnReceiveData. It acts a function pointer which points the assigned method on the form in the example above. From within the stream reading loop this method is called every time a new buffer is retrieved.

Comments

  1. 10 Jul 2007 at 15:29
      if (oReqCookie.Name ==
            oRespCookie.Name)  {
            oReqCookie.Value =
                   oRespCookie.Name;

    Do you mean?








     if (oReqCookie.Name ==
            oRespCookie.Name)  {
            oReqCookie.Value =
                   oRespCookie.Value;




  2. 12 Mar 2007 at 18:57

    You have a paragraph that states:

    "The most common use of delegates is an eventhandler, which uses the delegate to fire events. When the event publisher fires the event method, the delegate that is assigned to handle the event is called and you're event subscriber object then can simply handle the event by implementing a method in your class."

    Unfortunately, for someone trying desparately to learn C#, this sounds like:

    "blah blah blah blah blah blah"

    I'm sorry but could you publish a REAL SIMPLE example and explanation of asynch calls in Asp.net/C#.  I have been all over the web looking for one and they all assume you already know C# so all the delegate calling callback calling method calling delegate calling calling callingcallingcalling.................has just finally gotten on my nerves.

  3. 29 Dec 2006 at 22:27
    I'm just new to c# coming from VB.NET.  This is a great example!  Thanks
  4. 10 May 2006 at 04:30

    hi

    i have similar problem like you (in a previous time) with in using httwebrequest to login in a website... especially how to handle event clicking ex: onkeypress="checklogin()"

    i hope you can help me to solve the problem..

     

    thnx b4

  5. 18 Oct 2005 at 02:51

    hi
    I use httpwebrequest to login into a website (using Networkcrendential). When i got that page i need to click a link. How can we achieve this (axwebbrowser ?) and it contains frames. And also after clicking that menu in second page i have to click a Javascript button. Is there anyway to achieve this.


    Rajesh

  6. 25 Mar 2005 at 00:48
    Your article is very good and your source code is a good start.  It has some cool features but is lacking some good programming practices.  Most noteable is the lack of finally blocks used.  You should try to insure that the Close() method on the WebRequest and WebResponse objects are always closed before the object reference goes out of scope.  You can ensure that happens by placing your code in a try/finally block.

    Also, you should consider having your class implement the IDisposable interface.  And in that implementation clean up, close, and release the resources used by your private variables.
  7. 01 Jan 1999 at 00:00

    This thread is for discussions of Retrieving HTTP content in .NET.

Leave a comment

Sign in or Join us (it's free).

Rick Strahl
AddThis

Related discussion

Related podcasts

  • More jQuery in ASP.NET

    In this episode Chris Brandsma, Rick Strahl, Dave Ward, Bertrand Le Roy, and Scott Koon conclude their discussion of Microsoft's jQuery in ASP.NET announcement1.This episode of the Alt.NET Podcast is brought to you by LLBLGen Pro, the most mature O/R mapper and code generator out there.Are ...

Events coming up

  • Nov 18

    15 Minutes of Fame

    Dresher, United States

    This is a yearly tradition. We select 10 of the favorite speakers from monthly meetings, code camps, and hands on labs. Each one does a 15 minute talk on their favorite .NET technology. This is our 10th anniversary so we plan a gala event with special prizes and refreshments.

We'd love to hear what you think! Submit ideas or give us feedback