Showing posts with label HttpWebRequest. Show all posts
Showing posts with label HttpWebRequest. Show all posts

Saturday, March 3, 2012

How to check url is still alive in asp.net

When I develop the web directory "iblogseeker.com", I need to check blog url user input. I found out the best way to detect whether a blog is alive or not, since blog url is very important and sensitive in this case. This example show detecting url on web using System.Net.HttpWebRequest and HttpWebRequest, and ValidatorCallout and RegularExpressionValidator for validating client side user input.

ValidatorCallout is an ASP.NET AJAX extender that enhances the functionality of existing ASP.NET validators. To use this control, add an TextBox "txtUrl" and a validator control "RegularExpressionValidator1" as you normally do. Then add the ValidatorCallout "ValidatorCalloutExtender1" and set its TargetControlID property to reference the validator control.

Validating Url with ASP.Net

Add the following code to <form> tag.
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <asp:Label ID="Label2" runat="server" Text="URL :"></asp:Label><br/>
        <asp:TextBox ID="txtUrl" runat="server" Width="250px" MaxLength="200">http://www.iblogseeker.com</asp:TextBox>
        <asp:Button ID="button1" runat="server" Text="Go" onclick="button1_Click" />
        <br />
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
            ControlToValidate="txtUrl"
            ValidationExpression="http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?"
            Display="None"
            ErrorMessage="<b>Url is not well-formatted.</b><br />
            <div style='margin-top:5px;padding:5px;border:1px solid #e9e9e9;background-color:white;'>
            <b>e.g.&nbsp;</b>
            <a href='javascript:window.open(&quot;http://www.aspmemo.net&quot;);'>http://www.aspmemo.net</a></div>">
            </asp:RegularExpressionValidator>
        <asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender1"
            runat="server" Enabled="True" TargetControlID="RegularExpressionValidator1"></asp:ValidatorCalloutExtender>
        <br />
        <asp:Label ID="lblUrlMsg" runat="server"></asp:Label>
    </div>
</form>


In code-behind, button click event look like as below.

protected void button1_Click(object sender, EventArgs e)
{
    try
    {
        string url = txtUrl.Text;
        HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
        request.AllowAutoRedirect = false;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            string msg = string.Empty;
            switch (response.StatusCode)
            {
                case HttpStatusCode.OK: //HTTP status 200
                    msg = HttpStatusCode.OK.ToString();
                    break;
                case HttpStatusCode.NoContent: //HTTP status 204
                    msg = HttpStatusCode.NoContent.ToString();
                    break;
                case HttpStatusCode.NotFound: //HTTP status 404
                    msg = HttpStatusCode.NotFound.ToString();
                    break;
                case HttpStatusCode.RequestTimeout: //HTTP status 408
                    msg = HttpStatusCode.RequestTimeout.ToString();
                    break;
                case HttpStatusCode.ServiceUnavailable: //HTTP status 503
                    msg = HttpStatusCode.ServiceUnavailable.ToString();
                    break;
                case HttpStatusCode.Unauthorized: //HTTP status 401
                    msg = HttpStatusCode.Unauthorized.ToString();
                    break;
                case HttpStatusCode.MovedPermanently: //HTTP status 301
                    msg = HttpStatusCode.MovedPermanently.ToString();
                    break;
                case HttpStatusCode.BadRequest: //HTTP status 400
                    msg = HttpStatusCode.BadRequest.ToString();
                    break;
                default:
                    msg = "Invalid URL!";
                    break;
            }
            lblUrlMsg.Text = msg;
        }
    }
    catch (Exception ex)
    {
        lblUrlMsg.Text = "Invalid URL!";
    }
}

Whenever you type not-well-formatted url (including special character), it show message. if you put well-formatted url, it show HttpStatus of url.

HttpStatusCode : http://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx

ValidatorCallout Demonstration : http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ValidatorCallout/ValidatorCallout.aspx

Monday, January 2, 2012

How to download image from a web site programatically using HttpWebRequest

I was working on adding new features to Car Pass application. The new feature will show some details about the car accident and one of the details is showing map image associated with car accident event. To get that, I have developed an image service that downloads the map images(Google Static Map see here) in the background. This is done using HttpWebRequest object to send request to image URL with parameter. Following code shows you how you can download an image from a Url programatically using HttpWebRequest.

Create .aspx page and put the following code in code-behind.
protected void Page_Load(object sender, EventArgs e)
{
    //Here should be your image url.
    String url = "http://maps.googleapis.com/maps/api/staticmap?center=huamark,bangkapi,th&zoom=15&size=500x500&scale=1&format=jpg&maptype=roadmap&language=en&markers=icon:http://www.iblogseeker.com/favicon.ico|13.758185,100.628732&sensor=false";

    HttpWebRequest webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
    HttpWebResponse resp = webRequest.GetResponse() as HttpWebResponse;
    if (resp.StatusCode == HttpStatusCode.OK)
    {
        if (resp.ContentType.Contains("image/"))
        {
            int pos = resp.ContentType.IndexOf("/");
            string fileName = string.Format("{0}.{1}", "Map", resp.ContentType.Substring(pos + 1));
            byte[] imageContent = ProcessImageStream(resp);

            MemoryStream ms = new MemoryStream(imageContent);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            string path = string.Format(@"G:\{0}", fileName);
            img.Save(path);

            //for image manipulation with third party component such as Telerik Reporting, Bitmap is better.
            //e.g. when you rotate image and put in Telerik Report as image.
            System.Drawing.Bitmap bmap= new Bitmap(ms);
            bmap.RotateFlip(RotateFlipType.Rotate90FlipXY);
            bmap.Save(string.Format(@"G:\B{0}", fileName));
        }
    }
}

Here is utility function called from Page_Load.
private static byte[] ProcessImageStream(HttpWebResponse resp)
{
    byte[] streamContent;
    MemoryStream memStream = new MemoryStream();
    const int BUFFER_SIZE = 4096;
    int iRead = 0;
    Int64 iSize = 0;
    memStream.SetLength(BUFFER_SIZE);
    try
    {
        using (memStream)
        {
            while (true)
            {
                iRead = 0;
                byte[] respBuffer = new byte[BUFFER_SIZE];
                iRead = resp.GetResponseStream().Read(respBuffer, 0, BUFFER_SIZE);
                if (iRead == 0)
                {
                    break;
                }
                iSize += iRead;
                memStream.SetLength(iSize);
                memStream.Write(respBuffer, 0, iRead);
            }
            streamContent = memStream.ToArray();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return streamContent;
}

When you run the application, it download image and save two images in drive G:.