Thursday, August 28, 2008

Check if a URL actually exists

0 comments
We have seen many validations for URLs.
But what to do if the requirement is like to check whether a URL is in the NET.
In other words, how can one knows the URL given has not returned a 404 error?

Here's the code



/// <summary>
/// Checks the status of the specified URL.
/// </summary>
/// <param name="strURL">The URL that needs to be checked</param>
/// <returns>True if the URL exists</returns>

public bool IsURLValid(string strURL)
{
string strResponse = "";
try
{
string pattern = @"((http|ftp|https):\/\/w{3}[\d]*.|(http|ftp|https):\/\/|w{3}[\d]*.)([\w\d\._\-#\(\)\[\]\\,;:]+@[\w\d\._\-#\(\)\[\]\\,;:])?([a-z0-9]+.)*[a-z\-0-9]+.([a-z]{2,3})?[a-z]{2,6}(:[0-9]+)?(\/[\/a-z0-9\._\-,]+)*[a-z0-9\-_\.\s\%]+(\?[a-z0-9=%&\.\-,#]+)?";
//validatng url in case if it hasn't been validated earlier
if(Regex.IsMatch(strURL,pattern))
{
WebRequest request = HttpWebRequest.Create(strURL);
request.Timeout = 5000;
strResponse = ((HttpWebResponse)request.GetResponse()).StatusCode.ToString();
}
}
catch(Exception exp)
{
strResponse = "";
}
return (strResponse=="OK")? true: false;
}



Does the work, but not very classy.
Any better ideas?
Read more...

Saturday, August 16, 2008

The Coalesce Operator (The ?? Operator in C#)e

3 comments
The Conventional Way
if (obj1 != null)
{
objOut = obj1;
}
else
{
objOut = obj2;
}

The Ternary Operator
objOut = (obj1 != null) ? obj1 : obj2;


The Coalesce Operator Way
objOut = obj1 ?? obj2;


The Extended Coalesce Operator

The Conventional Way
if (obj1 != null)
{
return obj1;
}
else if (obj2 != null)
{
return obj2;
}
else if (obj3 != null)
{
return obj3;
}
else
{
return null;
}

The Coalesce Operator Way
return obj1 ?? obj2 ?? obj3;


As a useful replacement to the Ternary Operator

The Ternary Operator Way
obj = (obj != null)? obj : objNew;

The Coalesce Operator Way
obj = obj ?? objNew;


Then why is not used more? I think cos its got a tough name.[:)]
How do you pronounce it?

I LOVE C#
Read more...

Resolving W3C Validation Issues

1 comments
For those who are wondering why should one bother with W3C Validations,
please read Why should we Validate our WebSites?

When validating your website using W3C some weird errors might occur

An Example is


there is no attribute "border"



even if you haven't given the border attribute

The Reason


The ASP.NET engines sees the W3C validator as down-level browser and renders
non-XHTML compliant code. Your code is most likely fine. The problem is with
ASP.NET.




The Solution(Step Wise)


1.Right Click on your Solution Explorer
2.Click on Add ASP.NET Folder ---> App_Browsers
3.Now Click on App_Browsers ---> Add New Item
4.A dialog Box now pops up with some Visual Studio Installed Templates.
Select the Browser File Template from there, change the name as W3CValidations.browser(any other convenient name also) and Click on the Add Button
5.Delete the whole XML MarkUp code inside the W3CValidations.browser
6.Place the following code instead



<browsers>
<!--
Browser capability file for the w3c validator

sample UA: "W3C_Validator/1.305.2.148 libwww-perl/5.803"
-->
<browser id="w3cValidator" parentID="default">
<identification>
<userAgent match="^W3C_Validator" />
</identification>

<capture>
<userAgent match="^W3C_Validator/(?'version'(?'major'\d+)(?'minor'\.\d+)\w*).*" />
</capture>

<capabilities>
<capability name="browser" value="w3cValidator" />
<capability name="majorversion" value="${major}" />
<capability name="minorversion" value="${minor}" />
<capability name="version" value="${version}" />
<capability name="w3cdomversion" value="1.0" />
<capability name="xml" value="true" />
<capability name="tagWriter" value="System.Web.UI.HtmlTextWriter" />
</capabilities>
</browser>
</browsers>



7.Now upload this Folder and File to your Hosting Service
8.Re Validate using W3C Validator
9.Bingo! You got a Clean Validation Certificate.
10. Show off the Validation Certificate to all those who cares [:)]

Courtesy

Link at DigitalColony.com

Link at idunno.org


Happy Coding!
Read more...

Friday, August 8, 2008

Nested GridView with Paging for Child Grid

1 comments
I have a post called Nested GridView using JavaScript in this same blog.

A guy at ASP.NET Forums asked how to implement paging for the child grid and this is what made me make a post on this.

Just change the ASPX.CS like this.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            BindGridToDS(GridView1.DataKeys[e.Row.RowIndex].Value.ToString(), (GridView)e.Row.FindControl("GridView2"));
        }
    }


    protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView gvwChild = ((GridView)sender);
        GridViewRow gvRowParent = ((GridView)sender).Parent.Parent as GridViewRow;

        gvwChild.PageIndex = e.NewPageIndex;
        BindGridToDS(GridView1.DataKeys[gvRowParent.RowIndex].Value.ToString(), gvwChild);

        //show the div again after postback
        string strDIVID = "div" + GridView1.DataKeys[gvRowParent.RowIndex].Value.ToString();
        string cScript = "";
        ClientScript.RegisterStartupScript(typeof(Page), "clientscript", cScript);
    }

    private void BindGridToDS(string strCustomerID, GridView gv)
    {
        SqlDataSource dbSrc = new SqlDataSource();
        dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings["NorthWind"].ConnectionString;
        dbSrc.SelectCommand = "SELECT * FROM Orders WHERE CustomerID = '" + strCustomerID + "' ORDER BY OrderDate";
        gv.DataSource = dbSrc;
        gv.DataBind();
    }



Happy Coding!
Read more...

Tuesday, August 5, 2008

Display Images stored as Image in GridView

0 comments
Suppose we have a table in DB named "Images"
The data inside it are



img_id(int) ---> the id of the image
img_name(varchar(50)) ---> the name given to image
img_data(image) ---> the image stored as bit array
img_contenttype(varchar(20)) ---> like image/png, image/jpeg and all





Our requirement is to show the images in a GridView

Here's the ASPX

<asp:GridView ID="gvwImages" runat="server" 
AutoGenerateColumns="false" 
DataSourceID="dsImages">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%--field img_name is the name given to image--%>
<asp:Label ID="lblName" runat="server" 
Text='<%#Eval("img_name") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<%--here field img_id is the id of the image--%>
<asp:Image ID="Image1" runat="server" 
ImageUrl='<%# "Handler.ashx?id=" + Eval("img_id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="dsImages" runat="server" 
ConnectionString='<%$ConnectionStrings: your conn string %>'
SelectCommand="Select img_id,img_name from Images">
</asp:SqlDataSource>




Here inside ImageUrl we have given Handler.ashx.
Since we dont have one, create one.
Go to Add New Item. select Generic Handler and click OK.

Inside the Handler.ashx, paste this code

using System;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public class Handler : IHttpHandler
{

public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginCon"].ConnectionString);
myConnection.Open();
//here field img_data is the content of the image (type image in DB)
//field img_contenttype is the type of the image (optional)
string sql = "Select img_data,img_contenttype from Images where img_id=@ImageId";
SqlCommand cmd = new SqlCommand(sql, myConnection);
cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = context.Request.QueryString["id"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.ContentType = dr["img_contenttype"].ToString();
context.Response.BinaryWrite((byte[])dr["img_data"]);
}

}



Simple enough right?

Now if you wanna test it do it using Northwind DB.
Take the "Employees" table inside it and try to diplay the field "Photo"
10 out of 10, it wont work in your Page. [:)]
Suprised?
The reason is that the images stored in Northwind DB has OLE Header.
The header length is invariably 78 bytes.
So if we remove the first 78 bytes we can view images from Northwind too.

Here goes the special Handler.ashx for Northwind DB.(Table used ---> Employees)

using System;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public class Handler : IHttpHandler
{

public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString);
sqlConnection.Open();
string sql = " Select Photo from Employees where EmployeeID=@EmpId";
SqlCommand cmd = new SqlCommand(sql, sqlConnection);
cmd.Parameters.Add("@EmpId", SqlDbType.Int).Value = context.Request.QueryString["id"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
// Output the binary data
// But first we need to strip out the OLE header
byte[] thePicture = (byte[])dr["Photo"];
const int OleHeaderLength = 78;
int strippedImageLength = thePicture.Length - OleHeaderLength;
byte[] strippedImageData = new byte[strippedImageLength];
Array.Copy(thePicture, OleHeaderLength, strippedImageData, 0, strippedImageLength);
context.Response.BinaryWrite(strippedImageData);
// context.Response.BinaryWrite((byte[])dr["Photo"]);
}

}




Happy Coding!
Read more...