Tag Archive > class

C# Basic HTTP Request Class

» 11 March 2011 » In C#, Programming » 7 Comments

Most of my clients, want me to do things with a Graphical User Interface. For this, I only have on language in mind, C#. And many of my client-related projects includes getting information from webpages, logging in, gathering data, etc. It’s very hard to repeat code over and over again with the HttpWebRequest and HttpWebResponse class. For this, I created a simple class that does GET and POST neatly and can handle cookies. Please do note that I didn’t reinvent the wheel on this one. This is just a collection of mostly used functions to make them reusable in many of my (and could be your) projects.

A simple HTTP GET request looks like this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://ruel.me");
request.CookieContainer = cJar;
request.UserAgent = UserAgent;
request.KeepAlive = false;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string response = sr.ReadToEnd();

And I think it’s fairly unacceptable to repeat this code over and over again in a single project. So yes, there should be a class made for this (together with the POST request).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace BasicReq
{
    /// <summary>
    /// A simple basic class for HTTP Requests.
    /// </summary>
    class BReq
    {
        /// <summary>
        /// UserAgent to be used on the requests
        /// </summary>
        public string UserAgent = @"Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/534.23 (KHTML, like Gecko) Chrome/11.0.686.3 Safari/534.23";
        
        /// <summary>
        /// Cookie Container that will handle all the cookies.
        /// </summary>
        private CookieContainer cJar;

        /// <summary>
        /// Performs a basic HTTP GET request.
        /// </summary>
        /// <param name="url">The URL of the request.</param>
        /// <returns>HTML Content of the response.</returns>
        public string HttpGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.CookieContainer = cJar;
            request.UserAgent = UserAgent;
            request.KeepAlive = false;
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            return sr.ReadToEnd();
        }

        /// <summary>
        /// Performs a basic HTTP POST request
        /// </summary>
        /// <param name="url">The URL of the request.</param>
        /// <param name="post">POST Data to be passed.</param>
        /// <param name="refer">Referrer of the request</param>
        /// <returns>HTML Content of the response.</returns>
        public string HttpPost(string url, string post, string refer = "")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.CookieContainer = cJar;
            request.UserAgent = UserAgent;
            request.KeepAlive = false;
            request.Method = "POST";
            request.Referer = refer;

            byte[] postBytes = Encoding.ASCII.GetBytes(post);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postBytes.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();
            
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            
            return sr.ReadToEnd();
        }

        /// <summary>
        /// Creates an HTML file from the string.
        /// </summary>
        /// <param name="html">HTML String.</param>
        public void DebugHtml(string html)
        {
            StreamWriter sw = new StreamWriter("debug.html");
            sw.Write(html);
            sw.Close();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BReq"/> class.
        /// </summary>
        public BReq()
        {
            cJar = new CookieContainer();
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="BReq"/> is reclaimed by garbage collection.
        /// </summary>
        ~BReq()
        {
            // Nothing here
        }
    }
}

Of course the UserAgent is a public variable, so you can change it anytime upon initialization. The cookie container is used only inside the class. Yes, that’s a major con, but you can freely modify it. And that means, you can only use this class on one function if you would like to retain the cookies.

There’s also a DebugHtml function that can help you log the last request (by passing the response as a parameter, outside the class).

That’s it for now, and I highly suggest we help each other improve this class by forking it. This way improvements and ideas can be added. The more the merrier! Thank you.

Forks

These people made wonderful forks!

Continue reading...

Tags: , , , , , , , ,

Merge Class Sorting Algorithm

» 08 September 2010 » In C/C++, Programming » 2 Comments

On my last post about sorting algorithm, I made a pretty bad coding mistake on the merge function. The thing is, it doesn’t really demonstrate that algorithm. Also, it never worked on Visual Studio, for some weird reasons.

I spent few hours, and now I am finished reconstructing the whole program and making the merge algorithm really work. I built a class for it, and I’m pretty sure this will work on any situation. Here are the source codes.

//MergeClass.h

#pragma once
#include "stdafx.h"
class MergeClass {
public:
    double xarr[ASIZE], brr[ASIZE];
    void msort(double a[], int x) {
        for(int i = 0; i < ASIZE; i++) {
            xarr[i] = a[i];
        }
        mergesort(0, x - 1);
        for(int i = 0; i < ASIZE; i++) {
            a[i] = xarr[i];
        }
    }
    void mergesort(int a, int b) {
        int c;
        if(a < b) {
            c = (a + b) / 2;
            mergesort(a, c);
            mergesort(c + 1, b);
            domerge(a, b, c);
        }
    }
    void domerge(int a, int b, int c) {
        int i, j, k;
        for(i = a; i <= b; i++) {
            brr[i] = xarr[i];
        }
        i = a;
        j = a;
        k = c + 1;
        while((i <= c) && (k <= b)) {
            if(brr[i] <= brr[k]) {
                xarr[j++] = brr[i++];
            } else {
                xarr[j++] = brr[k++];
            }
        }
        while(i <= c) {
            xarr[j++] = brr[i++];    
        }
    }
};
// stdafx.h

#pragma once
#include "targetver.h"
#include <iostream>
#define ASIZE 6            //Size of the array you are to sort. This is very much used in this program.

using namespace::std;
// SortingAlgorithm.cpp

#include "stdafx.h"
#include "MergeClass.h"


void pH();                                            //function for my header
void pVal(double arr[], char *sor, int len);        //Outputs the inputted array
void bubbleS(double arr[], int len, bool out);        //Bubble Sort
void insertS(double arr[], int len, bool out);        //Insertion Sort
void selectS(double arr[], int len, bool out);        //Selection Sort
void mergeS(double arr[], int len, bool out);        //Merge Sort (initializer)

int main() {
    bool lp = true;
    int ch;
    double sArray[ASIZE] = {86.49, 201.35, 55.67, 1942.46, 291.64, 193.14};
    pH();
    pVal(sArray, "None", ASIZE);
    cout << "Please enter the sorting algorithm you want to use:" << endl << endl;
    cout << "\t[1] Bubble Sort" << endl;
    cout << "\t[2] Insertion Sort" << endl;
    cout << "\t[3] Selection Sort" << endl;
    cout << "\t[4] Merge Sort" << endl;
    cout << "\t[5] None (Exit)" << endl;
    while (lp) {
        cout << endl << "Choice: ";
        cin >> ch;
        cin.ignore();
        switch(ch) {
            case 1:
                bubbleS(sArray, ASIZE, true);
                lp = false;
                break;
            case 2:
                insertS(sArray, ASIZE, true);
                lp = false;
                break;
            case 3:
                selectS(sArray, ASIZE, true);
                lp = false;
                break;
            case 4:
                mergeS(sArray, ASIZE, true);
                lp = false;
                break;
            case 5:
                lp = false;
                break;
            default:
                cout << "(Invalid Choice)" << endl;
        }
    }
    cin.get();
    return 0;
}

void pH() {
    cout << "(c) Ruel Pagayon 2010 - http://ruel.me" << endl;
}

void pVal(double arr[], char *sor, int len) {
    cout << endl << "Sorting Algorithm:\t" << sor << endl << endl;
    for(int i = 0; i < len; i++) {
        cout << "\t[" << i << "]\t=>\t" << arr[i] << endl;
    }
    cout << endl;
}

void bubbleS(double arr[], int len, bool out) {
    double h;
    for (int p = 0; p < len - 1; p++) {
        for(int i = 0; i < len - 1; i++) {
            if(arr[i] > arr[i + 1]) {
                h = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = h;
            }
        }
    }
    if(out) {
        pVal(arr, "Bubble Sort", len);
    }
}

void insertS(double arr[], int len, bool out) {
    double tb;
    for(int j, i = 0; i < len; i++) {
        tb = arr[i];
        j = i - 1;
        while ((tb < arr[j]) && (j >= 0)) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = tb;
    }
    if(out) {
        pVal(arr, "Insert Sort", len);
    }
}

void selectS(double arr[], int len, bool out) {
    double mV;
    for (int mI, i = 0; i < len - 1; i++) {
        mV = arr[i];
        mI = i;
        for(int j = i + 1; j < len; j++) {
            if(arr[j] < mV) {
                mV = arr[j];
                mI = j;
            }
        }
        arr[mI] = arr[i];
        arr[i] = mV;
    }
    if(out) {
        pVal(arr, "Selection Sort", len);
    }
}

void mergeS(double arr[], int len, bool out) {
    MergeClass mx;
    mx.msort(arr, len);
    if(out) {
        pVal(arr, "Merge Sort", len);
    }
}

There we go. If you face problems regarding the code, please feel free to comment. By the way, the code was coded, compiled, and built on Visual C++.

Continue reading...

Tags: , , , ,