< C++ Service Point Program Example | Main | VB .NET Service Point Program Example >

 


 

Chapter 10 Part 13:

HTTP with .NET

 

 

What do we have in this chapter 10 Part 13?

  1. C# Service Point Program Example

 

 

C# Service Point Program Example

 

Create a new console application project and you might want to use ServicePointCS as the solution and project names.

 

C# Service Point Program Example - creating a new console application project in Visual Studio 2008 IDE

 

Rename the source file to ServicePointClass to reflect the application that we are going to develop. The default given class name will automatically renamed to the source file.

 

C# Service Point Program Example - renaming the source file automatically renaming the class

 

Add/edit the following code. We have two classes and the Main() method.

 

using System;

using System.Net;

using System.Collections;

using System.Threading;

using System.IO;

 

namespace ServicePointCS

{

    /// <summary>

    /// Maintains context information for each HTTP request

    /// </summary>

    public class HttpState

    {

        public HttpWebRequest httpRequest;

        public HttpWebResponse httpResponse;

        public Stream httpResponseStream;

        public Uri uriResource;

        public byte[ ] readBuffer;

        public ManualResetEvent doneEvent;

        public int bytesReceived;

 

        public const int DefaultReadBufferLength = 4096;

 

        /// <summary>

        /// Constructor for initializing HttpState object

        /// </summary>

        /// <param name="resource">URI to retrieve</param>

        /// <param name="done">Event to signal when done</param>

        public HttpState(Uri resource, ManualResetEvent done)

        {

            httpRequest = null;

            httpResponse = null;

            uriResource = resource;

            readBuffer = new byte[DefaultReadBufferLength];

            doneEvent = done;

            bytesReceived = 0;

        }

    }

 

    /// <summary>

    /// Contains the ServicePoint sample

    /// </summary>

    class ServicePointClass

    {

        /// <summary>

        /// Displays usage information

        /// </summary>

        public static void usage()

        {

            Console.WriteLine("Executable_file_name [-u URI] [-p proxy] [-l count] [-s count]");

            Console.WriteLine("Available options:");

            Console.WriteLine("     -u URI      URI resource to retrieve");

            Console.WriteLine("     -p proxy    Proxy server to use");

            Console.WriteLine("     -l count    Maximum number of concurrent connections");

            Console.WriteLine("     -s count    Maximum number of ServicePoint instances");

            Console.WriteLine();

        }

 

        /// <summary>

        /// Asynchronous delegate for read operation on the HTTP stream.

        /// </summary>

        /// <param name="ar">Asynchronous context information for operation</param>

        public static void HttpStreamReadCallback(IAsyncResult ar)

        {

            HttpState httpInfo = (HttpState)ar.AsyncState;

 

            try

            {

                long percent = 0;

                int count = httpInfo.httpResponseStream.EndRead(ar);

 

                httpInfo.bytesReceived += count;

 

                percent = (long)(httpInfo.bytesReceived * 100) / httpInfo.httpResponse.ContentLength;

                Console.WriteLine("{0}: read {1} bytes: {2}%", httpInfo.uriResource.AbsoluteUri.ToString(), count, percent.ToString().PadLeft(4));

 

                if (count > 0)

                {

                    PostStreamRead(httpInfo);

                }

                else

                {

                    httpInfo.httpResponseStream.Close();

                    httpInfo.httpResponseStream = null;

                    httpInfo.httpResponse.Close();

                    httpInfo.httpResponse = null;

                    httpInfo.doneEvent.Set();

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine("Exception occurred: {0}", ex.Message);

                if (httpInfo.httpResponseStream != null)

                    httpInfo.httpResponseStream.Close();

                if (httpInfo.httpResponse != null)

                    httpInfo.httpResponse.Close();

                httpInfo.doneEvent.Set();

            }

        }

 

        /// <summary>

        /// Post as an asynchronous receive operation on the HTTP stream.

        /// </summary>

        /// <param name="httpInfo">Context information for HTTP request</param>

        public static void PostStreamRead(HttpState httpInfo)

        {

            IAsyncResult asyncStreamRead = httpInfo.httpResponseStream.BeginRead(

                httpInfo.readBuffer,

                0,

                httpInfo.readBuffer.Length,

                new AsyncCallback(HttpStreamReadCallback),

                httpInfo

                );

        }

 

        /// <summary>

        /// Asynchronous delegate for the HTTP response.

        /// </summary>

        /// <param name="ar">Asynchronous context information</param>

        public static void HttpResponseCallback(IAsyncResult ar)

        {

            HttpState httpInfo = (HttpState)ar.AsyncState;

 

            try

            {

                httpInfo.httpResponse = (HttpWebResponse)httpInfo.httpRequest.EndGetResponse(ar);

                httpInfo.httpResponseStream = httpInfo.httpResponse.GetResponseStream();

                PostStreamRead(httpInfo);

            }

            catch (WebException wex)

            {

                Console.WriteLine("Exception occurred: {0}", wex.Message);

                Console.WriteLine(wex.StackTrace);

                httpInfo.doneEvent.Set();

            }

        }

 

 

 

        /// <summary>

        /// Retrieves the given resource

        /// </summary>

        /// <param name="uriResource">URI to retrieve</param>

        /// <param name="doneEvent">Event to signal when done</param>

        public static void GetUriResource(Uri uriResource, ManualResetEvent doneEvent)

        {

            HttpState httpInfo = new HttpState(uriResource, doneEvent);

 

            try

            {

                Console.WriteLine("Issuing an async GET request for: {0}", uriResource.ToString());

                httpInfo.httpRequest = (HttpWebRequest)WebRequest.Create(uriResource.AbsoluteUri);

                httpInfo.httpRequest.BeginGetResponse(new AsyncCallback(HttpResponseCallback), httpInfo);

                Console.WriteLine("POSTED lor!");

            }

            catch (WebException wex)

            {

                Console.WriteLine("Exception occurred: {0}", wex.Message);

                doneEvent.Set();

            }

        }

 

        /// <summary>

        /// Main application which parses the command line and issues the HTTP request.

        /// </summary>

        /// <param name="args">Command line arguments</param>

        static void Main(string[ ] args)

        {

        ArrayList uriList = new ArrayList();

        IWebProxy  httpProxy = WebRequest.DefaultWebProxy;

        int connectionLimit = 2, servicePointLimit = 1;

        int i;

 

        usage();

 

        // Parse the command line

        for(i=0; i < args.Length ;i++)

        {

            try

            {

                if ( ( args[i][0] == '-' ) || ( args[i][0] == '/' ) )

                {

                    switch ( Char.ToLower( args[i][1] ) )

                    {

                        case 'u':

                            // URI to download (get)

                            uriList.Add( new Uri( args[ ++i ] ) );

                            break;

                        case 'p':

                            // Name of proxy server to use

                            httpProxy = new WebProxy( args[ ++i ] );

                            break;

                        case 'l':

                            // Number of connections limited to service point manager

                            connectionLimit = System.Convert.ToInt32( args[ ++i ] );

                            break;

                        case 's':

                            // Service point limit

                            servicePointLimit = System.Convert.ToInt32( args[ ++i ] );

                            break;

                        default:

                            usage();

                            return;

                    }

                }

            }

            catch

            {

                usage();

                return;

            }

        }

 

        try

        {

            ManualResetEvent [ ] requestEvents = new ManualResetEvent[ uriList.Count ];

            // Setup the ServicePointManager first

            WebRequest.DefaultWebProxy = httpProxy;

            ServicePointManager.MaxServicePoints = servicePointLimit;

            ServicePointManager.DefaultConnectionLimit = connectionLimit;

            ServicePointManager.MaxServicePointIdleTime = 20000; // 20 seconds

            Console.WriteLine("Uri count: {0}", uriList.Count);

 

            for(i=0; i < uriList.Count ;i++)

            {

                Console.WriteLine("Uri: {0}", ((Uri)uriList[i]).ToString() );

                string baseUri = "http://" + ((Uri)uriList[i]).Host + "/";

                Console.WriteLine("Base URI: {0}", baseUri );

                ServicePoint    sp = ServicePointManager.FindServicePoint((Uri)uriList[i], httpProxy );

                requestEvents[i] = new ManualResetEvent( false );

                GetUriResource( (Uri)uriList[i], requestEvents[i] );

            }

            Console.WriteLine("Waiting...");

            ManualResetEvent.WaitAll( requestEvents );

            Console.WriteLine("Considered done...");

        }

        catch ( Exception ex )

        {

            Console.WriteLine("Exception occurred: {0}", ex.Message);

        }

        }

    }

}

 

 

Build the project.

 

C# Service Point Program Example - building the project

 

Run the project.

 

C# Service Point Program Example - running the project

 

The following is the sample output with default arguments.

 

C# Service Point Program Example - a sample output with default arguments

 

The following is a sample output when run from the command prompt with two URIs. Well, there is an error on the percentage of the progress for one of the URI. This is left for your exercise to rectify the logical error!

 

C# Service Point Program Example - a sample output when run from command prompt with argument values

 

 

 


 

< C++ Service Point Program Example | Main | VB .NET Service Point Program Example >