How to encrypt a query string ?

Few months back I had used a nice component from TSHAK to encrypt query strings. it requires just one line of code to encrypt a query string. Right now I am unable to find the exact page at TSHAK where I got the control. Due to a site re organization at TSHAK , they might have moved it to some other place. You can download the component here and place it in your bin folder.

To encrypt a query string we will need to pass it an encryption key which is a byte array

Dim qs As TSHAK.Components.SecureQueryString
qs = New TSHAK.Components.SecureQueryString(New Byte() {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 8})

To add the query string values
qs("Myname")="John"
qs("MyAge")=5
Response.Redirect("Page2.aspx?data=" + HttpUtility.UrlEncode(qs.ToString()))

Now to decrypt and use the values in Page2.aspx
Dim qs As TSHAK.Components.SecureQueryString
qs= New TSHAK.Components.SecureQueryString(New Byte() {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 8}, Request("data"))
Dim myName=qs("MyName")
Dim age=qs("MyAge")

kick it on DotNetKicks.com

Get the IP Address and Referer of a visitor

Here is the code snippet to obtain the IP Address and Referer of a visitor to your website

Dim IPAddress=Request.ServerVariables("REMOTE_ADDR")
Dim Referer=Request.ServerVariables("HTTP_REFERER")

Check a demo here

Check my IP

WidgetBucks $25 sign up bonus is back

If you are looking to monetize your website and haven’t signed up with widgetbucks yet, It’s a good time now, as they are giving out a $25 sign up bonus . Widgetbucks is an ad network which pays in both CPC (per click) and CPM (per 1000 impression) basis. The payout is low at $50 and payment is through paypal. The ads are pretty, well designed and can give your dull blogs a colourful new life besides the handsome CPM rates. However widgetbucks seems best if your website primary targets US visitors, for non US visitors the rates seems to be less than average. However, try it for yourself and take home $25 too. Sign up here

Replace “\n” with “<BR\>”

There are lot of times we accept user input in a textarea or a multiline textbox and save it to a database. But while displaying the data from the database, you will find that the line breaks are not displayed properly, infact there will be no line breaks. We will need to convert all the new line characters (”\n” character) to “<BR/>” so that they are properly rendered in the browser. There seems to be quite a few ways to do it but the simplest method which always worked for me is as follows. Just pass the string to the the function and it will format the string properly so that the new line characters are replaced with “<Br/>” tags

Public Shared Function ConvertToBR(ByVal InputString As String) As String
Dim Pattern As String = "\n"
Dim Rgx As New Regex(Pattern)
Dim OutputString As String=Rgx.Replace(InputString, "<br/>")
Return OutputString
End Function

Efficient Search Engine Friendly Gridview Paging control

The Gridview Control in ASP.NET has built in paging support. But here are a few disadvantages of using the built in paging

  • It fetches all the records from the database even when we need only 10 records per page. This is quite inefficient when your tables have thousands of records
  • The paging controls uses javascript which makes the pages inaccessible to search engine.

I looked around the net for solutions to these problems. There were a few solutions and some of them even costs upwards of $100 but the best I found was a free paging control by Bidel Akbari at codeproject

Here are the main features of his paging control

  • Very easy to install and use.
  • Uses server side paging so that only the required few rows are returned from the database
  • Search engine friendly paging. The first version was supposed to use query strings for paging which is the way paging should work. However in the latest version 2.8 , it uses javascript for paging and a hidden div with hyperinks so that search engines can find the inner pages.
  • You can use the paging control with the Repeater and Datalist controls
  • There are a variety of properties to change the appearance of the control. He has also made two slick skins for the control

Overall a great and extremely useful control . You can see a demo of the control here in my site freedownloadablefonts.net . You can find more info and download the control here

Free ASP.NET Web Hosting Providers

There seems to be quite a few people asking whether there are any web hosts providing free asp.net hosting . I did a bit of research and came up with a few good free hosting providers. The good thing about all the free web hosts is that they no longer serve forced ads. A few of them even support SQL Server Express 2005 and almost all of them allow FTP access for easy file transfer. But do remember that all them will require that you have a domain name. Domain name can be registered at Godaddy.com or any registrar that you prefer.

Host Space Bandwidth .NET Version Database Comments
ChristianASP 250 MB 2,000 MB 3.5 SQL Express 2005 No catch. Free web hosting
ASPSpider 100 MB 2,500 MB 3.5 SQL Express 2005 Limited Numbers
Laneware 30 MB 2,500 MB 3.5 MS Access Accounts automatically disabled after 4 months
ASPHost4Free 100 MB Unlimited ASP MS Access Only ASP for now. But .Net Beta hosting is out now
Quantasoft 100 MB 2,000 MB 3.5 SQL Express 2005 Good features

If anyone knows any more good free asp.net web hosting solutions , we may add them to the list.
Also if you are looking for paid asp.net web hosting, you may want to take a look at our sponsors Lunarpages Web Hosting . They are providing one free domain and 3 month of free hosting
kick it on DotNetKicks.com

Loading and previewing fonts from files in ASP.NET

Few weeks back I created a free fonts preview and download site www.freedownloadablefonts.net. There are around 6000 fonts in .ttf files and I needed to display a preview of the fonts. All the fonts were copied to a folder “~/Fonts”. Then I created a http handler “GetFontImage.ashx” to which the font path and text to display was passed as query strings . It created an image using the font specified. The code for “GetFontImage.ashx” is as follows

<%@ WebHandler Language="VB" Class="GetFontImage" %>
Imports System
Imports System.Web
Public Class GetFontImage : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "image/png"
Dim fontpath As String = context.Request.QueryString("fontpath")
Dim Text As String = context.Request.QueryString("Text")
Dim FontImage As System.Drawing.Bitmap = clsUtility.GetFontPic(fontpath, Text)
Dim ms As IO.MemoryStream = New IO.MemoryStream()
FontImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
Dim FontImageBytes() As Byte = ms.GetBuffer()
FontImage.Dispose()
ms.Close()
context.Response.BinaryWrite(FontImageBytes)
context.Response.End()
End Sub
End Class

GetFontImage.ashx calls another function clsUtility.GetFontPic(fontpath, Text) whose code is as follows. clsUtility.GetFontPic(fontpath, Text) uses the privatefontcollection class to load the font from file

Imports Microsoft.VisualBasic
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Text
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D
Public Class clsUtility
Public Shared Function GetFontPic(ByVal Fontpath As String, ByVal Text As String) As System.Drawing.Bitmap
Dim width As Integer = 620
Dim height As Integer = 30
Dim FontImage As New System.Drawing.Bitmap(width, height, PixelFormat.Format24bppRgb)
Dim g As Graphics = Graphics.FromImage(FontImage)
g.Clear(Color.White)
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias
g.SmoothingMode = SmoothingMode.AntiAlias
Dim pointF As New PointF(10,0)
Dim FontSize As Integer = 24
Dim solidBrush As New SolidBrush(Color.Black)
Dim privateFontCollection As New PrivateFontCollection()
privateFontCollection.AddFontFile(Fontpath) ' load font from file
Dim thisFont As FontFamily = privateFontCollection.Families(0)
Dim regFont As New Font(thisFont, FontSize, FontStyle.Regular, GraphicsUnit.Pixel) ' Create a new font
g.DrawString(Text, regFont, solidBrush, pointF) ' Using the font write the text using the font style
Return FontImage
End Function

All the font information were stored in a database in a table with the following columns
1. FontID
2. FontName
3. Path
4. AddedDate
A script can be easily created to add all the font information to the table using the privatefontcolection class as above
The home page displays the 10 latest fonts in a gridview. The code is as folows
Default.aspx

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="FontID" DataSourceID="SqlDataSourceFonts" ShowHeader="False" Width="100%" GridLines="None" BorderStyle=None BorderWidth="0">
<Columns>
<asp:TemplateField ItemStyle-BackColor="White" HeaderText="Image" ItemStyle-BorderWidth="0"> <ItemTemplate>
<asp:Image AlternateText='<%# Eval("FontName") %>' ImageUrl='<%# GetImageURL(Eval("path"),Eval("FontName")) %> ' ID="FontImage" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceFonts" runat="server" ConnectionString="<%$ ConnectionStrings:FontsConnectionString %>"
SelectCommand="SELECT TOP 10 * FROM [Fonts_Fonts] ORDER BY [AddedDate] DESC”>

The code is pretty straight forward with a Gridview bound to an SQLDatasource. The code for GetImageURL() is as follows
Default.aspx.vb

Public Function GetImageURL(ByVal Path As String, ByVal FontName As String)
Return "GetFontImage.ashx?FontPath=" & Server.MapPath(Path) & "&Text=" & FontName
End Function

kick it on DotNetKicks.com

Check Page Rank of all pages of a website quickly

The most recent Google Page Rank (PR) update happened some days ago and most of us might have checked our websites PR using the google toolbar or through the numerous websites which can display PR ( one of my favourites being http://www.digpagerank.com/ ) . Though the PR toolbar and most “check PR” websites can display the PR of individual pages, it is quite cumbersome when you want to know the Page Rank of all the pages in a website . A quick way of finding the PR of all the websites is by using this SEO plugin for firefox . After installing the plugin, and restarting firefox , go to Tools->Add-Ons .. This will list all the add-ons , look for the SEO plugin and click on options. From the options menus for PR select “Automatic” as seen in the screen below

Change options

Now go to www.Google.com and in the search box type site:www.yourdomainname
For eg typing site:www.LittleStarDimapur.com gave me the following result

Check PR of all pages

As you can see all the internal pages PR is displayed . The plug-in also has a lot of other options which gives plenty of information like yahoo backlinks, DMOZ listing, etc.

Fixing postbacks while using URLRewriter.net

Last week I had done a post on how to rewrite URLs using the URLRewriter.Net component. You can read it here . Another issue that comes up while using URL rewriting in ASP.NET is the problem of postbacks. Whenever a postback occurs in the page, you find that after the postback the URL in the address bar of the browser shows your ugly URL again which you were trying so hard to hide . You can test it out here in my website Christian-Jokes.net (I’ll be fixing it soon though ). Go to any joke and check the URL in your browser . You will see the friendly URL. Now write down a short comment for the joke and submit the comment. After the comment is submitted, you see that the URL in the browser has changed to something like this “ShowJoke.aspx?JokeID=123″ .

Thankfully, again the the guys at URLrewriter.Net has a simple solution for us, though it took me some time to find it . Add the following code at the top of your page

<%@ Register TagPrefix="url" Namespace="Intelligencia.UrlRewriter"
Assembly="Intelligencia.UrlRewriter" %>

and then change your form tag from <asp:form runat=”server”> to <url:form runat=”server”>

If you are using master pages, you will most probably add the above lines in your master page file

Check your webpage and postbacks and URL rewriting should be working fine now !
kick it on DotNetKicks.com

Caching a dataset for improving performance in ASP.NET

In a website that I recently completed www.Christian-Jokes.net the left navigation bar listed the categories of jokes from the database. So on every page load I was querying the database to load the categories. Obviously this was a bad idea. I needed to cache the categories in memory without querying the database on every page load. The categories were placed in the master page. In the master page page load event I wrote the following code to cache the categories of jokes

Dim JokeCategories As Data.DataSet
JokeCategories = Cache("JokeCategories")
If JokeCategories Is Nothing Then
JokeCategories = GetJokeCategories()'This fn returns the categories
Cache.Insert("JokeCategories", JokeCategories, Nothing, DateAdd(DateInterval.Minute, 180, Now()), Web.Caching.Cache.NoSlidingExpiration)
End If
RepeaterJokecategories.datasource=Jokecategories RepeaterJokeCategories.Databind()

Just 5 lines of code and a great boost in performance !

Now the categories are loaded from the database only if they are not present in the cache. Once loaded the categories are placed in the cache for 180 minutes