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 !

October 1st, 2008 | Posted in Tutorials | 10 Comments
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
September 20th, 2008 | Posted in Tutorials | 1 Comment
Friendly URLs have become necessary to obtain better rankings in Search engines. The improvement in rankings may not be huge but because of the burgeoning of websites in almost every niche we need to use every single advantage that we can get. Friendly URLs are URLS without a query sting or without the “?” character. Friendly URLs have a URL structure which look like static pages instead of dynamic pages.
Unfriendly URL : “www.MyShop.com/ShowProduct.aspx?ProductID=1
Friendly URL : “www.MyShop.com/Monitors/Samsung-Syncmaster.aspx
The absence of a good, built in URL rewriting solution in ASP.NET makes it difficut to implement friendly URLs in dynamic pages. The only type of URL rewriting available in ASP.NET can be used only for small websites with a few pages since we need to have a rule for each page. The following is an example of URL rewriting which can be done in the web.config file
<system.web>
<urlMappings enabled="true">
<add
url="~/Clubs/Computer Club.aspx"
mappedUrl="~/ShowPage.aspx?PageID=1" />
<add
url="~/Clubs/Eco Club.aspx"
mappedUrl="~/ShowPage.aspx?PageID=2" />
</urlMappings >
</system.web>
You can easily see that a website with even a fairly large number of pages can become difficult to maintain. Adding or deleting of pages will also require the web.cong file to be modified. This is a tedious solution and certainly not suitable for medium to large dynamic sites.
The guys at URLRewriter.NET have made a very useful URL Rewriting component . The best thing about it is that it is very simple to implement and it works in a shared hosting environment. All you have to do is download the dll file and copy it to your bin directory. Add a few lines in your web.config file as follows.
<configSections>
<section name="rewriter"
requirePermission="false"
type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
</configSections>
<system.web>
<httpModules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter"/>
</httpModules>
</system.web>
Now you will have to define the rules in your web.config file
An example of a rule is as follows
<rewriter>
<rewrite url = "~/Products/([^/.]+)\.aspx” to=”~/ListProducts.aspx?Category=$1″ />
<rewrite url = “~/Products/(.+)/([0-9]+)-(.+).aspx” to=”~/ShowProduct.aspx?ProductName=$2&ProductID=$1″ />
</rewriter>
According to the the first rule “~/Products/Monitors.aspx” will be rewritten as “~/ListProducts.aspx?Category=Monitors”
According to the second rule “~/Products/Monitors/3-Samsung940BW.aspx” will be rewritten as “~/ShowProduct.aspx?ProductName=Samsung940BW&ProductID=3”
Thus now you can use the friendly URLS instead of the URLs with query strings. It’s simple as that !
After using URLRewrite.NET , I had noticed a major bug. The bug is not in the component but with ASP.NET URL rewriting itself. All the pages using URL Rewriting do not get indexed by Google, this happens for both the built in URL rewriting and URLRewriter.NET component. Google bots cannot crawl pages which use Rewriting. It gives an error “Network unreachable” . This is a major problem for websites which depend on search engine traffic and almost all websites do.
After searching around a lot , I found a solution . The solution is to create a file name “genericmozilla5.browser” under the “App_Browsers” Directory in your root directory. Type in the following in the file
<browsers>
<browser id="GenericMozilla5" parentID="Mozilla">
<identification>
<userAgent match="Mozilla/5\.(?'minor'\d+).*[C|c]ompatible; ?(?’browser’.+); ?\+?(http://.+)\)” />
</identification>
<capabilities>
<capability name=”majorversion” value=”5″ />
<capability name=”minorversion” value=”${minor}” />
<capability name=”browser” value=”${browser}” />
<capability name=”Version” value=”5.${minor}” />
<capability name=”activexcontrols” value=”true” />
<capability name=”backgroundsounds” value=”true” />
<capability name=”cookies” value=”true” />
<capability name=”css1″ value=”true” />
<capability name=”css2″ value=”true” />
<capability name=”ecmascriptversion” value=”1.2″ />
<capability name=”frames” value=”true” />
<capability name=”javaapplets” value=”true” />
<capability name=”javascript” value=”true” />
<capability name=”jscriptversion” value=”5.0″ />
<capability name=”supportsCallback” value=”true” />
<capability name=”supportsFileUpload” value=”true” />
<capability name=”supportsMultilineTextBoxDisplay” value=”true” />
<capability name=”supportsMaintainScrollPositionOnPostback” value=”true” />
<capability name=”supportsVCard” value=”true” />
<capability name=”supportsXmlHttp” value=”true” />
<capability name=”tables” value=”true” />
<capability name=”vbscript” value=”true” />
<capability name=”w3cdomversion” value=”1.0″ />
<capability name=”xml” value=”true” />
<capability name=”tagwriter” value=”System.Web.UI.HtmlTextWriter” />
</capabilities>
</browser>
</browsers>
This solved the problem for me.
Update :
Also check my post on fixing postbacks while using URLRewriter.net
September 5th, 2008 | Posted in Tutorials | 54 Comments
For those who do not want to mess with PHP code .
Here is an easy way to add Google Analytics in wordpress.
1. Download the plug in from http://yoast.com/wordpress/google-analytics/
2. copy it to your plug ins folder
3. If you already don’t have an account, create one free account at www.google.com/analytics
4. Add your website. After you add your website in google analytics , you will be given some code like below
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-52211906-3“);
pageTracker._trackPageview();
</script>
The string in red color is your User Account String. You will need to input this string in the plug-in while setting it up.

That’s all , now you can see detailed traffic reports of your wordpress blog in your google analytics account
August 28th, 2008 | Posted in Wordpress | 5 Comments
Suppose you have a label control name lblMessage in your masterpage and you want to access the label control from one of your pages, you can do so using the following code
Ctype( Page.Master.FindControl("lblMessage"),Label).Text = "Hello"
August 25th, 2008 | Posted in Code snippets | 1 Comment
Many people have problems inserting flash files in masterpages . The following code is the correct way of inserting flash file in a mastepage . It will work in all situations
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase= "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0” width=”663″ height=”105″ title=”Serious Reading….”>
<param name=”movie” value=’<%= Request.ApplicationPath + “main_anim.swf” %>’
<param name=”quality” value=”high” />
<embed src=’<%= Request.ApplicationPath + “main_anim.swf” %>’ pluginspage=”http://www.macromedia.com/go/getflashplayer” type=”application/x-shockwave-flash” width=”663″ height=”105″></embed>
</object>
August 25th, 2008 | Posted in Code snippets | 6 Comments
Here are a few basic tips for on page search engine optimisation that i try to implement in all my websites.
1. The page title gets top priority. It should be short. Only your main keywords should be in the title. Eliminated all unwanted words. Replace the word “and” with | so that you can save some characters. For example ” Read funny jokes here ” can be replaced with just “Funny jokes”. Stuffing too many keywords in the title can be counter productive. Keep only your main keywords there.
2. After the title , in the page content , the first line should be the heading of the page enclosed in
<h1> tags. Be sure to put one keyword in your heading too. Next you can have a sub heading<h1>
<h2> where you can place another keyword. In the content of the page you can bold and italicize some of the keywords that you are aiming for. Do not overdo it however.
3. Have an alt attribute for all your image tags. You can put another keyword in the alt attribute of the image too. Again keep the alt text short.
4. At last in the footer of your page, end it with another keyword !
Copyright © Funny Jokes everyday.
5. Use Meta tags . the META description is important as the META description appears just below the link to your website when someone does a Google search. If you do not include a META description Google selects some text frm your content and displays it which most of the time is not satisfactory . People are going to read the description and decide whether to click the link to your website or not. So make sure your description contains useful info which will encourage the users to click on your link. The length of the META description should be around 120 -180 characters.
August 25th, 2008 | Posted in SEO, Tutorials | No Comments
To format a gridview column to display dates properly , two properties needs to be changed, the DateFormatString property and the HTML encode property. After setting the DateFormatString the HTMLEncode property should be set to false. For Example :
<asp:BoundField DataField="RegistrationDate" DataFormatString="{0:MM/dd/yyyy}" HeaderText="Date"
HtmlEncode="False" SortExpression="RegistrationDate" />
August 25th, 2008 | Posted in Code snippets | No Comments
In some scenarios you may only want users of a particular role to delete records from the GridView. So you need a mechanism to disable/hide the delete link in the gridview based on roles. The code below will enable the delete link only for “Admin” roles and disable it for the rest.
Protected Sub gridView1_RowDataBound(ByVal sender As Object, ByVal e As system.Web.UI.WebControls.GridViewRowEventArgs) Handles Gridview1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If User.IsInRole("Admin") Then
Dim DeleteLink As LinkButton = CType(e.Row.FindControl("HyperLinkDelete"), LinkButton)
DeleteLink.Enabled = true
else
DeleteLink.Enabled = True
End If
End If
End Sub
August 25th, 2008 | Posted in Code snippets | No Comments
Most web hosts provide more mySQL databases than SQl Server 2005 database. To keep your hosting costs low , you might need to use MySQL in your projects.
To connect to MySQL database
First download the drivers here
Then copy MySql.Data .dll and MySql.Web.dll to your bin directory
The connection string is as follows
<add name="ASPNETDBConnectionString" connectionString = "Server=localhost;User ID=youruserID; Password=yourpassword; Database=databasename"
providerName="MySql.Data.MySqlClient" />
The MySQl Connector 5.2 has built in support for membership provider too. So from inside Visual Studio you can use the ASP.NET configuration to automatically generate the membership schema
August 25th, 2008 | Posted in Tutorials | No Comments