How to fetch Last Record in Subsonic

Is it just me or is Subsonic the topic of discussion right now? :D
I had a need to retrieve the last ID that had been generated in a table; that being, the last “auto increment” ID of a table.

The following example worked a charm using Subsonic and activerecord.

var fetch_ref_id = contract.All().OrderByDescending(c =>;
if (iRef_new_id != null)
     iRef_new_id = fetch_ref_id[0].id;

As you can see, it creates a new list (noted by the ToList()) by connecting to the table “category”, it then selects all results (All()) and then orders the list by Descending and finally, the take(1) simply takes the top record.

I then whack the result (if you have a column called id) into a integer.

Subsonic ordering – OrderByDescending

So the subsonic documentation sucks. If you’re new to activerecord, linq and subsonic in general; you’ll find it fairly hard to construct basic queries. However once you’ve got it under control, it’s a piece of cake.

To sort your table using activerecord, use the following examples;

To sort ascending by a column called name

var categories = category.All().OrderBy(c =>;

To sort descendingby a column called name

var categories = category.All().OrderByDescending(c =>;

You can then just bind to your gridview/dropdown list or whatever you like.

            if (categories != null)
                drp.DataSource = categories ;

SubSonic 3.0 ActiveRecord Tutorial

I wanted to demonstrate the complete and utter power of SubSonic Activerecord’s toolset. Pretty much, its an easy to use querying engine which automatically creates objects that you can use within your ASP.NET project. You can use LINQ querying if you like, or you can use the SubSonic preferred way as demonstrated below;

Want to bind a gridview?

var categories = category.All();
gvList.DataSource = categories;

Boom. Done.

<pre lang="csharp" line="1">
int iLineID = 1;
category delCat = category.SingleOrDefault(x => == iLineID);

Too easy right?

What about adding a new record?

category newCat = new category(); = "Dummy category name";

How easy is that? Go grab SubSonic now!

ASP.NET & AlternatingRowStyle & IE8

If you’re a ASP.NET developer like myself, you may or may not have noticed a few changes to your sites when viewed in Internet Explorer 8.

As an example I had a gridview which had a different background for alternating rows.

<AlternatingRowStyle CssClass="odd" /></code>

And my CSS was something like

.odd { background-image: url(../graphics/tealbg.gif); }

The Solution

The easy (and maybe a little messy) way to solve this is to force the page to use IE7 compatibility. You can do this by adding the following to your tag.

<meta http-equiv="X-UA-Compatible" content="IE=7" />

Note: The above meta tag MUST appear before any link tags (stylesheet includes for example)

ASP.NETs Forms Based Authentication

Websites that offer membership based services often require their important files to be secured from non-members. For this purpose, they need to implement form based authentication that ensures that only members can access the files and even if a non-member copies the exact location of the file on the server, he/she is denied access to the file and redirected back to the login page. Let’s check it out.

1. If you are using an IDE then you need to create a new project and add a LoginPage.aspx page. Switch to html view and add the following code inside the tag of you LoginPage.aspx page.

<h2> <font face="Times New Roman">Login Credentials</font> </h2>
<table> <tr>
<td>User Name :</td>
<td><input id="CUserName" type="text" runat="server" NAME="CUserName"></td>
<td><ASP:RequiredFieldValidator ControlToValidate="CUserName" Display="Static" ErrorMessage="*" runat="server" ID="VUserName" /></td></tr>
<td><input id="CUserPass" type="password" runat="server" NAME="CUserPass"></td>
<td><ASP:RequiredFieldValidator ControlToValidate="CUserPass" Display="Static" ErrorMessage="*" runat="server" ID="VUserPass" /></td> </tr>
<input type="submit" Value="Login" runat="server" ID="cmdLogin" NAME="cmdLogin">
<asp:Label id="lblMsg" ForeColor="red" FontName="Times New Roman" FontSize="12" runat="server"/>

2. Now, change the authentication in your web.config file to and modify the authentication parameters as given below:

<allow users="*" />
<deny users="?" />

3. Now, browse the virtual directory in Internet Information Services (IIS), right click on it to access the properties. Move to security tab & click on edit to check Anonymous access option.

4. On your IDE change the view mode to code view for the LoginPage.aspx page and add the following code to it. Refer to Point 4 of Code Event Handler at

Provide your own coding for authenticating the username & password

if CUserName.Value = "AAAAAAA" and CUserPass.Value = "BBBBBBBB" Then
FormsAuthentication.RedirectFromLoginPage(CUserName.Value , True)
Response.Redirect("LoginPage.aspx" , True)
End if
End Sub

5. Create a new page and name it as DefaultPage.aspx and add the following to the html view of the page.

<table border="0">
<td><-asp:Button id="SendFile" runat="server" Text="Send File"></asp:Button></td>

Now, switch to code view for this page & add the following lines

Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button.Click FormsAuthentication.SignOut()
Response.Redirect("LoginPage.aspx" , True)
End Sub
Private Sub SendFile_Click( ByVal sender As System.Object , ByVal e As System.EventArgs ) Handles SendFile.Click
Response.ContentType = "application/msword"
Response.TransmitFile("SecuredFolderAnyFile.doc") ‘Create a SecuredFolder in Virtual Directory & add “AnyFile.doc” to it
End Sub

Why I used a button instead of a hyperlink is because in case of hyperlink the file will be cached and even if you change the contents of the file, the old file will be displayed. A button will prevent this.

6. Protect the SecuredFolder and ensure that you have granted the READ permission to the Network service or ASPNET. Run your project and try what happens when you try to paste the url of the file and then access it. You will notice a Login page instead of the file.

The GridView fired event PageIndexChanging which wasn’t handled

If you’ve set a gridviews AllowPaging attribute to “true”, you’ll notice the following error;

The GridView fired event PageIndexChanging which wasn’t handled

To setup paging with Gridviews, you also need to set the page index property to the new page that you wish to view. Funny enough, this is extremely easy to do. See below for a code example written in C#.

The ASPX page

<asp:GridView ID="gvList" runat="server" AutoGenerateColumns="true" AllowPaging="true" PageSize="10" OnPageIndexChanging="gvList_PageIndexChanging">

and the C# code

    protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)

        gvList.PageIndex = e.NewPageIndex;

Hiding Details view after update

I had the need to hide a detailsview after an update. Forget using visible=false, this just hides it permanently!

Try setting the datagrid selectedindex = -1

        protected void dvDetailsView_Updated(Object sender, System.Web.UI.WebControls.DetailsViewUpdatedEventArgs e)
            gvGridview.SelectedIndex = -1;

Weird scrolling issue with Modalpopupextender

Are you ripping your hair out over a issue with the AJAX modalpopupextender and a never-ending scrollbar?!? I had a panel with a style=absolute in the style= tag, causing the popup to show in the middle of the page. But for some reason, the page went wonky and I could scroll endlessly!

Here’s the fix;

I changed this

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"

to this

!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""

and my pain ended.

Using Windows Authentication under IIS7 (ASP.NET)

Okay so I took me a few hours but I finally figured out how to turn on Windows Authentication under IIS7. For some reason, it’s turned off by default and in IIS7 under authentication you’ll only see anonymous.

I have a ASP.NET 1.1 application that requires Windows Authentication and this was the error I was receiving.

“You do not have permission to view this directory or page using the credentials you supplied”

  1. Whip open the control panel, and select programs and features
  2. On the left select “Turn Windows Features on or off”
  3. Drill down to “Internet Information Services” – “World Wide Web” services” – “Security” – “Windows Authentication”
  4. Tick “Windows Authentication”

My gosh, hidden away eh?
I love Windows Vista.

Check all function for Datagrids

I had the need to create a datagrid check all function, similar to those that you see in yahoo, gmail, hotmail etc.

My Datagrid looked like this;

<asp:datagrid id="dgList" Runat="server" width="600px" AutoGenerateColumns="False">
			<asp:CheckBox ID="chkAll" onclick="javascript:jsSelectAll('dgList','dgList__ctl1_chkAll');" runat="server" ToolTip="Select/Deselect All" AutoPostBack="false" />
			<asp:CheckBox ID="chkSelect" Runat="server"></asp:CheckBox>
	<asp:BoundColumn DataField="col1" HeaderText="col1"></asp:BoundColumn>
	<asp:BoundColumn DataField="col2" HeaderText="col2"></asp:BoundColumn>

With the datagrid code above, make sure you modify the jsSelectAll parameters!
1st var: The name of your datagrid (In my example, dgList)
2nd var: The name of your check all checkbox

I used a javascript function that loops through all the checkboxes within the datagrid and selects/de-selects.

function jsSelectAll(datagridID, checkallID)
	var obj = document.getElementById(datagridID).all.tags("input");
	var blCheck = true;
	var chk = document.getElementById(checkallID); 
	if (chk.checked == true)
	for (var i=0; i<obj.length; i++){
		if (obj[i].type == "checkbox"){
			obj[i].checked = blCheck;

NullableTypes Access is denied

I came across a problem where everytime I recompiled my C# ASP.NET project and visited the website; it would report the following error.

Exception Details: System.IO.FileLoadException: Access is denied: 'NullableTypes'

I asked the developers for a fix and they came through with a quick and easy solution.

First you must check that the ASPNET user (most likely NETWORK SERVICE) has access to your project folder and also the “C:/WINDOWS/Microsoft.NET/Framework/v1.1.4322/Temporary” folder.

If that doesn’t work (like in my case), download the NullableTypes 1.3 beta and drag and drop the DLL into your C:/WINDOWS/Assemby folder. This did the trick for me!

Adding sorting ability to a repeater control

This code snippet shows you how to sort a repeater web form control. This is handy when you are using scrollable repeater tables.

DataView dv = ds.Tables[0].DefaultView;
dv.Sort = "firstname asc";
rptUsers.DataSource = dv;

« Previous Entries