Monday, February 25, 2008

Validating a Telerik Combo Box at Client/Server side

Recently in one of my projects, i faced a challenge to validate the character set that can be input in to a Telerik Combo Box. Initially any invalid character that i entered such as "&lt" would cause the Combo box to crash, because such characters are illegal, and the crash comes because they are sent at the server side (ItemsRequsted Event).
I started on with my search but could not find anything conclusive that could do the job for me. In the end after going through their client API i found the function of my interest "OnClientItemsRequesting". This function has the ability to cancel the server side event if it returns false. So i wrote the following code in my aspx page.


<radC:RadComboBox ID="ComboBox" CausesValidation="false"
ExpandEffect="Stretch" AutoPostBack="false" runat="server"
EnableLoadOnDemand="True" Height="200px"
OnItemsRequested="RadComboBox1_ItemsRequested"
AllowCustomText
="true"
MarkFirstMatch="True" Width="230px" TabIndex="1"
OnClientItemsRequesting="ClearComboItems"
MaxLength="50"></radC:RadComboBox>
The ComboBox will now call the ClearComboItems function when OnClientItemsRequesting is fired. The definition for ClearComboItems is below

 function ClearComboItems(combobox)
{
badkeys=
new Array("&#x3C;", "%3c", "&#60", "%3C", "%3e",
"%3E", "%27", "&#x27;", "&#34", "&#38","&#39",
"&#60", "&#62", "&#x22", "&#x27", "&#x26",
"&#x3C", "&#x3E", "&quote;", "&apos;",
"~","@","#","$","^","&","*",":","!","`","&amp",
"&lt", "&gt", "\\u0022", "\\u0026", "\\u0027",
"\\u003c", "\\u003e", "select", "insert","update",
"delete", "drop", "having", "truncate", "union",
"--", "#", "%", "@@", "+","_","-","=","1","2","3","4",
"5","6","7","8","9","0", "1=1","exec", "alert", ";", "document",
"meta","iframe","html","script", "0x", "{","<", ">", "xp_",
"'1'='1'", "../", "./", ".exe", ".dll", "/*","*/", "waitfor",
"&#", "<<", ".config");
var val = combobox.GetText();
for (i=0; i<val.length; i++)
{
for (j=0; j<badkeys.length; j++)
{
if (val.indexOf(badkeys[j],i) == -1)
{
}
else
{
combobox.ClearSelection();
return false;
}
}
}
}
As we can see above, we have created an array badkeys and defined all the characters that have to be deprecated from being sent to the server. The return false argument does not let the sever side event to be fired and the illegal string are not passed to the server. To put in a place a check at the server you can add the same logic to the ComboBox_ItemsRequested event. This is shown below



 protected void RadComboBox1_ItemsRequested(object o, Telerik.WebControls.RadComboBoxItemsRequestedEventArgs e)
{
string key = ClearComboItems(e.Text.ToString());
}
public static string ClearComboItems(string strText)
    {
string[] badkeys = {"&#x3C;", "%3c", "&#60", "%3C",
"%3e", "%3E", "%27", "&#x27;", "&#34",
"&#38", "&#39", "&#60", "&#62", "&#x22", "&#x27", "&#x26",
"&#x3C", "&#x3E", "&quote;", "&apos;"
,
"~", "@", "#", "$", "^", "&", "*", ":", ".", "!","`",
"&amp", "&lt", "&gt", "\\u0022","\\u0026", "\\u0027",
"\\u003c", "\\u003e", "select", "insert", "update", "delete",
"drop", "having","truncate", "union", "--", "#", "%", "@@", "+",
"_", "-", "=","1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
"'", "1=1", "exec", "alert", ";","document", "meta", "iframe",
"html", "script", "0x", "{", "<", ">", "xp_", "'1'='1'", "../",
"./", ".exe", ".dll", "/*", "*/", "waitfor", "&#", "<<", ".config"};
for (int i = 0; i < strText.Length; i++)
{
for (int j = 0; j < badkeys.Length; j++)
{
strText = strText.Replace(badkeys[j],
"");
}
}
return strText.Trim();
}
To further strengthen the security of the Combo box you may also call the same function on "OnClientBlur". This will avoid copy pasting of illegal characters in the combo box.

I hope this helps..

Monday, February 11, 2008

Building a Photo Gallery in ASP.net 2.0 in 10 minutes

In this post i`ll show how easy it is to build a small and an efficient photo gallery using standard ASP.net controls.
Before we get started with the actual thing, lets visualize what all a photo gallery would have.

1) Its going to have a array of thumbnails splashed on the page.
2) The thumbnails would show an enlarged image when you click over them.
3) Last, but not the least, you`ll need pictures to flood the gallery. (Make a new folder, and place all the images you want to display as part of the photo gallery in it. Name the folder as "ImageFolder")

Now, lets consider the first point, ans try to build a design to design the thumbnails on the page. I felt that the "DataList" control would be a nice option. So lets go ahead and drag one to our webform. The code would look some what like the one shown below.

<asp:DataList ID="DataList2" runat="server"
RepeatColumns="5"></asp:DataList>

I have included the RepeatColumns="5" property so as to show five images in a row, you could set a value of your choice, depending on the design requirements.
Now you need to show images, and for that drag a HTML image tag from the toolbox and place it in side the of the DataList.
<asp:DataList ID="DataList2" runat="server" 
RepeatColumn
="5"><ItemTemplate>
<img src='<%# Container.DataItem %>
' border="0" title="Click to Enlarge"/></ItemTemplate>
</asp:DataList>

I have added <%# Container.DataItem %> statement, so as to pick the image paths from a dataset. I`ll cover this aspect later, so for the time, just let it be this way. For the time, thats all you require in the design part. Lets hit on to the code behind file to make the required changes.
On the Page load event write the following code.

string path = "ImageFolder/";
ArrayList pics =
new ArrayList();
foreach (
string
s in Directory.GetFiles(Server.MapPath(path), "*.jpg"))
{
string html = path + Path.GetFileName(s);
pics.Add(html);
}
DataList2.DataSource = pics;
DataList2.DataBind();

You need to add System.IO namespace to make the above code work. Now, when you run the project, you will see that the images are full size, and not exactly in the form of thumbnails. So, the next task at hand is to generate thumbnails for the images. There are two ways to achieve the objective.

1) To generate thumbnail images on the fly
2) Bind the datalist to the a folder with thumbnail images itself.

To achieve the objective using option 1 you need to change the HTML, particularly the image tag in the datalist. Here`s how it will look.
<img src='Makethumbnail.aspx?file=
<%# Container.DataItem %>' border="0"
title="
Click to Enlarge"/>

Notice the statement "Makethumbnail.aspx?file=". You`d feel, that how could a standard aspx file be a source of an image. In this case it is, and this is what is going to help us in creating a thumbnail. So, add a new webform by the name of Makethumbnail.aspx, and go to the codebehind. Just paste the code as i have written below.
string file = Request.QueryString["file"];
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(file));
System.Drawing.Image thumbnailImage = image.GetThumbnailImage(
75, 71, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
MemoryStream imageStream =
new MemoryStream();
thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageContent = new Byte[imageStream.Length];
imageStream.Position =
0;
imageStream.Read(imageContent,
0, (int)imageStream.Length);
Response.ContentType =
"image/gif";
Response.BinaryWrite(imageContent);


Now paste this code outside the page load
public bool ThumbnailCallback()
{
return true;
}

You will now find after compiling your project, that thumbnails now appear in place. You`ll notice that the images appear to be shrunk, and lose points on quality. So, to compensate for the same, you can go in to bind thumbnail images itself to the data list. But, do take note, that thumbnails would score on the basis of performance, as the size would be drastically low, compared to a high quality thumbnail. Finally, the choice is yours.

After completing our first objective, lets go and add some interactivity. To make the image clickable, you will to add a hyperlink, and a corresponding URL. Now our code would look something like this

<asp:HyperLink ID="HyperLink1"
runat="server" rel="lightbox[roadtrip]"
NavigateUrl='<%# Container.DataItem %>'
ToolTip="
Press left or right arrow keys to navigate">
<img src='Makethumbnail.aspx?file=
<
%# Container.DataItem %>' border="0"
title="
Click to Enlarge"/>
</asp:HyperLink>

The above code makes the image clickable and adds the animation, courtesy the Lightbox JS . You will need the lightbox files, to get them click here. Finally run your project, and click on one of the images. You will see how the images pop up at the center of the screen with really professional effects. You can also navigate across your images by pressing the left/right arrow keys, or clicking on the left/right end of the images.

This completes the photo gallery sample. You can alter the model to your needs, by changing a few variables. I hope this helps in accomplishing your task....